SemaExpr.cpp 592 KB
Newer Older
1
2
3
4
//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
//
//                     The LLVM Compiler Infrastructure
//
5
6
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
7
8
9
10
11
12
13
//
//===----------------------------------------------------------------------===//
//
//  This file implements semantic analysis for expressions.
//
//===----------------------------------------------------------------------===//

14
#include "TreeTransform.h"
15
#include "clang/AST/ASTConsumer.h"
16
#include "clang/AST/ASTContext.h"
17
#include "clang/AST/ASTLambda.h"
18
#include "clang/AST/ASTMutationListener.h"
19
#include "clang/AST/CXXInheritance.h"
Daniel Dunbar's avatar
Daniel Dunbar committed
20
#include "clang/AST/DeclObjC.h"
21
#include "clang/AST/DeclTemplate.h"
22
#include "clang/AST/EvaluatedExprVisitor.h"
23
#include "clang/AST/Expr.h"
24
#include "clang/AST/ExprCXX.h"
25
#include "clang/AST/ExprObjC.h"
26
#include "clang/AST/ExprOpenMP.h"
27
#include "clang/AST/RecursiveASTVisitor.h"
28
#include "clang/AST/TypeLoc.h"
29
#include "clang/Basic/PartialDiagnostic.h"
30
31
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
32
33
#include "clang/Lex/LiteralSupport.h"
#include "clang/Lex/Preprocessor.h"
34
#include "clang/Sema/AnalysisBasedWarnings.h"
35
#include "clang/Sema/DeclSpec.h"
36
#include "clang/Sema/DelayedDiagnostic.h"
37
#include "clang/Sema/Designator.h"
38
39
40
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/ParsedTemplate.h"
41
#include "clang/Sema/Scope.h"
42
#include "clang/Sema/ScopeInfo.h"
43
#include "clang/Sema/SemaFixItUtils.h"
Mehdi Amini's avatar
Mehdi Amini committed
44
#include "clang/Sema/SemaInternal.h"
45
#include "clang/Sema/Template.h"
46
#include "llvm/Support/ConvertUTF.h"
47
using namespace clang;
48
using namespace sema;
49

50
51
/// \brief Determine whether the use of this declaration is valid, without
/// emitting diagnostics.
52
bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53
54
55
56
57
58
59
60
  // See if this is an auto-typed variable whose initializer we are parsing.
  if (ParsingInitForAutoVars.count(D))
    return false;

  // See if this is a deleted function.
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    if (FD->isDeleted())
      return false;
61
62
63

    // If the function has a deduced return type, and we can't deduce it,
    // then we can't use it either.
Aaron Ballman's avatar
Aaron Ballman committed
64
    if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65
        DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66
      return false;
67
  }
68
69

  // See if this function is unavailable.
70
  if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71
72
73
      cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
    return false;

74
75
  return true;
}
76

77
78
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  // Warn if this is used but marked unused.
79
80
81
82
83
84
85
86
  if (const auto *A = D->getAttr<UnusedAttr>()) {
    // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
    // should diagnose them.
    if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
      const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
      if (DC && !DC->hasAttr<UnusedAttr>())
        S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
    }
87
88
89
  }
}

Nico Weber's avatar
Nico Weber committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
  const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
  if (!OMD)
    return false;
  const ObjCInterfaceDecl *OID = OMD->getClassInterface();
  if (!OID)
    return false;

  for (const ObjCCategoryDecl *Cat : OID->visible_categories())
    if (ObjCMethodDecl *CatMeth =
            Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
      if (!CatMeth->hasAttr<AvailabilityAttr>())
        return true;
  return false;
}

106
107
108
AvailabilityResult
Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
  AvailabilityResult Result = D->getAvailability(Message);
109
110
111

  // For typedefs, if the typedef declaration appears available look
  // to the underlying type to see if it is more restrictive.
David Blaikie's avatar
David Blaikie committed
112
  while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113
114
115
    if (Result == AR_Available) {
      if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
        D = TT->getDecl();
116
        Result = D->getAvailability(Message);
117
118
119
120
121
        continue;
      }
    }
    break;
  }
122

123
124
  // Forward class declarations get their attributes from their definition.
  if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125
    if (IDecl->getDefinition()) {
126
      D = IDecl->getDefinition();
127
      Result = D->getAvailability(Message);
128
    }
129
  }
130

131
132
133
134
  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
    if (Result == AR_Available) {
      const DeclContext *DC = ECD->getDeclContext();
      if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135
        Result = TheEnumDecl->getAvailability(Message);
136
    }
137

138
  if (Result == AR_NotYetIntroduced) {
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    // Don't do this for enums, they can't be redeclared.
    if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
      return AR_Available;

    bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
    // Objective-C method declarations in categories are not modelled as
    // redeclarations, so manually look for a redeclaration in a category
    // if necessary.
    if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
      Warn = false;
    // In general, D will point to the most recent redeclaration. However,
    // for `@class A;` decls, this isn't true -- manually go through the
    // redecl chain in that case.
    if (Warn && isa<ObjCInterfaceDecl>(D))
      for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
           Redecl = Redecl->getPreviousDecl())
        if (!Redecl->hasAttr<AvailabilityAttr>() ||
            Redecl->getAttr<AvailabilityAttr>()->isInherited())
          Warn = false;

    return Warn ? AR_NotYetIntroduced : AR_Available;
  }
161
162

  return Result;
163
164
165
166
167
168
169
}

static void
DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
                           const ObjCInterfaceDecl *UnknownObjCClass,
                           bool ObjCPropertyAccess) {
  std::string Message;
170
  // See if this declaration is unavailable, deprecated, or partial.
171
  if (AvailabilityResult Result =
172
          S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
173

174
175
176
177
178
    if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) {
      S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
      return;
    }

179
    const ObjCPropertyDecl *ObjCPDecl = nullptr;
180
181
    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
      if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
182
        AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
183
184
185
        if (PDeclResult == Result)
          ObjCPDecl = PD;
      }
186
    }
187

188
189
190
    S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
                              ObjCPDecl, ObjCPropertyAccess);
  }
191
192
}

193
/// \brief Emit a note explaining that this function is deleted.
194
void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
195
196
  assert(Decl->isDeleted());

197
198
  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);

199
  if (Method && Method->isDeleted() && Method->isDefaulted()) {
200
201
202
203
204
205
    // If the method was explicitly defaulted, point at that declaration.
    if (!Method->isImplicit())
      Diag(Decl->getLocation(), diag::note_implicitly_deleted);

    // Try to diagnose why this special member function was implicitly
    // deleted. This might fail, if that reason no longer applies.
206
    CXXSpecialMember CSM = getSpecialMember(Method);
207
    if (CSM != CXXInvalid)
208
      ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
209
210

    return;
211
212
  }

213
214
215
216
  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
  if (Ctor && Ctor->isInheritingConstructor())
    return NoteDeletedInheritingConstructor(Ctor);

217
218
  Diag(Decl->getLocation(), diag::note_availability_specified_here)
    << Decl << true;
219
220
}

221
222
223
/// \brief Determine whether a FunctionDecl was ever declared with an
/// explicit storage class.
static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
224
  for (auto I : D->redecls()) {
Rafael Espindola's avatar
Rafael Espindola committed
225
    if (I->getStorageClass() != SC_None)
226
227
228
229
230
231
      return true;
  }
  return false;
}

/// \brief Check whether we're in an extern inline function and referring to a
232
/// variable or function with internal linkage (C11 6.7.4p3).
233
234
///
/// This is only a warning because we used to silently accept this code, but
235
236
237
238
/// in many cases it will not behave correctly. This is not enabled in C++ mode
/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
/// and so while there may still be user mistakes, most of the time we can't
/// prove that there are errors.
239
240
241
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
                                                      const NamedDecl *D,
                                                      SourceLocation Loc) {
242
243
244
245
246
  // This is disabled under C++; there are too many ways for this to fire in
  // contexts where the warning is a false positive, or where it is technically
  // correct but benign.
  if (S.getLangOpts().CPlusPlus)
    return;
247
248
249
250
251
252
253

  // Check if this is an inlined function or method.
  FunctionDecl *Current = S.getCurFunctionDecl();
  if (!Current)
    return;
  if (!Current->isInlined())
    return;
254
  if (!Current->isExternallyVisible())
255
    return;
256

257
  // Check if the decl has internal linkage.
258
  if (D->getFormalLinkage() != InternalLinkage)
259
260
    return;

261
262
263
264
265
266
267
268
  // Downgrade from ExtWarn to Extension if
  //  (1) the supposedly external inline function is in the main file,
  //      and probably won't be included anywhere else.
  //  (2) the thing we're referencing is a pure function.
  //  (3) the thing we're referencing is another inline function.
  // This last can give us false negatives, but it's better than warning on
  // wrappers for simple C library functions.
  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
269
  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
270
271
272
  if (!DowngradeWarning && UsedFn)
    DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();

273
274
  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
                               : diag::ext_internal_in_extern_inline)
275
    << /*IsVar=*/!UsedFn << D;
276

277
  S.MaybeSuggestAddingStaticToDecl(Current);
278

Alp Toker's avatar
Alp Toker committed
279
280
  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
      << D;
281
282
}

283
void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
284
  const FunctionDecl *First = Cur->getFirstDecl();
285
286
287
288
289
290
291
292
293

  // Suggest "static" on the function, if possible.
  if (!hasAnyExplicitStorageClass(First)) {
    SourceLocation DeclBegin = First->getSourceRange().getBegin();
    Diag(DeclBegin, diag::note_convert_inline_to_static)
      << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  }
}

294
295
296
297
298
299
300
301
302
303
304
/// \brief Determine whether the use of this declaration is valid, and
/// emit any corresponding diagnostics.
///
/// This routine diagnoses various problems with referencing
/// declarations that can occur when using a declaration. For example,
/// it might warn if a deprecated or unavailable declaration is being
/// used, or produce an error (and return true) if a C++0x deleted
/// function is being used.
///
/// \returns true if there was an error (this declaration cannot be
/// referenced), false otherwise.
305
///
306
bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
307
308
                             const ObjCInterfaceDecl *UnknownObjCClass,
                             bool ObjCPropertyAccess) {
309
  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
310
311
    // If there were any diagnostics suppressed by template argument deduction,
    // emit them now.
312
    auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
313
    if (Pos != SuppressedDiagnostics.end()) {
314
315
      for (const PartialDiagnosticAt &Suppressed : Pos->second)
        Diag(Suppressed.first, Suppressed.second);
316

317
      // Clear out the list of suppressed diagnostics, so that we don't emit
318
      // them again for this specialization. However, we don't obsolete this
319
320
      // entry from the table, because we want to avoid ever emitting these
      // diagnostics again.
321
      Pos->second.clear();
322
    }
323
324
325
326
327

    // C++ [basic.start.main]p3:
    //   The function 'main' shall not be used within a program.
    if (cast<FunctionDecl>(D)->isMain())
      Diag(Loc, diag::ext_main_used);
328
329
  }

330
  // See if this is an auto-typed variable whose initializer we are parsing.
331
  if (ParsingInitForAutoVars.count(D)) {
332
333
334
335
336
    if (isa<BindingDecl>(D)) {
      Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
        << D->getDeclName();
    } else {
      const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
337

338
339
340
      Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
        << D->getDeclName() << (unsigned)AT->getKeyword();
    }
341
    return true;
342
343
  }

344
345
346
  // See if this is a deleted function.
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    if (FD->isDeleted()) {
347
348
349
350
351
352
353
      auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
      if (Ctor && Ctor->isInheritingConstructor())
        Diag(Loc, diag::err_deleted_inherited_ctor_use)
            << Ctor->getParent()
            << Ctor->getInheritedConstructor().getConstructor()->getParent();
      else 
        Diag(Loc, diag::err_deleted_function_use);
354
      NoteDeletedFunction(FD);
355
356
      return true;
    }
357
358
359

    // If the function has a deduced return type, and we can't deduce it,
    // then we can't use it either.
Aaron Ballman's avatar
Aaron Ballman committed
360
    if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
361
362
        DeduceReturnType(FD, Loc))
      return true;
363
364
365

    if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
      return true;
366

Hans Wennborg's avatar
Hans Wennborg committed
367
    if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc))
368
      return true;
369
  }
370
371
372
373
374
375
376
377
378
379
380
381
382

  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  // Only the variables omp_in and omp_out are allowed in the combiner.
  // Only the variables omp_priv and omp_orig are allowed in the
  // initializer-clause.
  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
  if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
      isa<VarDecl>(D)) {
    Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
        << getCurFunction()->HasOMPDeclareReductionCombiner;
    Diag(D->getLocation(), diag::note_entity_declared_at) << D;
    return true;
  }
383

Nico Weber's avatar
Nico Weber committed
384
385
  DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
                             ObjCPropertyAccess);
386

387
  DiagnoseUnusedOfDecl(*this, D, Loc);
388

389
  diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
390

391
  return false;
392
393
}

394
395
396
397
398
399
400
401
402
403
404
/// \brief Retrieve the message suffix that should be added to a
/// diagnostic complaining about the given function being deleted or
/// unavailable.
std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
  std::string Message;
  if (FD->getAvailability(&Message))
    return ": " + Message;

  return std::string();
}

405
406
407
408
/// DiagnoseSentinelCalls - This routine checks whether a call or
/// message-send is to a declaration with the sentinel attribute, and
/// if so, it checks that the requirements of the sentinel are
/// satisfied.
409
void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
410
                                 ArrayRef<Expr *> Args) {
411
  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
412
  if (!attr)
413
    return;
414

415
416
417
418
419
420
  // The number of formal parameters of the declaration.
  unsigned numFormalParams;

  // The kind of declaration.  This is also an index into a %select in
  // the diagnostic.
  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
421

422
  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
423
424
    numFormalParams = MD->param_size();
    calleeType = CT_Method;
Mike Stump's avatar
Mike Stump committed
425
  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
426
427
428
429
    numFormalParams = FD->param_size();
    calleeType = CT_Function;
  } else if (isa<VarDecl>(D)) {
    QualType type = cast<ValueDecl>(D)->getType();
430
    const FunctionType *fn = nullptr;
431
432
433
434
435
436
437
438
    if (const PointerType *ptr = type->getAs<PointerType>()) {
      fn = ptr->getPointeeType()->getAs<FunctionType>();
      if (!fn) return;
      calleeType = CT_Function;
    } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
      fn = ptr->getPointeeType()->castAs<FunctionType>();
      calleeType = CT_Block;
    } else {
439
      return;
440
    }
441

442
    if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
443
      numFormalParams = proto->getNumParams();
444
445
446
447
    } else {
      numFormalParams = 0;
    }
  } else {
448
449
    return;
  }
450
451
452
453
454
455
456
457
458
459
460
461
462
463

  // "nullPos" is the number of formal parameters at the end which
  // effectively count as part of the variadic arguments.  This is
  // useful if you would prefer to not have *any* formal parameters,
  // but the language forces you to have at least one.
  unsigned nullPos = attr->getNullPos();
  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);

  // The number of arguments which should follow the sentinel.
  unsigned numArgsAfterSentinel = attr->getSentinel();

  // If there aren't enough arguments for all the formal parameters,
  // the sentinel, and the args after the sentinel, complain.
464
  if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
465
    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
466
    Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
467
468
    return;
  }
469
470

  // Otherwise, find the sentinel expression.
471
  Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
472
473
  if (!sentinelExpr) return;
  if (sentinelExpr->isValueDependent()) return;
474
  if (Context.isSentinelNullExpr(sentinelExpr)) return;
475

476
477
  // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
  // or 'NULL' if those are actually defined in the context.  Only use
478
479
480
  // 'nil' for ObjC methods, where it's much more likely that the
  // variadic arguments form a list of object pointers.
  SourceLocation MissingNilLoc
481
    = getLocForEndOfToken(sentinelExpr->getLocEnd());
482
  std::string NullValue;
483
  if (calleeType == CT_Method && PP.isMacroDefined("nil"))
484
    NullValue = "nil";
485
486
  else if (getLangOpts().CPlusPlus11)
    NullValue = "nullptr";
487
  else if (PP.isMacroDefined("NULL"))
488
489
    NullValue = "NULL";
  else
490
    NullValue = "(void*) 0";
491
492

  if (MissingNilLoc.isInvalid())
493
    Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
494
495
  else
    Diag(MissingNilLoc, diag::warn_missing_sentinel) 
496
      << int(calleeType)
497
      << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
498
  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
499
500
}

501
502
SourceRange Sema::getExprRange(Expr *E) const {
  return E ? E->getSourceRange() : SourceRange();
503
504
}

505
506
507
508
509
//===----------------------------------------------------------------------===//
//  Standard Promotions and Conversions
//===----------------------------------------------------------------------===//

/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
510
ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
511
512
513
514
  // Handle any placeholder expressions which made it here.
  if (E->getType()->isPlaceholderType()) {
    ExprResult result = CheckPlaceholderExpr(E);
    if (result.isInvalid()) return ExprError();
515
    E = result.get();
516
517
  }
  
518
519
520
  QualType Ty = E->getType();
  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");

521
522
523
524
  if (Ty->isFunctionType()) {
    // If we are here, we are not calling a function but taking
    // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
    if (getLangOpts().OpenCL) {
525
526
      if (Diagnose)
        Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
527
528
      return ExprError();
    }
529
530
531
532
533
534

    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
      if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
        if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
          return ExprError();

535
    E = ImpCastExprToType(E, Context.getPointerType(Ty),
536
                          CK_FunctionToPointerDecay).get();
537
  } else if (Ty->isArrayType()) {
538
539
540
541
542
543
    // In C90 mode, arrays only promote to pointers if the array expression is
    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
    // type 'array of type' is converted to an expression that has type 'pointer
    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
    // that has type 'array of type' ...".  The relevant change is "an lvalue"
    // (C90) to "an expression" (C99).
544
545
546
547
548
    //
    // C++ 4.2p1:
    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
    // T" can be converted to an rvalue of type "pointer to T".
    //
549
    if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
550
      E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
551
                            CK_ArrayToPointerDecay).get();
552
  }
553
  return E;
554
555
}

556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  // Check to see if we are dereferencing a null pointer.  If so,
  // and if not volatile-qualified, this is undefined behavior that the
  // optimizer will delete, so warn about it.  People sometimes try to use this
  // to get a deterministic trap and are surprised by clang's behavior.  This
  // only handles the pattern "*null", which is a very syntactic check.
  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
    if (UO->getOpcode() == UO_Deref &&
        UO->getSubExpr()->IgnoreParenCasts()->
          isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
        !UO->getType().isVolatileQualified()) {
    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
                          S.PDiag(diag::warn_indirection_through_null)
                            << UO->getSubExpr()->getSourceRange());
    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
                        S.PDiag(diag::note_indirection_through_null));
  }
}

575
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
576
577
                                    SourceLocation AssignLoc,
                                    const Expr* RHS) {
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
  const ObjCIvarDecl *IV = OIRE->getDecl();
  if (!IV)
    return;
  
  DeclarationName MemberName = IV->getDeclName();
  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  if (!Member || !Member->isStr("isa"))
    return;
  
  const Expr *Base = OIRE->getBase();
  QualType BaseType = Base->getType();
  if (OIRE->isArrow())
    BaseType = BaseType->getPointeeType();
  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
    if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
593
      ObjCInterfaceDecl *ClassDeclared = nullptr;
594
595
596
      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
      if (!ClassDeclared->getSuperClass()
          && (*ClassDeclared->ivar_begin()) == IV) {
597
598
599
600
601
602
        if (RHS) {
          NamedDecl *ObjectSetClass =
            S.LookupSingleName(S.TUScope,
                               &S.Context.Idents.get("object_setClass"),
                               SourceLocation(), S.LookupOrdinaryName);
          if (ObjectSetClass) {
603
            SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
            FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
            FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
                                                     AssignLoc), ",") <<
            FixItHint::CreateInsertion(RHSLocEnd, ")");
          }
          else
            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
        } else {
          NamedDecl *ObjectGetClass =
            S.LookupSingleName(S.TUScope,
                               &S.Context.Idents.get("object_getClass"),
                               SourceLocation(), S.LookupOrdinaryName);
          if (ObjectGetClass)
            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
            FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
            FixItHint::CreateReplacement(
                                         SourceRange(OIRE->getOpLoc(),
                                                     OIRE->getLocEnd()), ")");
          else
            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
        }
626
627
628
629
630
        S.Diag(IV->getLocation(), diag::note_ivar_decl);
      }
    }
}

631
ExprResult Sema::DefaultLvalueConversion(Expr *E) {
632
633
634
635
  // Handle any placeholder expressions which made it here.
  if (E->getType()->isPlaceholderType()) {
    ExprResult result = CheckPlaceholderExpr(E);
    if (result.isInvalid()) return ExprError();
636
    E = result.get();
637
638
  }
  
639
640
641
  // C++ [conv.lval]p1:
  //   A glvalue of a non-function, non-array type T can be
  //   converted to a prvalue.
642
  if (!E->isGLValue()) return E;
643

644
645
  QualType T = E->getType();
  assert(!T.isNull() && "r-value conversion on typeless expression?");
646

647
648
  // We don't want to throw lvalue-to-rvalue casts on top of
  // expressions of certain types in C++.
649
  if (getLangOpts().CPlusPlus &&
650
651
652
      (E->getType() == Context.OverloadTy ||
       T->isDependentType() ||
       T->isRecordType()))
653
    return E;
654

655
656
657
658
659
660
  // The C standard is actually really unclear on this point, and
  // DR106 tells us what the result should be but not why.  It's
  // generally best to say that void types just doesn't undergo
  // lvalue-to-rvalue at all.  Note that expressions of unqualified
  // 'void' type are never l-values, but qualified void can be.
  if (T->isVoidType())
661
    return E;
662

663
  // OpenCL usually rejects direct accesses to values of 'half' type.
664
  if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
665
666
667
668
669
670
      T->isHalfType()) {
    Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
      << 0 << T;
    return ExprError();
  }

671
  CheckForNullPointerDereference(*this, E);
672
673
674
675
676
677
678
679
680
681
682
683
  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
    NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
                                     &Context.Idents.get("object_getClass"),
                                     SourceLocation(), LookupOrdinaryName);
    if (ObjectGetClass)
      Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
        FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
        FixItHint::CreateReplacement(
                    SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
    else
      Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  }
684
685
  else if (const ObjCIvarRefExpr *OIRE =
            dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
686
687
    DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);

688
689
690
691
692
693
694
695
  // C++ [conv.lval]p1:
  //   [...] If T is a non-class type, the type of the prvalue is the
  //   cv-unqualified version of T. Otherwise, the type of the
  //   rvalue is T.
  //
  // C99 6.3.2.1p2:
  //   If the lvalue has qualified type, the value has the unqualified
  //   version of the type of the lvalue; otherwise, the value has the
696
  //   type of the lvalue.
697
698
  if (T.hasQualifiers())
    T = T.getUnqualifiedType();
699

700
  // Under the MS ABI, lock down the inheritance model now.
701
702
  if (T->isMemberPointerType() &&
      Context.getTargetInfo().getCXXABI().isMicrosoft())
703
    (void)isCompleteType(E->getExprLoc(), T);
704

705
  UpdateMarkingForLValueToRValue(E);
706
707
708
709
710
  
  // Loading a __weak object implicitly retains the value, so we need a cleanup to 
  // balance that.
  if (getLangOpts().ObjCAutoRefCount &&
      E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
711
    Cleanup.setExprNeedsCleanups(true);
712

713
714
  ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
                                            nullptr, VK_RValue);
715

716
717
718
719
720
  // C11 6.3.2.1p2:
  //   ... if the lvalue has atomic type, the value has the non-atomic version 
  //   of the type of the lvalue ...
  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
    T = Atomic->getValueType().getUnqualifiedType();
721
722
    Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
                                   nullptr, VK_RValue);
723
724
  }
  
725
  return Res;
726
727
}

728
729
ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
730
731
  if (Res.isInvalid())
    return ExprError();
732
  Res = DefaultLvalueConversion(Res.get());
733
734
  if (Res.isInvalid())
    return ExprError();
735
  return Res;
736
737
}

738
739
740
741
742
743
744
745
746
/// CallExprUnaryConversions - a special case of an unary conversion
/// performed on a function designator of a call expression.
ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  QualType Ty = E->getType();
  ExprResult Res = E;
  // Only do implicit cast for a function type, but not for a pointer
  // to function type.
  if (Ty->isFunctionType()) {
    Res = ImpCastExprToType(E, Context.getPointerType(Ty),
747
                            CK_FunctionToPointerDecay).get();
748
749
750
    if (Res.isInvalid())
      return ExprError();
  }
751
  Res = DefaultLvalueConversion(Res.get());
752
753
  if (Res.isInvalid())
    return ExprError();
754
  return Res.get();
755
}
756

757
/// UsualUnaryConversions - Performs various conversions that are common to most
758
/// operators (C99 6.3). The conversions of array and function types are
759
/// sometimes suppressed. For example, the array->pointer conversion doesn't
760
761
/// apply if the array is an argument to the sizeof or address (&) operators.
/// In these instances, this routine should *not* be called.
762
ExprResult Sema::UsualUnaryConversions(Expr *E) {
763
  // First, convert to an r-value.
764
765
  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  if (Res.isInvalid())
766
    return ExprError();
767
  E = Res.get();
768

769
  QualType Ty = E->getType();
770
  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
771

772
773
  // Half FP have to be promoted to float unless it is natively supported
  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
774
    return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
775

776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
  // Try to perform integral promotions if the object has a theoretically
  // promotable type.
  if (Ty->isIntegralOrUnscopedEnumerationType()) {
    // C99 6.3.1.1p2:
    //
    //   The following may be used in an expression wherever an int or
    //   unsigned int may be used:
    //     - an object or expression with an integer type whose integer
    //       conversion rank is less than or equal to the rank of int
    //       and unsigned int.
    //     - A bit-field of type _Bool, int, signed int, or unsigned int.
    //
    //   If an int can represent all values of the original type, the
    //   value is converted to an int; otherwise, it is converted to an
    //   unsigned int. These are called the integer promotions. All
    //   other types are unchanged by the integer promotions.
792

793
794
    QualType PTy = Context.isPromotableBitField(E);
    if (!PTy.isNull()) {
795
      E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
796
      return E;
797
798
799
    }
    if (Ty->isPromotableIntegerType()) {
      QualType PT = Context.getPromotedIntegerType(Ty);
800
      E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
801
      return E;
802
    }
803
  }
804
  return E;
805
806
}

Chris Lattner's avatar
Chris Lattner committed
807
/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
808
809
810
/// do not have a prototype. Arguments that have type float or __fp16
/// are promoted to double. All other argument types are converted by
/// UsualUnaryConversions().
811
812
ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  QualType Ty = E->getType();
Chris Lattner's avatar
Chris Lattner committed
813
  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
814

815
816
  ExprResult Res = UsualUnaryConversions(E);
  if (Res.isInvalid())
817
    return ExprError();
818
  E = Res.get();
819

820
821
822
823
  // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
  // double.
  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  if (BTy && (BTy->getKind() == BuiltinType::Half ||
824
825
              BTy->getKind() == BuiltinType::Float)) {
    if (getLangOpts().OpenCL &&
826
        !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
827
828
829
830
831
832
833
        if (BTy->getKind() == BuiltinType::Half) {
            E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
        }
    } else {
      E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
    }
  }
834

835
  // C++ performs lvalue-to-rvalue conversion as a default argument
836
837
838
839
840
841
842
843
  // promotion, even on class types, but note:
  //   C++11 [conv.lval]p2:
  //     When an lvalue-to-rvalue conversion occurs in an unevaluated
  //     operand or a subexpression thereof the value contained in the
  //     referenced object is not accessed. Otherwise, if the glvalue
  //     has a class type, the conversion copy-initializes a temporary
  //     of type T from the glvalue and the result of the conversion
  //     is a prvalue for the temporary.
844
845
  // FIXME: add some way to gate this entire thing for correctness in
  // potentially potentially evaluated contexts.
846
  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
847
848
    ExprResult Temp = PerformCopyInitialization(
                       InitializedEntity::InitializeTemporary(E->getType()),
849
                                                E->getExprLoc(), E);
850
851
852
    if (Temp.isInvalid())
      return ExprError();
    E = Temp.get();
853
854
  }

855
  return E;
Chris Lattner's avatar
Chris Lattner committed
856
857
}

858
859
860
861
/// Determine the degree of POD-ness for an expression.
/// Incomplete types are considered POD, since this check can be performed
/// when we're in an unevaluated context.
Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
862
  if (Ty->isIncompleteType()) {
863
864
865
866
867
868
869
870
871
872
873
    // C++11 [expr.call]p7:
    //   After these conversions, if the argument does not have arithmetic,
    //   enumeration, pointer, pointer to member, or class type, the program
    //   is ill-formed.
    //
    // Since we've already performed array-to-pointer and function-to-pointer
    // decay, the only such type in C++ is cv void. This also handles
    // initializer lists as variadic arguments.
    if (Ty->isVoidType())
      return VAK_Invalid;

874
875
    if (Ty->isObjCObjectType())
      return VAK_Invalid;
876
    return VAK_Valid;
877
878
879
880
881
  }

  if (Ty.isCXX98PODType(Context))
    return VAK_Valid;

882
883
  // C++11 [expr.call]p7:
  //   Passing a potentially-evaluated argument of class type (Clause 9)
884
  //   having a non-trivial copy constructor, a non-trivial move constructor,
885
  //   or a non-trivial destructor, with no corresponding parameter,
886
  //   is conditionally-supported with implementation-defined semantics.
Richard Smith's avatar
Richard Smith committed
887
  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
888
    if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
889
890
891
      if (!Record->hasNonTrivialCopyConstructor() &&
          !Record->hasNonTrivialMoveConstructor() &&
          !Record->hasNonTrivialDestructor())
892
893
894
895
        return VAK_ValidInCXX11;

  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
    return VAK_Valid;
896
897
898
899

  if (Ty->isObjCObjectType())
    return VAK_Invalid;

900
901
902
  if (getLangOpts().MSVCCompat)
    return VAK_MSVCUndefined;

903
904
905
  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  // permitted to reject them. We should consider doing so.
  return VAK_Undefined;
906
907
}

908
void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
909
  // Don't allow one to pass an Objective-C interface to a vararg.
910
911
  const QualType &Ty = E->getType();
  VarArgKind VAK = isValidVarArgType(Ty);
912
913

  // Complain about passing non-POD types through varargs.
914
  switch (VAK) {
915
  case VAK_ValidInCXX11:
916
    DiagRuntimeBehavior(
917
        E->getLocStart(), nullptr,
918
        PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
919
920
921
922
923
924
          << Ty << CT);
    // Fall through.
  case VAK_Valid:
    if (Ty->isRecordType()) {
      // This is unlikely to be what the user intended. If the class has a
      // 'c_str' member function, the user probably meant to call that.
925
      DiagRuntimeBehavior(E->getLocStart(), nullptr,
926
927
928
                          PDiag(diag::warn_pass_class_arg_to_vararg)
                            << Ty << CT << hasCStrMethod(E) << ".c_str()");
    }
929
    break;
930

931
  case VAK_Undefined:
932
  case VAK_MSVCUndefined:
933
    DiagRuntimeBehavior(
934
        E->getLocStart(), nullptr,
935
936
937
938
939
940
941
        PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
          << getLangOpts().CPlusPlus11 << Ty << CT);
    break;

  case VAK_Invalid:
    if (Ty->isObjCObjectType())
      DiagRuntimeBehavior(
942
          E->getLocStart(), nullptr,
943
944
945
946
947
948
          PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
            << Ty << CT);
    else
      Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
        << isa<InitListExpr>(E) << Ty << CT;
    break;
949
  }
950
951
}

952
/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
953
/// will create a trap if the resulting type is not a POD type.
954
ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall's avatar
John McCall committed
955
                                                  FunctionDecl *FDecl) {
956
  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
957
958
959
960
961
962
963
964
965
966
967
    // Strip the unbridged-cast placeholder expression off, if applicable.
    if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
        (CT == VariadicMethod ||
         (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
      E = stripARCUnbridgedCast(E);

    // Otherwise, do normal placeholder checking.
    } else {
      ExprResult ExprRes = CheckPlaceholderExpr(E);
      if (ExprRes.isInvalid())
        return ExprError();
968
      E = ExprRes.get();
969
970
    }
  }
971
  
972
  ExprResult ExprRes = DefaultArgumentPromotion(E);
973
974
  if (ExprRes.isInvalid())
    return ExprError();
975
  E = ExprRes.get();
976

977
978
  // Diagnostics regarding non-POD argument types are
  // emitted along with format string checking in Sema::CheckFunctionCall().
979
  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
980
981
982
983
984
985
986
987
988
989
    // Turn this into a trap.
    CXXScopeSpec SS;
    SourceLocation TemplateKWLoc;
    UnqualifiedId Name;
    Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
                       E->getLocStart());
    ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
                                          Name, true, false);
    if (TrapFn.isInvalid())
      return ExprError();
John McCall's avatar
John McCall committed
990

991
    ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
992
                                    E->getLocStart(), None,
993
994
995
                                    E->getLocEnd());
    if (Call.isInvalid())
      return ExprError();
996

997
998
999
1000
    ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
                                  Call.get(), E);
    if (Comma.isInvalid())
      return ExprError();
For faster browsing, not all history is shown. View entire blame