clang  6.0.0svn
SemaExpr.cpp
Go to the documentation of this file.
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.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"
28 #include "clang/AST/TypeLoc.h"
31 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49 
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53  // See if this is an auto-typed variable whose initializer we are parsing.
54  if (ParsingInitForAutoVars.count(D))
55  return false;
56 
57  // See if this is a deleted function.
58  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59  if (FD->isDeleted())
60  return false;
61 
62  // If the function has a deduced return type, and we can't deduce it,
63  // then we can't use it either.
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  cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72  return false;
73 
74  return true;
75 }
76 
78  // Warn if this is used but marked unused.
79  if (const auto *A = D->getAttr<UnusedAttr>()) {
80  // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81  // should diagnose them.
82  if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
83  A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
84  const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
85  if (DC && !DC->hasAttr<UnusedAttr>())
86  S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
87  }
88  }
89 }
90 
91 /// \brief Emit a note explaining that this function is deleted.
93  assert(Decl->isDeleted());
94 
95  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
96 
97  if (Method && Method->isDeleted() && Method->isDefaulted()) {
98  // If the method was explicitly defaulted, point at that declaration.
99  if (!Method->isImplicit())
100  Diag(Decl->getLocation(), diag::note_implicitly_deleted);
101 
102  // Try to diagnose why this special member function was implicitly
103  // deleted. This might fail, if that reason no longer applies.
104  CXXSpecialMember CSM = getSpecialMember(Method);
105  if (CSM != CXXInvalid)
106  ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
107 
108  return;
109  }
110 
111  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
112  if (Ctor && Ctor->isInheritingConstructor())
113  return NoteDeletedInheritingConstructor(Ctor);
114 
115  Diag(Decl->getLocation(), diag::note_availability_specified_here)
116  << Decl << true;
117 }
118 
119 /// \brief Determine whether a FunctionDecl was ever declared with an
120 /// explicit storage class.
122  for (auto I : D->redecls()) {
123  if (I->getStorageClass() != SC_None)
124  return true;
125  }
126  return false;
127 }
128 
129 /// \brief Check whether we're in an extern inline function and referring to a
130 /// variable or function with internal linkage (C11 6.7.4p3).
131 ///
132 /// This is only a warning because we used to silently accept this code, but
133 /// in many cases it will not behave correctly. This is not enabled in C++ mode
134 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
135 /// and so while there may still be user mistakes, most of the time we can't
136 /// prove that there are errors.
138  const NamedDecl *D,
139  SourceLocation Loc) {
140  // This is disabled under C++; there are too many ways for this to fire in
141  // contexts where the warning is a false positive, or where it is technically
142  // correct but benign.
143  if (S.getLangOpts().CPlusPlus)
144  return;
145 
146  // Check if this is an inlined function or method.
147  FunctionDecl *Current = S.getCurFunctionDecl();
148  if (!Current)
149  return;
150  if (!Current->isInlined())
151  return;
152  if (!Current->isExternallyVisible())
153  return;
154 
155  // Check if the decl has internal linkage.
156  if (D->getFormalLinkage() != InternalLinkage)
157  return;
158 
159  // Downgrade from ExtWarn to Extension if
160  // (1) the supposedly external inline function is in the main file,
161  // and probably won't be included anywhere else.
162  // (2) the thing we're referencing is a pure function.
163  // (3) the thing we're referencing is another inline function.
164  // This last can give us false negatives, but it's better than warning on
165  // wrappers for simple C library functions.
166  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
167  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
168  if (!DowngradeWarning && UsedFn)
169  DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
170 
171  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
172  : diag::ext_internal_in_extern_inline)
173  << /*IsVar=*/!UsedFn << D;
174 
176 
177  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
178  << D;
179 }
180 
182  const FunctionDecl *First = Cur->getFirstDecl();
183 
184  // Suggest "static" on the function, if possible.
185  if (!hasAnyExplicitStorageClass(First)) {
186  SourceLocation DeclBegin = First->getSourceRange().getBegin();
187  Diag(DeclBegin, diag::note_convert_inline_to_static)
188  << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
189  }
190 }
191 
192 /// \brief Determine whether the use of this declaration is valid, and
193 /// emit any corresponding diagnostics.
194 ///
195 /// This routine diagnoses various problems with referencing
196 /// declarations that can occur when using a declaration. For example,
197 /// it might warn if a deprecated or unavailable declaration is being
198 /// used, or produce an error (and return true) if a C++0x deleted
199 /// function is being used.
200 ///
201 /// \returns true if there was an error (this declaration cannot be
202 /// referenced), false otherwise.
203 ///
205  const ObjCInterfaceDecl *UnknownObjCClass,
206  bool ObjCPropertyAccess,
207  bool AvoidPartialAvailabilityChecks) {
208  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
209  // If there were any diagnostics suppressed by template argument deduction,
210  // emit them now.
211  auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
212  if (Pos != SuppressedDiagnostics.end()) {
213  for (const PartialDiagnosticAt &Suppressed : Pos->second)
214  Diag(Suppressed.first, Suppressed.second);
215 
216  // Clear out the list of suppressed diagnostics, so that we don't emit
217  // them again for this specialization. However, we don't obsolete this
218  // entry from the table, because we want to avoid ever emitting these
219  // diagnostics again.
220  Pos->second.clear();
221  }
222 
223  // C++ [basic.start.main]p3:
224  // The function 'main' shall not be used within a program.
225  if (cast<FunctionDecl>(D)->isMain())
226  Diag(Loc, diag::ext_main_used);
227  }
228 
229  // See if this is an auto-typed variable whose initializer we are parsing.
230  if (ParsingInitForAutoVars.count(D)) {
231  if (isa<BindingDecl>(D)) {
232  Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
233  << D->getDeclName();
234  } else {
235  Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
236  << D->getDeclName() << cast<VarDecl>(D)->getType();
237  }
238  return true;
239  }
240 
241  // See if this is a deleted function.
242  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
243  if (FD->isDeleted()) {
244  auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
245  if (Ctor && Ctor->isInheritingConstructor())
246  Diag(Loc, diag::err_deleted_inherited_ctor_use)
247  << Ctor->getParent()
248  << Ctor->getInheritedConstructor().getConstructor()->getParent();
249  else
250  Diag(Loc, diag::err_deleted_function_use);
251  NoteDeletedFunction(FD);
252  return true;
253  }
254 
255  // If the function has a deduced return type, and we can't deduce it,
256  // then we can't use it either.
257  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
258  DeduceReturnType(FD, Loc))
259  return true;
260 
261  if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
262  return true;
263  }
264 
265  auto getReferencedObjCProp = [](const NamedDecl *D) ->
266  const ObjCPropertyDecl * {
267  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
268  return MD->findPropertyDecl();
269  return nullptr;
270  };
271  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
272  if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
273  return true;
274  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
275  return true;
276  }
277 
278  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
279  // Only the variables omp_in and omp_out are allowed in the combiner.
280  // Only the variables omp_priv and omp_orig are allowed in the
281  // initializer-clause.
282  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
283  if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
284  isa<VarDecl>(D)) {
285  Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
286  << getCurFunction()->HasOMPDeclareReductionCombiner;
287  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
288  return true;
289  }
290 
291  DiagnoseAvailabilityOfDecl(D, Loc, UnknownObjCClass, ObjCPropertyAccess,
292  AvoidPartialAvailabilityChecks);
293 
294  DiagnoseUnusedOfDecl(*this, D, Loc);
295 
297 
298  return false;
299 }
300 
301 /// \brief Retrieve the message suffix that should be added to a
302 /// diagnostic complaining about the given function being deleted or
303 /// unavailable.
305  std::string Message;
306  if (FD->getAvailability(&Message))
307  return ": " + Message;
308 
309  return std::string();
310 }
311 
312 /// DiagnoseSentinelCalls - This routine checks whether a call or
313 /// message-send is to a declaration with the sentinel attribute, and
314 /// if so, it checks that the requirements of the sentinel are
315 /// satisfied.
317  ArrayRef<Expr *> Args) {
318  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
319  if (!attr)
320  return;
321 
322  // The number of formal parameters of the declaration.
323  unsigned numFormalParams;
324 
325  // The kind of declaration. This is also an index into a %select in
326  // the diagnostic.
327  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
328 
329  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
330  numFormalParams = MD->param_size();
331  calleeType = CT_Method;
332  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
333  numFormalParams = FD->param_size();
334  calleeType = CT_Function;
335  } else if (isa<VarDecl>(D)) {
336  QualType type = cast<ValueDecl>(D)->getType();
337  const FunctionType *fn = nullptr;
338  if (const PointerType *ptr = type->getAs<PointerType>()) {
339  fn = ptr->getPointeeType()->getAs<FunctionType>();
340  if (!fn) return;
341  calleeType = CT_Function;
342  } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
343  fn = ptr->getPointeeType()->castAs<FunctionType>();
344  calleeType = CT_Block;
345  } else {
346  return;
347  }
348 
349  if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
350  numFormalParams = proto->getNumParams();
351  } else {
352  numFormalParams = 0;
353  }
354  } else {
355  return;
356  }
357 
358  // "nullPos" is the number of formal parameters at the end which
359  // effectively count as part of the variadic arguments. This is
360  // useful if you would prefer to not have *any* formal parameters,
361  // but the language forces you to have at least one.
362  unsigned nullPos = attr->getNullPos();
363  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
364  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
365 
366  // The number of arguments which should follow the sentinel.
367  unsigned numArgsAfterSentinel = attr->getSentinel();
368 
369  // If there aren't enough arguments for all the formal parameters,
370  // the sentinel, and the args after the sentinel, complain.
371  if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
372  Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
373  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
374  return;
375  }
376 
377  // Otherwise, find the sentinel expression.
378  Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
379  if (!sentinelExpr) return;
380  if (sentinelExpr->isValueDependent()) return;
381  if (Context.isSentinelNullExpr(sentinelExpr)) return;
382 
383  // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
384  // or 'NULL' if those are actually defined in the context. Only use
385  // 'nil' for ObjC methods, where it's much more likely that the
386  // variadic arguments form a list of object pointers.
387  SourceLocation MissingNilLoc
388  = getLocForEndOfToken(sentinelExpr->getLocEnd());
389  std::string NullValue;
390  if (calleeType == CT_Method && PP.isMacroDefined("nil"))
391  NullValue = "nil";
392  else if (getLangOpts().CPlusPlus11)
393  NullValue = "nullptr";
394  else if (PP.isMacroDefined("NULL"))
395  NullValue = "NULL";
396  else
397  NullValue = "(void*) 0";
398 
399  if (MissingNilLoc.isInvalid())
400  Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
401  else
402  Diag(MissingNilLoc, diag::warn_missing_sentinel)
403  << int(calleeType)
404  << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
405  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
406 }
407 
409  return E ? E->getSourceRange() : SourceRange();
410 }
411 
412 //===----------------------------------------------------------------------===//
413 // Standard Promotions and Conversions
414 //===----------------------------------------------------------------------===//
415 
416 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
418  // Handle any placeholder expressions which made it here.
419  if (E->getType()->isPlaceholderType()) {
420  ExprResult result = CheckPlaceholderExpr(E);
421  if (result.isInvalid()) return ExprError();
422  E = result.get();
423  }
424 
425  QualType Ty = E->getType();
426  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
427 
428  if (Ty->isFunctionType()) {
429  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
430  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
431  if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
432  return ExprError();
433 
434  E = ImpCastExprToType(E, Context.getPointerType(Ty),
435  CK_FunctionToPointerDecay).get();
436  } else if (Ty->isArrayType()) {
437  // In C90 mode, arrays only promote to pointers if the array expression is
438  // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
439  // type 'array of type' is converted to an expression that has type 'pointer
440  // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
441  // that has type 'array of type' ...". The relevant change is "an lvalue"
442  // (C90) to "an expression" (C99).
443  //
444  // C++ 4.2p1:
445  // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
446  // T" can be converted to an rvalue of type "pointer to T".
447  //
448  if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
449  E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
450  CK_ArrayToPointerDecay).get();
451  }
452  return E;
453 }
454 
456  // Check to see if we are dereferencing a null pointer. If so,
457  // and if not volatile-qualified, this is undefined behavior that the
458  // optimizer will delete, so warn about it. People sometimes try to use this
459  // to get a deterministic trap and are surprised by clang's behavior. This
460  // only handles the pattern "*null", which is a very syntactic check.
461  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
462  if (UO->getOpcode() == UO_Deref &&
463  UO->getSubExpr()->IgnoreParenCasts()->
464  isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
465  !UO->getType().isVolatileQualified()) {
466  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
467  S.PDiag(diag::warn_indirection_through_null)
468  << UO->getSubExpr()->getSourceRange());
469  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
470  S.PDiag(diag::note_indirection_through_null));
471  }
472 }
473 
474 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
475  SourceLocation AssignLoc,
476  const Expr* RHS) {
477  const ObjCIvarDecl *IV = OIRE->getDecl();
478  if (!IV)
479  return;
480 
481  DeclarationName MemberName = IV->getDeclName();
482  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
483  if (!Member || !Member->isStr("isa"))
484  return;
485 
486  const Expr *Base = OIRE->getBase();
487  QualType BaseType = Base->getType();
488  if (OIRE->isArrow())
489  BaseType = BaseType->getPointeeType();
490  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
491  if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
492  ObjCInterfaceDecl *ClassDeclared = nullptr;
493  ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
494  if (!ClassDeclared->getSuperClass()
495  && (*ClassDeclared->ivar_begin()) == IV) {
496  if (RHS) {
497  NamedDecl *ObjectSetClass =
499  &S.Context.Idents.get("object_setClass"),
501  if (ObjectSetClass) {
502  SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
503  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
504  FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
506  AssignLoc), ",") <<
507  FixItHint::CreateInsertion(RHSLocEnd, ")");
508  }
509  else
510  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
511  } else {
512  NamedDecl *ObjectGetClass =
514  &S.Context.Idents.get("object_getClass"),
516  if (ObjectGetClass)
517  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
518  FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
520  SourceRange(OIRE->getOpLoc(),
521  OIRE->getLocEnd()), ")");
522  else
523  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
524  }
525  S.Diag(IV->getLocation(), diag::note_ivar_decl);
526  }
527  }
528 }
529 
531  // Handle any placeholder expressions which made it here.
532  if (E->getType()->isPlaceholderType()) {
533  ExprResult result = CheckPlaceholderExpr(E);
534  if (result.isInvalid()) return ExprError();
535  E = result.get();
536  }
537 
538  // C++ [conv.lval]p1:
539  // A glvalue of a non-function, non-array type T can be
540  // converted to a prvalue.
541  if (!E->isGLValue()) return E;
542 
543  QualType T = E->getType();
544  assert(!T.isNull() && "r-value conversion on typeless expression?");
545 
546  // We don't want to throw lvalue-to-rvalue casts on top of
547  // expressions of certain types in C++.
548  if (getLangOpts().CPlusPlus &&
549  (E->getType() == Context.OverloadTy ||
550  T->isDependentType() ||
551  T->isRecordType()))
552  return E;
553 
554  // The C standard is actually really unclear on this point, and
555  // DR106 tells us what the result should be but not why. It's
556  // generally best to say that void types just doesn't undergo
557  // lvalue-to-rvalue at all. Note that expressions of unqualified
558  // 'void' type are never l-values, but qualified void can be.
559  if (T->isVoidType())
560  return E;
561 
562  // OpenCL usually rejects direct accesses to values of 'half' type.
563  if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
564  T->isHalfType()) {
565  Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
566  << 0 << T;
567  return ExprError();
568  }
569 
571  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
572  NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
573  &Context.Idents.get("object_getClass"),
574  SourceLocation(), LookupOrdinaryName);
575  if (ObjectGetClass)
576  Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
577  FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
579  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
580  else
581  Diag(E->getExprLoc(), diag::warn_objc_isa_use);
582  }
583  else if (const ObjCIvarRefExpr *OIRE =
584  dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
585  DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
586 
587  // C++ [conv.lval]p1:
588  // [...] If T is a non-class type, the type of the prvalue is the
589  // cv-unqualified version of T. Otherwise, the type of the
590  // rvalue is T.
591  //
592  // C99 6.3.2.1p2:
593  // If the lvalue has qualified type, the value has the unqualified
594  // version of the type of the lvalue; otherwise, the value has the
595  // type of the lvalue.
596  if (T.hasQualifiers())
597  T = T.getUnqualifiedType();
598 
599  // Under the MS ABI, lock down the inheritance model now.
600  if (T->isMemberPointerType() &&
601  Context.getTargetInfo().getCXXABI().isMicrosoft())
602  (void)isCompleteType(E->getExprLoc(), T);
603 
604  UpdateMarkingForLValueToRValue(E);
605 
606  // Loading a __weak object implicitly retains the value, so we need a cleanup to
607  // balance that.
609  Cleanup.setExprNeedsCleanups(true);
610 
611  ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
612  nullptr, VK_RValue);
613 
614  // C11 6.3.2.1p2:
615  // ... if the lvalue has atomic type, the value has the non-atomic version
616  // of the type of the lvalue ...
617  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
618  T = Atomic->getValueType().getUnqualifiedType();
619  Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
620  nullptr, VK_RValue);
621  }
622 
623  return Res;
624 }
625 
627  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
628  if (Res.isInvalid())
629  return ExprError();
630  Res = DefaultLvalueConversion(Res.get());
631  if (Res.isInvalid())
632  return ExprError();
633  return Res;
634 }
635 
636 /// CallExprUnaryConversions - a special case of an unary conversion
637 /// performed on a function designator of a call expression.
639  QualType Ty = E->getType();
640  ExprResult Res = E;
641  // Only do implicit cast for a function type, but not for a pointer
642  // to function type.
643  if (Ty->isFunctionType()) {
644  Res = ImpCastExprToType(E, Context.getPointerType(Ty),
645  CK_FunctionToPointerDecay).get();
646  if (Res.isInvalid())
647  return ExprError();
648  }
649  Res = DefaultLvalueConversion(Res.get());
650  if (Res.isInvalid())
651  return ExprError();
652  return Res.get();
653 }
654 
655 /// UsualUnaryConversions - Performs various conversions that are common to most
656 /// operators (C99 6.3). The conversions of array and function types are
657 /// sometimes suppressed. For example, the array->pointer conversion doesn't
658 /// apply if the array is an argument to the sizeof or address (&) operators.
659 /// In these instances, this routine should *not* be called.
661  // First, convert to an r-value.
662  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
663  if (Res.isInvalid())
664  return ExprError();
665  E = Res.get();
666 
667  QualType Ty = E->getType();
668  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
669 
670  // Half FP have to be promoted to float unless it is natively supported
671  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
672  return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
673 
674  // Try to perform integral promotions if the object has a theoretically
675  // promotable type.
677  // C99 6.3.1.1p2:
678  //
679  // The following may be used in an expression wherever an int or
680  // unsigned int may be used:
681  // - an object or expression with an integer type whose integer
682  // conversion rank is less than or equal to the rank of int
683  // and unsigned int.
684  // - A bit-field of type _Bool, int, signed int, or unsigned int.
685  //
686  // If an int can represent all values of the original type, the
687  // value is converted to an int; otherwise, it is converted to an
688  // unsigned int. These are called the integer promotions. All
689  // other types are unchanged by the integer promotions.
690 
691  QualType PTy = Context.isPromotableBitField(E);
692  if (!PTy.isNull()) {
693  E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
694  return E;
695  }
696  if (Ty->isPromotableIntegerType()) {
697  QualType PT = Context.getPromotedIntegerType(Ty);
698  E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
699  return E;
700  }
701  }
702  return E;
703 }
704 
705 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
706 /// do not have a prototype. Arguments that have type float or __fp16
707 /// are promoted to double. All other argument types are converted by
708 /// UsualUnaryConversions().
710  QualType Ty = E->getType();
711  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
712 
713  ExprResult Res = UsualUnaryConversions(E);
714  if (Res.isInvalid())
715  return ExprError();
716  E = Res.get();
717 
718  // If this is a 'float' or '__fp16' (CVR qualified or typedef)
719  // promote to double.
720  // Note that default argument promotion applies only to float (and
721  // half/fp16); it does not apply to _Float16.
722  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
723  if (BTy && (BTy->getKind() == BuiltinType::Half ||
724  BTy->getKind() == BuiltinType::Float)) {
725  if (getLangOpts().OpenCL &&
726  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
727  if (BTy->getKind() == BuiltinType::Half) {
728  E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
729  }
730  } else {
731  E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
732  }
733  }
734 
735  // C++ performs lvalue-to-rvalue conversion as a default argument
736  // promotion, even on class types, but note:
737  // C++11 [conv.lval]p2:
738  // When an lvalue-to-rvalue conversion occurs in an unevaluated
739  // operand or a subexpression thereof the value contained in the
740  // referenced object is not accessed. Otherwise, if the glvalue
741  // has a class type, the conversion copy-initializes a temporary
742  // of type T from the glvalue and the result of the conversion
743  // is a prvalue for the temporary.
744  // FIXME: add some way to gate this entire thing for correctness in
745  // potentially potentially evaluated contexts.
746  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
747  ExprResult Temp = PerformCopyInitialization(
749  E->getExprLoc(), E);
750  if (Temp.isInvalid())
751  return ExprError();
752  E = Temp.get();
753  }
754 
755  return E;
756 }
757 
758 /// Determine the degree of POD-ness for an expression.
759 /// Incomplete types are considered POD, since this check can be performed
760 /// when we're in an unevaluated context.
762  if (Ty->isIncompleteType()) {
763  // C++11 [expr.call]p7:
764  // After these conversions, if the argument does not have arithmetic,
765  // enumeration, pointer, pointer to member, or class type, the program
766  // is ill-formed.
767  //
768  // Since we've already performed array-to-pointer and function-to-pointer
769  // decay, the only such type in C++ is cv void. This also handles
770  // initializer lists as variadic arguments.
771  if (Ty->isVoidType())
772  return VAK_Invalid;
773 
774  if (Ty->isObjCObjectType())
775  return VAK_Invalid;
776  return VAK_Valid;
777  }
778 
779  if (Ty.isCXX98PODType(Context))
780  return VAK_Valid;
781 
782  // C++11 [expr.call]p7:
783  // Passing a potentially-evaluated argument of class type (Clause 9)
784  // having a non-trivial copy constructor, a non-trivial move constructor,
785  // or a non-trivial destructor, with no corresponding parameter,
786  // is conditionally-supported with implementation-defined semantics.
787  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
788  if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
789  if (!Record->hasNonTrivialCopyConstructor() &&
790  !Record->hasNonTrivialMoveConstructor() &&
791  !Record->hasNonTrivialDestructor())
792  return VAK_ValidInCXX11;
793 
794  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
795  return VAK_Valid;
796 
797  if (Ty->isObjCObjectType())
798  return VAK_Invalid;
799 
800  if (getLangOpts().MSVCCompat)
801  return VAK_MSVCUndefined;
802 
803  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
804  // permitted to reject them. We should consider doing so.
805  return VAK_Undefined;
806 }
807 
809  // Don't allow one to pass an Objective-C interface to a vararg.
810  const QualType &Ty = E->getType();
811  VarArgKind VAK = isValidVarArgType(Ty);
812 
813  // Complain about passing non-POD types through varargs.
814  switch (VAK) {
815  case VAK_ValidInCXX11:
816  DiagRuntimeBehavior(
817  E->getLocStart(), nullptr,
818  PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
819  << Ty << CT);
820  // Fall through.
821  case VAK_Valid:
822  if (Ty->isRecordType()) {
823  // This is unlikely to be what the user intended. If the class has a
824  // 'c_str' member function, the user probably meant to call that.
825  DiagRuntimeBehavior(E->getLocStart(), nullptr,
826  PDiag(diag::warn_pass_class_arg_to_vararg)
827  << Ty << CT << hasCStrMethod(E) << ".c_str()");
828  }
829  break;
830 
831  case VAK_Undefined:
832  case VAK_MSVCUndefined:
833  DiagRuntimeBehavior(
834  E->getLocStart(), nullptr,
835  PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
836  << getLangOpts().CPlusPlus11 << Ty << CT);
837  break;
838 
839  case VAK_Invalid:
840  if (Ty->isObjCObjectType())
841  DiagRuntimeBehavior(
842  E->getLocStart(), nullptr,
843  PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
844  << Ty << CT);
845  else
846  Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
847  << isa<InitListExpr>(E) << Ty << CT;
848  break;
849  }
850 }
851 
852 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
853 /// will create a trap if the resulting type is not a POD type.
855  FunctionDecl *FDecl) {
856  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
857  // Strip the unbridged-cast placeholder expression off, if applicable.
858  if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
859  (CT == VariadicMethod ||
860  (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
861  E = stripARCUnbridgedCast(E);
862 
863  // Otherwise, do normal placeholder checking.
864  } else {
865  ExprResult ExprRes = CheckPlaceholderExpr(E);
866  if (ExprRes.isInvalid())
867  return ExprError();
868  E = ExprRes.get();
869  }
870  }
871 
872  ExprResult ExprRes = DefaultArgumentPromotion(E);
873  if (ExprRes.isInvalid())
874  return ExprError();
875  E = ExprRes.get();
876 
877  // Diagnostics regarding non-POD argument types are
878  // emitted along with format string checking in Sema::CheckFunctionCall().
879  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
880  // Turn this into a trap.
881  CXXScopeSpec SS;
882  SourceLocation TemplateKWLoc;
883  UnqualifiedId Name;
884  Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
885  E->getLocStart());
886  ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
887  Name, true, false);
888  if (TrapFn.isInvalid())
889  return ExprError();
890 
891  ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
892  E->getLocStart(), None,
893  E->getLocEnd());
894  if (Call.isInvalid())
895  return ExprError();
896 
897  ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
898  Call.get(), E);
899  if (Comma.isInvalid())
900  return ExprError();
901  return Comma.get();
902  }
903 
904  if (!getLangOpts().CPlusPlus &&
905  RequireCompleteType(E->getExprLoc(), E->getType(),
906  diag::err_call_incomplete_argument))
907  return ExprError();
908 
909  return E;
910 }
911 
912 /// \brief Converts an integer to complex float type. Helper function of
913 /// UsualArithmeticConversions()
914 ///
915 /// \return false if the integer expression is an integer type and is
916 /// successfully converted to the complex type.
918  ExprResult &ComplexExpr,
919  QualType IntTy,
920  QualType ComplexTy,
921  bool SkipCast) {
922  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
923  if (SkipCast) return false;
924  if (IntTy->isIntegerType()) {
925  QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
926  IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
927  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
928  CK_FloatingRealToComplex);
929  } else {
930  assert(IntTy->isComplexIntegerType());
931  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
932  CK_IntegralComplexToFloatingComplex);
933  }
934  return false;
935 }
936 
937 /// \brief Handle arithmetic conversion with complex types. Helper function of
938 /// UsualArithmeticConversions()
940  ExprResult &RHS, QualType LHSType,
941  QualType RHSType,
942  bool IsCompAssign) {
943  // if we have an integer operand, the result is the complex type.
944  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
945  /*skipCast*/false))
946  return LHSType;
947  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
948  /*skipCast*/IsCompAssign))
949  return RHSType;
950 
951  // This handles complex/complex, complex/float, or float/complex.
952  // When both operands are complex, the shorter operand is converted to the
953  // type of the longer, and that is the type of the result. This corresponds
954  // to what is done when combining two real floating-point operands.
955  // The fun begins when size promotion occur across type domains.
956  // From H&S 6.3.4: When one operand is complex and the other is a real
957  // floating-point type, the less precise type is converted, within it's
958  // real or complex domain, to the precision of the other type. For example,
959  // when combining a "long double" with a "double _Complex", the
960  // "double _Complex" is promoted to "long double _Complex".
961 
962  // Compute the rank of the two types, regardless of whether they are complex.
963  int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
964 
965  auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
966  auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
967  QualType LHSElementType =
968  LHSComplexType ? LHSComplexType->getElementType() : LHSType;
969  QualType RHSElementType =
970  RHSComplexType ? RHSComplexType->getElementType() : RHSType;
971 
972  QualType ResultType = S.Context.getComplexType(LHSElementType);
973  if (Order < 0) {
974  // Promote the precision of the LHS if not an assignment.
975  ResultType = S.Context.getComplexType(RHSElementType);
976  if (!IsCompAssign) {
977  if (LHSComplexType)
978  LHS =
979  S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
980  else
981  LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
982  }
983  } else if (Order > 0) {
984  // Promote the precision of the RHS.
985  if (RHSComplexType)
986  RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
987  else
988  RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
989  }
990  return ResultType;
991 }
992 
993 /// \brief Handle arithmetic conversion from integer to float. Helper function
994 /// of UsualArithmeticConversions()
996  ExprResult &IntExpr,
997  QualType FloatTy, QualType IntTy,
998  bool ConvertFloat, bool ConvertInt) {
999  if (IntTy->isIntegerType()) {
1000  if (ConvertInt)
1001  // Convert intExpr to the lhs floating point type.
1002  IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1003  CK_IntegralToFloating);
1004  return FloatTy;
1005  }
1006 
1007  // Convert both sides to the appropriate complex float.
1008  assert(IntTy->isComplexIntegerType());
1009  QualType result = S.Context.getComplexType(FloatTy);
1010 
1011  // _Complex int -> _Complex float
1012  if (ConvertInt)
1013  IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1014  CK_IntegralComplexToFloatingComplex);
1015 
1016  // float -> _Complex float
1017  if (ConvertFloat)
1018  FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1019  CK_FloatingRealToComplex);
1020 
1021  return result;
1022 }
1023 
1024 /// \brief Handle arithmethic conversion with floating point types. Helper
1025 /// function of UsualArithmeticConversions()
1027  ExprResult &RHS, QualType LHSType,
1028  QualType RHSType, bool IsCompAssign) {
1029  bool LHSFloat = LHSType->isRealFloatingType();
1030  bool RHSFloat = RHSType->isRealFloatingType();
1031 
1032  // If we have two real floating types, convert the smaller operand
1033  // to the bigger result.
1034  if (LHSFloat && RHSFloat) {
1035  int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1036  if (order > 0) {
1037  RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1038  return LHSType;
1039  }
1040 
1041  assert(order < 0 && "illegal float comparison");
1042  if (!IsCompAssign)
1043  LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1044  return RHSType;
1045  }
1046 
1047  if (LHSFloat) {
1048  // Half FP has to be promoted to float unless it is natively supported
1049  if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1050  LHSType = S.Context.FloatTy;
1051 
1052  return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1053  /*convertFloat=*/!IsCompAssign,
1054  /*convertInt=*/ true);
1055  }
1056  assert(RHSFloat);
1057  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1058  /*convertInt=*/ true,
1059  /*convertFloat=*/!IsCompAssign);
1060 }
1061 
1062 /// \brief Diagnose attempts to convert between __float128 and long double if
1063 /// there is no support for such conversion. Helper function of
1064 /// UsualArithmeticConversions().
1065 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1066  QualType RHSType) {
1067  /* No issue converting if at least one of the types is not a floating point
1068  type or the two types have the same rank.
1069  */
1070  if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1071  S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1072  return false;
1073 
1074  assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1075  "The remaining types must be floating point types.");
1076 
1077  auto *LHSComplex = LHSType->getAs<ComplexType>();
1078  auto *RHSComplex = RHSType->getAs<ComplexType>();
1079 
1080  QualType LHSElemType = LHSComplex ?
1081  LHSComplex->getElementType() : LHSType;
1082  QualType RHSElemType = RHSComplex ?
1083  RHSComplex->getElementType() : RHSType;
1084 
1085  // No issue if the two types have the same representation
1086  if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1087  &S.Context.getFloatTypeSemantics(RHSElemType))
1088  return false;
1089 
1090  bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1091  RHSElemType == S.Context.LongDoubleTy);
1092  Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1093  RHSElemType == S.Context.Float128Ty);
1094 
1095  /* We've handled the situation where __float128 and long double have the same
1096  representation. The only other allowable conversion is if long double is
1097  really just double.
1098  */
1099  return Float128AndLongDouble &&
1101  &llvm::APFloat::IEEEdouble());
1102 }
1103 
1104 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1105 
1106 namespace {
1107 /// These helper callbacks are placed in an anonymous namespace to
1108 /// permit their use as function template parameters.
1109 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1110  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1111 }
1112 
1113 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1114  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1115  CK_IntegralComplexCast);
1116 }
1117 }
1118 
1119 /// \brief Handle integer arithmetic conversions. Helper function of
1120 /// UsualArithmeticConversions()
1121 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1123  ExprResult &RHS, QualType LHSType,
1124  QualType RHSType, bool IsCompAssign) {
1125  // The rules for this case are in C99 6.3.1.8
1126  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1127  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1128  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1129  if (LHSSigned == RHSSigned) {
1130  // Same signedness; use the higher-ranked type
1131  if (order >= 0) {
1132  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1133  return LHSType;
1134  } else if (!IsCompAssign)
1135  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1136  return RHSType;
1137  } else if (order != (LHSSigned ? 1 : -1)) {
1138  // The unsigned type has greater than or equal rank to the
1139  // signed type, so use the unsigned type
1140  if (RHSSigned) {
1141  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1142  return LHSType;
1143  } else if (!IsCompAssign)
1144  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1145  return RHSType;
1146  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1147  // The two types are different widths; if we are here, that
1148  // means the signed type is larger than the unsigned type, so
1149  // use the signed type.
1150  if (LHSSigned) {
1151  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1152  return LHSType;
1153  } else if (!IsCompAssign)
1154  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1155  return RHSType;
1156  } else {
1157  // The signed type is higher-ranked than the unsigned type,
1158  // but isn't actually any bigger (like unsigned int and long
1159  // on most 32-bit systems). Use the unsigned type corresponding
1160  // to the signed type.
1161  QualType result =
1162  S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1163  RHS = (*doRHSCast)(S, RHS.get(), result);
1164  if (!IsCompAssign)
1165  LHS = (*doLHSCast)(S, LHS.get(), result);
1166  return result;
1167  }
1168 }
1169 
1170 /// \brief Handle conversions with GCC complex int extension. Helper function
1171 /// of UsualArithmeticConversions()
1173  ExprResult &RHS, QualType LHSType,
1174  QualType RHSType,
1175  bool IsCompAssign) {
1176  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1177  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1178 
1179  if (LHSComplexInt && RHSComplexInt) {
1180  QualType LHSEltType = LHSComplexInt->getElementType();
1181  QualType RHSEltType = RHSComplexInt->getElementType();
1182  QualType ScalarType =
1183  handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1184  (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1185 
1186  return S.Context.getComplexType(ScalarType);
1187  }
1188 
1189  if (LHSComplexInt) {
1190  QualType LHSEltType = LHSComplexInt->getElementType();
1191  QualType ScalarType =
1192  handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1193  (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1194  QualType ComplexType = S.Context.getComplexType(ScalarType);
1195  RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1196  CK_IntegralRealToComplex);
1197 
1198  return ComplexType;
1199  }
1200 
1201  assert(RHSComplexInt);
1202 
1203  QualType RHSEltType = RHSComplexInt->getElementType();
1204  QualType ScalarType =
1205  handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1206  (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1207  QualType ComplexType = S.Context.getComplexType(ScalarType);
1208 
1209  if (!IsCompAssign)
1210  LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1211  CK_IntegralRealToComplex);
1212  return ComplexType;
1213 }
1214 
1215 /// UsualArithmeticConversions - Performs various conversions that are common to
1216 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1217 /// routine returns the first non-arithmetic type found. The client is
1218 /// responsible for emitting appropriate error diagnostics.
1220  bool IsCompAssign) {
1221  if (!IsCompAssign) {
1222  LHS = UsualUnaryConversions(LHS.get());
1223  if (LHS.isInvalid())
1224  return QualType();
1225  }
1226 
1227  RHS = UsualUnaryConversions(RHS.get());
1228  if (RHS.isInvalid())
1229  return QualType();
1230 
1231  // For conversion purposes, we ignore any qualifiers.
1232  // For example, "const float" and "float" are equivalent.
1233  QualType LHSType =
1234  Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1235  QualType RHSType =
1236  Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1237 
1238  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1239  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1240  LHSType = AtomicLHS->getValueType();
1241 
1242  // If both types are identical, no conversion is needed.
1243  if (LHSType == RHSType)
1244  return LHSType;
1245 
1246  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1247  // The caller can deal with this (e.g. pointer + int).
1248  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1249  return QualType();
1250 
1251  // Apply unary and bitfield promotions to the LHS's type.
1252  QualType LHSUnpromotedType = LHSType;
1253  if (LHSType->isPromotableIntegerType())
1254  LHSType = Context.getPromotedIntegerType(LHSType);
1255  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1256  if (!LHSBitfieldPromoteTy.isNull())
1257  LHSType = LHSBitfieldPromoteTy;
1258  if (LHSType != LHSUnpromotedType && !IsCompAssign)
1259  LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1260 
1261  // If both types are identical, no conversion is needed.
1262  if (LHSType == RHSType)
1263  return LHSType;
1264 
1265  // At this point, we have two different arithmetic types.
1266 
1267  // Diagnose attempts to convert between __float128 and long double where
1268  // such conversions currently can't be handled.
1269  if (unsupportedTypeConversion(*this, LHSType, RHSType))
1270  return QualType();
1271 
1272  // Handle complex types first (C99 6.3.1.8p1).
1273  if (LHSType->isComplexType() || RHSType->isComplexType())
1274  return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1275  IsCompAssign);
1276 
1277  // Now handle "real" floating types (i.e. float, double, long double).
1278  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1279  return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1280  IsCompAssign);
1281 
1282  // Handle GCC complex int extension.
1283  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1284  return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1285  IsCompAssign);
1286 
1287  // Finally, we have two differing integer types.
1288  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1289  (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1290 }
1291 
1292 
1293 //===----------------------------------------------------------------------===//
1294 // Semantic Analysis for various Expression Types
1295 //===----------------------------------------------------------------------===//
1296 
1297 
1298 ExprResult
1300  SourceLocation DefaultLoc,
1301  SourceLocation RParenLoc,
1302  Expr *ControllingExpr,
1303  ArrayRef<ParsedType> ArgTypes,
1304  ArrayRef<Expr *> ArgExprs) {
1305  unsigned NumAssocs = ArgTypes.size();
1306  assert(NumAssocs == ArgExprs.size());
1307 
1308  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1309  for (unsigned i = 0; i < NumAssocs; ++i) {
1310  if (ArgTypes[i])
1311  (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1312  else
1313  Types[i] = nullptr;
1314  }
1315 
1316  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1317  ControllingExpr,
1318  llvm::makeArrayRef(Types, NumAssocs),
1319  ArgExprs);
1320  delete [] Types;
1321  return ER;
1322 }
1323 
1324 ExprResult
1326  SourceLocation DefaultLoc,
1327  SourceLocation RParenLoc,
1328  Expr *ControllingExpr,
1330  ArrayRef<Expr *> Exprs) {
1331  unsigned NumAssocs = Types.size();
1332  assert(NumAssocs == Exprs.size());
1333 
1334  // Decay and strip qualifiers for the controlling expression type, and handle
1335  // placeholder type replacement. See committee discussion from WG14 DR423.
1336  {
1339  ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1340  if (R.isInvalid())
1341  return ExprError();
1342  ControllingExpr = R.get();
1343  }
1344 
1345  // The controlling expression is an unevaluated operand, so side effects are
1346  // likely unintended.
1347  if (!inTemplateInstantiation() &&
1348  ControllingExpr->HasSideEffects(Context, false))
1349  Diag(ControllingExpr->getExprLoc(),
1350  diag::warn_side_effects_unevaluated_context);
1351 
1352  bool TypeErrorFound = false,
1353  IsResultDependent = ControllingExpr->isTypeDependent(),
1354  ContainsUnexpandedParameterPack
1355  = ControllingExpr->containsUnexpandedParameterPack();
1356 
1357  for (unsigned i = 0; i < NumAssocs; ++i) {
1358  if (Exprs[i]->containsUnexpandedParameterPack())
1359  ContainsUnexpandedParameterPack = true;
1360 
1361  if (Types[i]) {
1362  if (Types[i]->getType()->containsUnexpandedParameterPack())
1363  ContainsUnexpandedParameterPack = true;
1364 
1365  if (Types[i]->getType()->isDependentType()) {
1366  IsResultDependent = true;
1367  } else {
1368  // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1369  // complete object type other than a variably modified type."
1370  unsigned D = 0;
1371  if (Types[i]->getType()->isIncompleteType())
1372  D = diag::err_assoc_type_incomplete;
1373  else if (!Types[i]->getType()->isObjectType())
1374  D = diag::err_assoc_type_nonobject;
1375  else if (Types[i]->getType()->isVariablyModifiedType())
1376  D = diag::err_assoc_type_variably_modified;
1377 
1378  if (D != 0) {
1379  Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1380  << Types[i]->getTypeLoc().getSourceRange()
1381  << Types[i]->getType();
1382  TypeErrorFound = true;
1383  }
1384 
1385  // C11 6.5.1.1p2 "No two generic associations in the same generic
1386  // selection shall specify compatible types."
1387  for (unsigned j = i+1; j < NumAssocs; ++j)
1388  if (Types[j] && !Types[j]->getType()->isDependentType() &&
1389  Context.typesAreCompatible(Types[i]->getType(),
1390  Types[j]->getType())) {
1391  Diag(Types[j]->getTypeLoc().getBeginLoc(),
1392  diag::err_assoc_compatible_types)
1393  << Types[j]->getTypeLoc().getSourceRange()
1394  << Types[j]->getType()
1395  << Types[i]->getType();
1396  Diag(Types[i]->getTypeLoc().getBeginLoc(),
1397  diag::note_compat_assoc)
1398  << Types[i]->getTypeLoc().getSourceRange()
1399  << Types[i]->getType();
1400  TypeErrorFound = true;
1401  }
1402  }
1403  }
1404  }
1405  if (TypeErrorFound)
1406  return ExprError();
1407 
1408  // If we determined that the generic selection is result-dependent, don't
1409  // try to compute the result expression.
1410  if (IsResultDependent)
1411  return new (Context) GenericSelectionExpr(
1412  Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1413  ContainsUnexpandedParameterPack);
1414 
1415  SmallVector<unsigned, 1> CompatIndices;
1416  unsigned DefaultIndex = -1U;
1417  for (unsigned i = 0; i < NumAssocs; ++i) {
1418  if (!Types[i])
1419  DefaultIndex = i;
1420  else if (Context.typesAreCompatible(ControllingExpr->getType(),
1421  Types[i]->getType()))
1422  CompatIndices.push_back(i);
1423  }
1424 
1425  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1426  // type compatible with at most one of the types named in its generic
1427  // association list."
1428  if (CompatIndices.size() > 1) {
1429  // We strip parens here because the controlling expression is typically
1430  // parenthesized in macro definitions.
1431  ControllingExpr = ControllingExpr->IgnoreParens();
1432  Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1433  << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1434  << (unsigned) CompatIndices.size();
1435  for (unsigned I : CompatIndices) {
1436  Diag(Types[I]->getTypeLoc().getBeginLoc(),
1437  diag::note_compat_assoc)
1438  << Types[I]->getTypeLoc().getSourceRange()
1439  << Types[I]->getType();
1440  }
1441  return ExprError();
1442  }
1443 
1444  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1445  // its controlling expression shall have type compatible with exactly one of
1446  // the types named in its generic association list."
1447  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1448  // We strip parens here because the controlling expression is typically
1449  // parenthesized in macro definitions.
1450  ControllingExpr = ControllingExpr->IgnoreParens();
1451  Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1452  << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1453  return ExprError();
1454  }
1455 
1456  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1457  // type name that is compatible with the type of the controlling expression,
1458  // then the result expression of the generic selection is the expression
1459  // in that generic association. Otherwise, the result expression of the
1460  // generic selection is the expression in the default generic association."
1461  unsigned ResultIndex =
1462  CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1463 
1464  return new (Context) GenericSelectionExpr(
1465  Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1466  ContainsUnexpandedParameterPack, ResultIndex);
1467 }
1468 
1469 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1470 /// location of the token and the offset of the ud-suffix within it.
1472  unsigned Offset) {
1473  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1474  S.getLangOpts());
1475 }
1476 
1477 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1478 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1480  IdentifierInfo *UDSuffix,
1481  SourceLocation UDSuffixLoc,
1482  ArrayRef<Expr*> Args,
1483  SourceLocation LitEndLoc) {
1484  assert(Args.size() <= 2 && "too many arguments for literal operator");
1485 
1486  QualType ArgTy[2];
1487  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1488  ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1489  if (ArgTy[ArgIdx]->isArrayType())
1490  ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1491  }
1492 
1493  DeclarationName OpName =
1495  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1496  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1497 
1498  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1499  if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1500  /*AllowRaw*/ false, /*AllowTemplate*/ false,
1501  /*AllowStringTemplate*/ false,
1502  /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1503  return ExprError();
1504 
1505  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1506 }
1507 
1508 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1509 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1510 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1511 /// multiple tokens. However, the common case is that StringToks points to one
1512 /// string.
1513 ///
1514 ExprResult
1516  assert(!StringToks.empty() && "Must have at least one string!");
1517 
1518  StringLiteralParser Literal(StringToks, PP);
1519  if (Literal.hadError)
1520  return ExprError();
1521 
1522  SmallVector<SourceLocation, 4> StringTokLocs;
1523  for (const Token &Tok : StringToks)
1524  StringTokLocs.push_back(Tok.getLocation());
1525 
1526  QualType CharTy = Context.CharTy;
1528  if (Literal.isWide()) {
1529  CharTy = Context.getWideCharType();
1530  Kind = StringLiteral::Wide;
1531  } else if (Literal.isUTF8()) {
1532  Kind = StringLiteral::UTF8;
1533  } else if (Literal.isUTF16()) {
1534  CharTy = Context.Char16Ty;
1535  Kind = StringLiteral::UTF16;
1536  } else if (Literal.isUTF32()) {
1537  CharTy = Context.Char32Ty;
1538  Kind = StringLiteral::UTF32;
1539  } else if (Literal.isPascal()) {
1540  CharTy = Context.UnsignedCharTy;
1541  }
1542 
1543  QualType CharTyConst = CharTy;
1544  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1545  if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1546  CharTyConst.addConst();
1547 
1548  // Get an array type for the string, according to C99 6.4.5. This includes
1549  // the nul terminator character as well as the string length for pascal
1550  // strings.
1551  QualType StrTy = Context.getConstantArrayType(CharTyConst,
1552  llvm::APInt(32, Literal.GetNumStringChars()+1),
1553  ArrayType::Normal, 0);
1554 
1555  // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1556  if (getLangOpts().OpenCL) {
1557  StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1558  }
1559 
1560  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1561  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1562  Kind, Literal.Pascal, StrTy,
1563  &StringTokLocs[0],
1564  StringTokLocs.size());
1565  if (Literal.getUDSuffix().empty())
1566  return Lit;
1567 
1568  // We're building a user-defined literal.
1569  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1570  SourceLocation UDSuffixLoc =
1571  getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1572  Literal.getUDSuffixOffset());
1573 
1574  // Make sure we're allowed user-defined literals here.
1575  if (!UDLScope)
1576  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1577 
1578  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1579  // operator "" X (str, len)
1580  QualType SizeType = Context.getSizeType();
1581 
1582  DeclarationName OpName =
1583  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1584  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1585  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1586 
1587  QualType ArgTy[] = {
1588  Context.getArrayDecayedType(StrTy), SizeType
1589  };
1590 
1591  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1592  switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1593  /*AllowRaw*/ false, /*AllowTemplate*/ false,
1594  /*AllowStringTemplate*/ true,
1595  /*DiagnoseMissing*/ true)) {
1596 
1597  case LOLR_Cooked: {
1598  llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1599  IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1600  StringTokLocs[0]);
1601  Expr *Args[] = { Lit, LenArg };
1602 
1603  return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1604  }
1605 
1606  case LOLR_StringTemplate: {
1607  TemplateArgumentListInfo ExplicitArgs;
1608 
1609  unsigned CharBits = Context.getIntWidth(CharTy);
1610  bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1611  llvm::APSInt Value(CharBits, CharIsUnsigned);
1612 
1613  TemplateArgument TypeArg(CharTy);
1614  TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1615  ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1616 
1617  for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1618  Value = Lit->getCodeUnit(I);
1619  TemplateArgument Arg(Context, Value, CharTy);
1620  TemplateArgumentLocInfo ArgInfo;
1621  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1622  }
1623  return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1624  &ExplicitArgs);
1625  }
1626  case LOLR_Raw:
1627  case LOLR_Template:
1628  case LOLR_ErrorNoDiagnostic:
1629  llvm_unreachable("unexpected literal operator lookup result");
1630  case LOLR_Error:
1631  return ExprError();
1632  }
1633  llvm_unreachable("unexpected literal operator lookup result");
1634 }
1635 
1636 ExprResult
1638  SourceLocation Loc,
1639  const CXXScopeSpec *SS) {
1640  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1641  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1642 }
1643 
1644 /// BuildDeclRefExpr - Build an expression that references a
1645 /// declaration that does not require a closure capture.
1646 ExprResult
1648  const DeclarationNameInfo &NameInfo,
1649  const CXXScopeSpec *SS, NamedDecl *FoundD,
1650  const TemplateArgumentListInfo *TemplateArgs) {
1651  bool RefersToCapturedVariable =
1652  isa<VarDecl>(D) &&
1653  NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1654 
1655  DeclRefExpr *E;
1656  if (isa<VarTemplateSpecializationDecl>(D)) {
1658  cast<VarTemplateSpecializationDecl>(D);
1659 
1660  E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1662  VarSpec->getTemplateKeywordLoc(), D,
1663  RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1664  FoundD, TemplateArgs);
1665  } else {
1666  assert(!TemplateArgs && "No template arguments for non-variable"
1667  " template specialization references");
1668  E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1670  SourceLocation(), D, RefersToCapturedVariable,
1671  NameInfo, Ty, VK, FoundD);
1672  }
1673 
1674  MarkDeclRefReferenced(E);
1675 
1676  if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1678  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1679  recordUseOfEvaluatedWeak(E);
1680 
1681  FieldDecl *FD = dyn_cast<FieldDecl>(D);
1682  if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1683  FD = IFD->getAnonField();
1684  if (FD) {
1685  UnusedPrivateFields.remove(FD);
1686  // Just in case we're building an illegal pointer-to-member.
1687  if (FD->isBitField())
1688  E->setObjectKind(OK_BitField);
1689  }
1690 
1691  // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1692  // designates a bit-field.
1693  if (auto *BD = dyn_cast<BindingDecl>(D))
1694  if (auto *BE = BD->getBinding())
1695  E->setObjectKind(BE->getObjectKind());
1696 
1697  return E;
1698 }
1699 
1700 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1701 /// possibly a list of template arguments.
1702 ///
1703 /// If this produces template arguments, it is permitted to call
1704 /// DecomposeTemplateName.
1705 ///
1706 /// This actually loses a lot of source location information for
1707 /// non-standard name kinds; we should consider preserving that in
1708 /// some way.
1709 void
1711  TemplateArgumentListInfo &Buffer,
1712  DeclarationNameInfo &NameInfo,
1713  const TemplateArgumentListInfo *&TemplateArgs) {
1714  if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1715  Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1716  Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1717 
1718  ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1719  Id.TemplateId->NumArgs);
1720  translateTemplateArguments(TemplateArgsPtr, Buffer);
1721 
1722  TemplateName TName = Id.TemplateId->Template.get();
1723  SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1724  NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1725  TemplateArgs = &Buffer;
1726  } else {
1727  NameInfo = GetNameFromUnqualifiedId(Id);
1728  TemplateArgs = nullptr;
1729  }
1730 }
1731 
1733  const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1734  DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1735  unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1736  DeclContext *Ctx =
1737  SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1738  if (!TC) {
1739  // Emit a special diagnostic for failed member lookups.
1740  // FIXME: computing the declaration context might fail here (?)
1741  if (Ctx)
1742  SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1743  << SS.getRange();
1744  else
1745  SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1746  return;
1747  }
1748 
1749  std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1750  bool DroppedSpecifier =
1751  TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1752  unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1753  ? diag::note_implicit_param_decl
1754  : diag::note_previous_decl;
1755  if (!Ctx)
1756  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1757  SemaRef.PDiag(NoteID));
1758  else
1759  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1760  << Typo << Ctx << DroppedSpecifier
1761  << SS.getRange(),
1762  SemaRef.PDiag(NoteID));
1763 }
1764 
1765 /// Diagnose an empty lookup.
1766 ///
1767 /// \return false if new lookup candidates were found
1768 bool
1770  std::unique_ptr<CorrectionCandidateCallback> CCC,
1771  TemplateArgumentListInfo *ExplicitTemplateArgs,
1772  ArrayRef<Expr *> Args, TypoExpr **Out) {
1773  DeclarationName Name = R.getLookupName();
1774 
1775  unsigned diagnostic = diag::err_undeclared_var_use;
1776  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1780  diagnostic = diag::err_undeclared_use;
1781  diagnostic_suggest = diag::err_undeclared_use_suggest;
1782  }
1783 
1784  // If the original lookup was an unqualified lookup, fake an
1785  // unqualified lookup. This is useful when (for example) the
1786  // original lookup would not have found something because it was a
1787  // dependent name.
1788  DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1789  while (DC) {
1790  if (isa<CXXRecordDecl>(DC)) {
1791  LookupQualifiedName(R, DC);
1792 
1793  if (!R.empty()) {
1794  // Don't give errors about ambiguities in this lookup.
1795  R.suppressDiagnostics();
1796 
1797  // During a default argument instantiation the CurContext points
1798  // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1799  // function parameter list, hence add an explicit check.
1800  bool isDefaultArgument =
1801  !CodeSynthesisContexts.empty() &&
1802  CodeSynthesisContexts.back().Kind ==
1803  CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1804  CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1805  bool isInstance = CurMethod &&
1806  CurMethod->isInstance() &&
1807  DC == CurMethod->getParent() && !isDefaultArgument;
1808 
1809  // Give a code modification hint to insert 'this->'.
1810  // TODO: fixit for inserting 'Base<T>::' in the other cases.
1811  // Actually quite difficult!
1812  if (getLangOpts().MSVCCompat)
1813  diagnostic = diag::ext_found_via_dependent_bases_lookup;
1814  if (isInstance) {
1815  Diag(R.getNameLoc(), diagnostic) << Name
1816  << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1817  CheckCXXThisCapture(R.getNameLoc());
1818  } else {
1819  Diag(R.getNameLoc(), diagnostic) << Name;
1820  }
1821 
1822  // Do we really want to note all of these?
1823  for (NamedDecl *D : R)
1824  Diag(D->getLocation(), diag::note_dependent_var_use);
1825 
1826  // Return true if we are inside a default argument instantiation
1827  // and the found name refers to an instance member function, otherwise
1828  // the function calling DiagnoseEmptyLookup will try to create an
1829  // implicit member call and this is wrong for default argument.
1830  if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1831  Diag(R.getNameLoc(), diag::err_member_call_without_object);
1832  return true;
1833  }
1834 
1835  // Tell the callee to try to recover.
1836  return false;
1837  }
1838 
1839  R.clear();
1840  }
1841 
1842  // In Microsoft mode, if we are performing lookup from within a friend
1843  // function definition declared at class scope then we must set
1844  // DC to the lexical parent to be able to search into the parent
1845  // class.
1846  if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1847  cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1848  DC->getLexicalParent()->isRecord())
1849  DC = DC->getLexicalParent();
1850  else
1851  DC = DC->getParent();
1852  }
1853 
1854  // We didn't find anything, so try to correct for a typo.
1855  TypoCorrection Corrected;
1856  if (S && Out) {
1857  SourceLocation TypoLoc = R.getNameLoc();
1858  assert(!ExplicitTemplateArgs &&
1859  "Diagnosing an empty lookup with explicit template args!");
1860  *Out = CorrectTypoDelayed(
1861  R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1862  [=](const TypoCorrection &TC) {
1863  emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1864  diagnostic, diagnostic_suggest);
1865  },
1866  nullptr, CTK_ErrorRecovery);
1867  if (*Out)
1868  return true;
1869  } else if (S && (Corrected =
1870  CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1871  &SS, std::move(CCC), CTK_ErrorRecovery))) {
1872  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1873  bool DroppedSpecifier =
1874  Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1875  R.setLookupName(Corrected.getCorrection());
1876 
1877  bool AcceptableWithRecovery = false;
1878  bool AcceptableWithoutRecovery = false;
1879  NamedDecl *ND = Corrected.getFoundDecl();
1880  if (ND) {
1881  if (Corrected.isOverloaded()) {
1885  for (NamedDecl *CD : Corrected) {
1886  if (FunctionTemplateDecl *FTD =
1887  dyn_cast<FunctionTemplateDecl>(CD))
1888  AddTemplateOverloadCandidate(
1889  FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1890  Args, OCS);
1891  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1892  if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1893  AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1894  Args, OCS);
1895  }
1896  switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1897  case OR_Success:
1898  ND = Best->FoundDecl;
1899  Corrected.setCorrectionDecl(ND);
1900  break;
1901  default:
1902  // FIXME: Arbitrarily pick the first declaration for the note.
1903  Corrected.setCorrectionDecl(ND);
1904  break;
1905  }
1906  }
1907  R.addDecl(ND);
1908  if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1909  CXXRecordDecl *Record = nullptr;
1910  if (Corrected.getCorrectionSpecifier()) {
1911  const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1912  Record = Ty->getAsCXXRecordDecl();
1913  }
1914  if (!Record)
1915  Record = cast<CXXRecordDecl>(
1916  ND->getDeclContext()->getRedeclContext());
1917  R.setNamingClass(Record);
1918  }
1919 
1920  auto *UnderlyingND = ND->getUnderlyingDecl();
1921  AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1922  isa<FunctionTemplateDecl>(UnderlyingND);
1923  // FIXME: If we ended up with a typo for a type name or
1924  // Objective-C class name, we're in trouble because the parser
1925  // is in the wrong place to recover. Suggest the typo
1926  // correction, but don't make it a fix-it since we're not going
1927  // to recover well anyway.
1928  AcceptableWithoutRecovery =
1929  isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1930  } else {
1931  // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1932  // because we aren't able to recover.
1933  AcceptableWithoutRecovery = true;
1934  }
1935 
1936  if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1937  unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1938  ? diag::note_implicit_param_decl
1939  : diag::note_previous_decl;
1940  if (SS.isEmpty())
1941  diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1942  PDiag(NoteID), AcceptableWithRecovery);
1943  else
1944  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1945  << Name << computeDeclContext(SS, false)
1946  << DroppedSpecifier << SS.getRange(),
1947  PDiag(NoteID), AcceptableWithRecovery);
1948 
1949  // Tell the callee whether to try to recover.
1950  return !AcceptableWithRecovery;
1951  }
1952  }
1953  R.clear();
1954 
1955  // Emit a special diagnostic for failed member lookups.
1956  // FIXME: computing the declaration context might fail here (?)
1957  if (!SS.isEmpty()) {
1958  Diag(R.getNameLoc(), diag::err_no_member)
1959  << Name << computeDeclContext(SS, false)
1960  << SS.getRange();
1961  return true;
1962  }
1963 
1964  // Give up, we can't recover.
1965  Diag(R.getNameLoc(), diagnostic) << Name;
1966  return true;
1967 }
1968 
1969 /// In Microsoft mode, if we are inside a template class whose parent class has
1970 /// dependent base classes, and we can't resolve an unqualified identifier, then
1971 /// assume the identifier is a member of a dependent base class. We can only
1972 /// recover successfully in static methods, instance methods, and other contexts
1973 /// where 'this' is available. This doesn't precisely match MSVC's
1974 /// instantiation model, but it's close enough.
1975 static Expr *
1977  DeclarationNameInfo &NameInfo,
1978  SourceLocation TemplateKWLoc,
1979  const TemplateArgumentListInfo *TemplateArgs) {
1980  // Only try to recover from lookup into dependent bases in static methods or
1981  // contexts where 'this' is available.
1982  QualType ThisType = S.getCurrentThisType();
1983  const CXXRecordDecl *RD = nullptr;
1984  if (!ThisType.isNull())
1985  RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1986  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1987  RD = MD->getParent();
1988  if (!RD || !RD->hasAnyDependentBases())
1989  return nullptr;
1990 
1991  // Diagnose this as unqualified lookup into a dependent base class. If 'this'
1992  // is available, suggest inserting 'this->' as a fixit.
1993  SourceLocation Loc = NameInfo.getLoc();
1994  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1995  DB << NameInfo.getName() << RD;
1996 
1997  if (!ThisType.isNull()) {
1998  DB << FixItHint::CreateInsertion(Loc, "this->");
2000  Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2001  /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2002  /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2003  }
2004 
2005  // Synthesize a fake NNS that points to the derived class. This will
2006  // perform name lookup during template instantiation.
2007  CXXScopeSpec SS;
2008  auto *NNS =
2009  NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2010  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2012  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2013  TemplateArgs);
2014 }
2015 
2016 ExprResult
2018  SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2019  bool HasTrailingLParen, bool IsAddressOfOperand,
2020  std::unique_ptr<CorrectionCandidateCallback> CCC,
2021  bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2022  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2023  "cannot be direct & operand and have a trailing lparen");
2024  if (SS.isInvalid())
2025  return ExprError();
2026 
2027  TemplateArgumentListInfo TemplateArgsBuffer;
2028 
2029  // Decompose the UnqualifiedId into the following data.
2030  DeclarationNameInfo NameInfo;
2031  const TemplateArgumentListInfo *TemplateArgs;
2032  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2033 
2034  DeclarationName Name = NameInfo.getName();
2035  IdentifierInfo *II = Name.getAsIdentifierInfo();
2036  SourceLocation NameLoc = NameInfo.getLoc();
2037 
2038  if (II && II->isEditorPlaceholder()) {
2039  // FIXME: When typed placeholders are supported we can create a typed
2040  // placeholder expression node.
2041  return ExprError();
2042  }
2043 
2044  // C++ [temp.dep.expr]p3:
2045  // An id-expression is type-dependent if it contains:
2046  // -- an identifier that was declared with a dependent type,
2047  // (note: handled after lookup)
2048  // -- a template-id that is dependent,
2049  // (note: handled in BuildTemplateIdExpr)
2050  // -- a conversion-function-id that specifies a dependent type,
2051  // -- a nested-name-specifier that contains a class-name that
2052  // names a dependent type.
2053  // Determine whether this is a member of an unknown specialization;
2054  // we need to handle these differently.
2055  bool DependentID = false;
2057  Name.getCXXNameType()->isDependentType()) {
2058  DependentID = true;
2059  } else if (SS.isSet()) {
2060  if (DeclContext *DC = computeDeclContext(SS, false)) {
2061  if (RequireCompleteDeclContext(SS, DC))
2062  return ExprError();
2063  } else {
2064  DependentID = true;
2065  }
2066  }
2067 
2068  if (DependentID)
2069  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2070  IsAddressOfOperand, TemplateArgs);
2071 
2072  // Perform the required lookup.
2073  LookupResult R(*this, NameInfo,
2075  ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2076  if (TemplateArgs) {
2077  // Lookup the template name again to correctly establish the context in
2078  // which it was found. This is really unfortunate as we already did the
2079  // lookup to determine that it was a template name in the first place. If
2080  // this becomes a performance hit, we can work harder to preserve those
2081  // results until we get here but it's likely not worth it.
2082  bool MemberOfUnknownSpecialization;
2083  LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2084  MemberOfUnknownSpecialization);
2085 
2086  if (MemberOfUnknownSpecialization ||
2088  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2089  IsAddressOfOperand, TemplateArgs);
2090  } else {
2091  bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2092  LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2093 
2094  // If the result might be in a dependent base class, this is a dependent
2095  // id-expression.
2097  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2098  IsAddressOfOperand, TemplateArgs);
2099 
2100  // If this reference is in an Objective-C method, then we need to do
2101  // some special Objective-C lookup, too.
2102  if (IvarLookupFollowUp) {
2103  ExprResult E(LookupInObjCMethod(R, S, II, true));
2104  if (E.isInvalid())
2105  return ExprError();
2106 
2107  if (Expr *Ex = E.getAs<Expr>())
2108  return Ex;
2109  }
2110  }
2111 
2112  if (R.isAmbiguous())
2113  return ExprError();
2114 
2115  // This could be an implicitly declared function reference (legal in C90,
2116  // extension in C99, forbidden in C++).
2117  if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2118  NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2119  if (D) R.addDecl(D);
2120  }
2121 
2122  // Determine whether this name might be a candidate for
2123  // argument-dependent lookup.
2124  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2125 
2126  if (R.empty() && !ADL) {
2127  if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2128  if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2129  TemplateKWLoc, TemplateArgs))
2130  return E;
2131  }
2132 
2133  // Don't diagnose an empty lookup for inline assembly.
2134  if (IsInlineAsmIdentifier)
2135  return ExprError();
2136 
2137  // If this name wasn't predeclared and if this is not a function
2138  // call, diagnose the problem.
2139  TypoExpr *TE = nullptr;
2140  auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2141  II, SS.isValid() ? SS.getScopeRep() : nullptr);
2142  DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2143  assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2144  "Typo correction callback misconfigured");
2145  if (CCC) {
2146  // Make sure the callback knows what the typo being diagnosed is.
2147  CCC->setTypoName(II);
2148  if (SS.isValid())
2149  CCC->setTypoNNS(SS.getScopeRep());
2150  }
2151  if (DiagnoseEmptyLookup(S, SS, R,
2152  CCC ? std::move(CCC) : std::move(DefaultValidator),
2153  nullptr, None, &TE)) {
2154  if (TE && KeywordReplacement) {
2155  auto &State = getTypoExprState(TE);
2156  auto BestTC = State.Consumer->getNextCorrection();
2157  if (BestTC.isKeyword()) {
2158  auto *II = BestTC.getCorrectionAsIdentifierInfo();
2159  if (State.DiagHandler)
2160  State.DiagHandler(BestTC);
2161  KeywordReplacement->startToken();
2162  KeywordReplacement->setKind(II->getTokenID());
2163  KeywordReplacement->setIdentifierInfo(II);
2164  KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2165  // Clean up the state associated with the TypoExpr, since it has
2166  // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2167  clearDelayedTypo(TE);
2168  // Signal that a correction to a keyword was performed by returning a
2169  // valid-but-null ExprResult.
2170  return (Expr*)nullptr;
2171  }
2172  State.Consumer->resetCorrectionStream();
2173  }
2174  return TE ? TE : ExprError();
2175  }
2176 
2177  assert(!R.empty() &&
2178  "DiagnoseEmptyLookup returned false but added no results");
2179 
2180  // If we found an Objective-C instance variable, let
2181  // LookupInObjCMethod build the appropriate expression to
2182  // reference the ivar.
2183  if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2184  R.clear();
2185  ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2186  // In a hopelessly buggy code, Objective-C instance variable
2187  // lookup fails and no expression will be built to reference it.
2188  if (!E.isInvalid() && !E.get())
2189  return ExprError();
2190  return E;
2191  }
2192  }
2193 
2194  // This is guaranteed from this point on.
2195  assert(!R.empty() || ADL);
2196 
2197  // Check whether this might be a C++ implicit instance member access.
2198  // C++ [class.mfct.non-static]p3:
2199  // When an id-expression that is not part of a class member access
2200  // syntax and not used to form a pointer to member is used in the
2201  // body of a non-static member function of class X, if name lookup
2202  // resolves the name in the id-expression to a non-static non-type
2203  // member of some class C, the id-expression is transformed into a
2204  // class member access expression using (*this) as the
2205  // postfix-expression to the left of the . operator.
2206  //
2207  // But we don't actually need to do this for '&' operands if R
2208  // resolved to a function or overloaded function set, because the
2209  // expression is ill-formed if it actually works out to be a
2210  // non-static member function:
2211  //
2212  // C++ [expr.ref]p4:
2213  // Otherwise, if E1.E2 refers to a non-static member function. . .
2214  // [t]he expression can be used only as the left-hand operand of a
2215  // member function call.
2216  //
2217  // There are other safeguards against such uses, but it's important
2218  // to get this right here so that we don't end up making a
2219  // spuriously dependent expression if we're inside a dependent
2220  // instance method.
2221  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2222  bool MightBeImplicitMember;
2223  if (!IsAddressOfOperand)
2224  MightBeImplicitMember = true;
2225  else if (!SS.isEmpty())
2226  MightBeImplicitMember = false;
2227  else if (R.isOverloadedResult())
2228  MightBeImplicitMember = false;
2229  else if (R.isUnresolvableResult())
2230  MightBeImplicitMember = true;
2231  else
2232  MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2233  isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2234  isa<MSPropertyDecl>(R.getFoundDecl());
2235 
2236  if (MightBeImplicitMember)
2237  return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2238  R, TemplateArgs, S);
2239  }
2240 
2241  if (TemplateArgs || TemplateKWLoc.isValid()) {
2242 
2243  // In C++1y, if this is a variable template id, then check it
2244  // in BuildTemplateIdExpr().
2245  // The single lookup result must be a variable template declaration.
2246  if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2247  Id.TemplateId->Kind == TNK_Var_template) {
2248  assert(R.getAsSingle<VarTemplateDecl>() &&
2249  "There should only be one declaration found.");
2250  }
2251 
2252  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2253  }
2254 
2255  return BuildDeclarationNameExpr(SS, R, ADL);
2256 }
2257 
2258 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2259 /// declaration name, generally during template instantiation.
2260 /// There's a large number of things which don't need to be done along
2261 /// this path.
2263  CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2264  bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2265  DeclContext *DC = computeDeclContext(SS, false);
2266  if (!DC)
2267  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2268  NameInfo, /*TemplateArgs=*/nullptr);
2269 
2270  if (RequireCompleteDeclContext(SS, DC))
2271  return ExprError();
2272 
2273  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2274  LookupQualifiedName(R, DC);
2275 
2276  if (R.isAmbiguous())
2277  return ExprError();
2278 
2280  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2281  NameInfo, /*TemplateArgs=*/nullptr);
2282 
2283  if (R.empty()) {
2284  Diag(NameInfo.getLoc(), diag::err_no_member)
2285  << NameInfo.getName() << DC << SS.getRange();
2286  return ExprError();
2287  }
2288 
2289  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2290  // Diagnose a missing typename if this resolved unambiguously to a type in
2291  // a dependent context. If we can recover with a type, downgrade this to
2292  // a warning in Microsoft compatibility mode.
2293  unsigned DiagID = diag::err_typename_missing;
2294  if (RecoveryTSI && getLangOpts().MSVCCompat)
2295  DiagID = diag::ext_typename_missing;
2296  SourceLocation Loc = SS.getBeginLoc();
2297  auto D = Diag(Loc, DiagID);
2298  D << SS.getScopeRep() << NameInfo.getName().getAsString()
2299  << SourceRange(Loc, NameInfo.getEndLoc());
2300 
2301  // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2302  // context.
2303  if (!RecoveryTSI)
2304  return ExprError();
2305 
2306  // Only issue the fixit if we're prepared to recover.
2307  D << FixItHint::CreateInsertion(Loc, "typename ");
2308 
2309  // Recover by pretending this was an elaborated type.
2310  QualType Ty = Context.getTypeDeclType(TD);
2311  TypeLocBuilder TLB;
2312  TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2313 
2314  QualType ET = getElaboratedType(ETK_None, SS, Ty);
2315  ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2317  QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2318 
2319  *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2320 
2321  return ExprEmpty();
2322  }
2323 
2324  // Defend against this resolving to an implicit member access. We usually
2325  // won't get here if this might be a legitimate a class member (we end up in
2326  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2327  // a pointer-to-member or in an unevaluated context in C++11.
2328  if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2329  return BuildPossibleImplicitMemberExpr(SS,
2330  /*TemplateKWLoc=*/SourceLocation(),
2331  R, /*TemplateArgs=*/nullptr, S);
2332 
2333  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2334 }
2335 
2336 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2337 /// detected that we're currently inside an ObjC method. Perform some
2338 /// additional lookup.
2339 ///
2340 /// Ideally, most of this would be done by lookup, but there's
2341 /// actually quite a lot of extra work involved.
2342 ///
2343 /// Returns a null sentinel to indicate trivial success.
2344 ExprResult
2346  IdentifierInfo *II, bool AllowBuiltinCreation) {
2347  SourceLocation Loc = Lookup.getNameLoc();
2348  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2349 
2350  // Check for error condition which is already reported.
2351  if (!CurMethod)
2352  return ExprError();
2353 
2354  // There are two cases to handle here. 1) scoped lookup could have failed,
2355  // in which case we should look for an ivar. 2) scoped lookup could have
2356  // found a decl, but that decl is outside the current instance method (i.e.
2357  // a global variable). In these two cases, we do a lookup for an ivar with
2358  // this name, if the lookup sucedes, we replace it our current decl.
2359 
2360  // If we're in a class method, we don't normally want to look for
2361  // ivars. But if we don't find anything else, and there's an
2362  // ivar, that's an error.
2363  bool IsClassMethod = CurMethod->isClassMethod();
2364 
2365  bool LookForIvars;
2366  if (Lookup.empty())
2367  LookForIvars = true;
2368  else if (IsClassMethod)
2369  LookForIvars = false;
2370  else
2371  LookForIvars = (Lookup.isSingleResult() &&
2373  ObjCInterfaceDecl *IFace = nullptr;
2374  if (LookForIvars) {
2375  IFace = CurMethod->getClassInterface();
2376  ObjCInterfaceDecl *ClassDeclared;
2377  ObjCIvarDecl *IV = nullptr;
2378  if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2379  // Diagnose using an ivar in a class method.
2380  if (IsClassMethod)
2381  return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2382  << IV->getDeclName());
2383 
2384  // If we're referencing an invalid decl, just return this as a silent
2385  // error node. The error diagnostic was already emitted on the decl.
2386  if (IV->isInvalidDecl())
2387  return ExprError();
2388 
2389  // Check if referencing a field with __attribute__((deprecated)).
2390  if (DiagnoseUseOfDecl(IV, Loc))
2391  return ExprError();
2392 
2393  // Diagnose the use of an ivar outside of the declaring class.
2394  if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2395  !declaresSameEntity(ClassDeclared, IFace) &&
2396  !getLangOpts().DebuggerSupport)
2397  Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2398 
2399  // FIXME: This should use a new expr for a direct reference, don't
2400  // turn this into Self->ivar, just return a BareIVarExpr or something.
2401  IdentifierInfo &II = Context.Idents.get("self");
2402  UnqualifiedId SelfName;
2403  SelfName.setIdentifier(&II, SourceLocation());
2405  CXXScopeSpec SelfScopeSpec;
2406  SourceLocation TemplateKWLoc;
2407  ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2408  SelfName, false, false);
2409  if (SelfExpr.isInvalid())
2410  return ExprError();
2411 
2412  SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2413  if (SelfExpr.isInvalid())
2414  return ExprError();
2415 
2416  MarkAnyDeclReferenced(Loc, IV, true);
2417 
2418  ObjCMethodFamily MF = CurMethod->getMethodFamily();
2419  if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2420  !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2421  Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2422 
2423  ObjCIvarRefExpr *Result = new (Context)
2424  ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2425  IV->getLocation(), SelfExpr.get(), true, true);
2426 
2427  if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2428  if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2429  recordUseOfEvaluatedWeak(Result);
2430  }
2431  if (getLangOpts().ObjCAutoRefCount) {
2432  if (CurContext->isClosure())
2433  Diag(Loc, diag::warn_implicitly_retains_self)
2434  << FixItHint::CreateInsertion(Loc, "self->");
2435  }
2436 
2437  return Result;
2438  }
2439  } else if (CurMethod->isInstanceMethod()) {
2440  // We should warn if a local variable hides an ivar.
2441  if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2442  ObjCInterfaceDecl *ClassDeclared;
2443  if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2444  if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2445  declaresSameEntity(IFace, ClassDeclared))
2446  Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2447  }
2448  }
2449  } else if (Lookup.isSingleResult() &&
2451  // If accessing a stand-alone ivar in a class method, this is an error.
2452  if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2453  return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2454  << IV->getDeclName());
2455  }
2456 
2457  if (Lookup.empty() && II && AllowBuiltinCreation) {
2458  // FIXME. Consolidate this with similar code in LookupName.
2459  if (unsigned BuiltinID = II->getBuiltinID()) {
2460  if (!(getLangOpts().CPlusPlus &&
2461  Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2462  NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2463  S, Lookup.isForRedeclaration(),
2464  Lookup.getNameLoc());
2465  if (D) Lookup.addDecl(D);
2466  }
2467  }
2468  }
2469  // Sentinel value saying that we didn't do anything special.
2470  return ExprResult((Expr *)nullptr);
2471 }
2472 
2473 /// \brief Cast a base object to a member's actual type.
2474 ///
2475 /// Logically this happens in three phases:
2476 ///
2477 /// * First we cast from the base type to the naming class.
2478 /// The naming class is the class into which we were looking
2479 /// when we found the member; it's the qualifier type if a
2480 /// qualifier was provided, and otherwise it's the base type.
2481 ///
2482 /// * Next we cast from the naming class to the declaring class.
2483 /// If the member we found was brought into a class's scope by
2484 /// a using declaration, this is that class; otherwise it's
2485 /// the class declaring the member.
2486 ///
2487 /// * Finally we cast from the declaring class to the "true"
2488 /// declaring class of the member. This conversion does not
2489 /// obey access control.
2490 ExprResult
2492  NestedNameSpecifier *Qualifier,
2493  NamedDecl *FoundDecl,
2494  NamedDecl *Member) {
2495  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2496  if (!RD)
2497  return From;
2498 
2499  QualType DestRecordType;
2500  QualType DestType;
2501  QualType FromRecordType;
2502  QualType FromType = From->getType();
2503  bool PointerConversions = false;
2504  if (isa<FieldDecl>(Member)) {
2505  DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2506 
2507  if (FromType->getAs<PointerType>()) {
2508  DestType = Context.getPointerType(DestRecordType);
2509  FromRecordType = FromType->getPointeeType();
2510  PointerConversions = true;
2511  } else {
2512  DestType = DestRecordType;
2513  FromRecordType = FromType;
2514  }
2515  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2516  if (Method->isStatic())
2517  return From;
2518 
2519  DestType = Method->getThisType(Context);
2520  DestRecordType = DestType->getPointeeType();
2521 
2522  if (FromType->getAs<PointerType>()) {
2523  FromRecordType = FromType->getPointeeType();
2524  PointerConversions = true;
2525  } else {
2526  FromRecordType = FromType;
2527  DestType = DestRecordType;
2528  }
2529  } else {
2530  // No conversion necessary.
2531  return From;
2532  }
2533 
2534  if (DestType->isDependentType() || FromType->isDependentType())
2535  return From;
2536 
2537  // If the unqualified types are the same, no conversion is necessary.
2538  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2539  return From;
2540 
2541  SourceRange FromRange = From->getSourceRange();
2542  SourceLocation FromLoc = FromRange.getBegin();
2543 
2544  ExprValueKind VK = From->getValueKind();
2545 
2546  // C++ [class.member.lookup]p8:
2547  // [...] Ambiguities can often be resolved by qualifying a name with its
2548  // class name.
2549  //
2550  // If the member was a qualified name and the qualified referred to a
2551  // specific base subobject type, we'll cast to that intermediate type
2552  // first and then to the object in which the member is declared. That allows
2553  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2554  //
2555  // class Base { public: int x; };
2556  // class Derived1 : public Base { };
2557  // class Derived2 : public Base { };
2558  // class VeryDerived : public Derived1, public Derived2 { void f(); };
2559  //
2560  // void VeryDerived::f() {
2561  // x = 17; // error: ambiguous base subobjects
2562  // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2563  // }
2564  if (Qualifier && Qualifier->getAsType()) {
2565  QualType QType = QualType(Qualifier->getAsType(), 0);
2566  assert(QType->isRecordType() && "lookup done with non-record type");
2567 
2568  QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2569 
2570  // In C++98, the qualifier type doesn't actually have to be a base
2571  // type of the object type, in which case we just ignore it.
2572  // Otherwise build the appropriate casts.
2573  if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2574  CXXCastPath BasePath;
2575  if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2576  FromLoc, FromRange, &BasePath))
2577  return ExprError();
2578 
2579  if (PointerConversions)
2580  QType = Context.getPointerType(QType);
2581  From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2582  VK, &BasePath).get();
2583 
2584  FromType = QType;
2585  FromRecordType = QRecordType;
2586 
2587  // If the qualifier type was the same as the destination type,
2588  // we're done.
2589  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2590  return From;
2591  }
2592  }
2593 
2594  bool IgnoreAccess = false;
2595 
2596  // If we actually found the member through a using declaration, cast
2597  // down to the using declaration's type.
2598  //
2599  // Pointer equality is fine here because only one declaration of a
2600  // class ever has member declarations.
2601  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2602  assert(isa<UsingShadowDecl>(FoundDecl));
2603  QualType URecordType = Context.getTypeDeclType(
2604  cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2605 
2606  // We only need to do this if the naming-class to declaring-class
2607  // conversion is non-trivial.
2608  if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2609  assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2610  CXXCastPath BasePath;
2611  if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2612  FromLoc, FromRange, &BasePath))
2613  return ExprError();
2614 
2615  QualType UType = URecordType;
2616  if (PointerConversions)
2617  UType = Context.getPointerType(UType);
2618  From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2619  VK, &BasePath).get();
2620  FromType = UType;
2621  FromRecordType = URecordType;
2622  }
2623 
2624  // We don't do access control for the conversion from the
2625  // declaring class to the true declaring class.
2626  IgnoreAccess = true;
2627  }
2628 
2629  CXXCastPath BasePath;
2630  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2631  FromLoc, FromRange, &BasePath,
2632  IgnoreAccess))
2633  return ExprError();
2634 
2635  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2636  VK, &BasePath);
2637 }
2638 
2640  const LookupResult &R,
2641  bool HasTrailingLParen) {
2642  // Only when used directly as the postfix-expression of a call.
2643  if (!HasTrailingLParen)
2644  return false;
2645 
2646  // Never if a scope specifier was provided.
2647  if (SS.isSet())
2648  return false;
2649 
2650  // Only in C++ or ObjC++.
2651  if (!getLangOpts().CPlusPlus)
2652  return false;
2653 
2654  // Turn off ADL when we find certain kinds of declarations during
2655  // normal lookup:
2656  for (NamedDecl *D : R) {
2657  // C++0x [basic.lookup.argdep]p3:
2658  // -- a declaration of a class member
2659  // Since using decls preserve this property, we check this on the
2660  // original decl.
2661  if (D->isCXXClassMember())
2662  return false;
2663 
2664  // C++0x [basic.lookup.argdep]p3:
2665  // -- a block-scope function declaration that is not a
2666  // using-declaration
2667  // NOTE: we also trigger this for function templates (in fact, we
2668  // don't check the decl type at all, since all other decl types
2669  // turn off ADL anyway).
2670  if (isa<UsingShadowDecl>(D))
2671  D = cast<UsingShadowDecl>(D)->getTargetDecl();
2672  else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2673  return false;
2674 
2675  // C++0x [basic.lookup.argdep]p3:
2676  // -- a declaration that is neither a function or a function
2677  // template
2678  // And also for builtin functions.
2679  if (isa<FunctionDecl>(D)) {
2680  FunctionDecl *FDecl = cast<FunctionDecl>(D);
2681 
2682  // But also builtin functions.
2683  if (FDecl->getBuiltinID() && FDecl->isImplicit())
2684  return false;
2685  } else if (!isa<FunctionTemplateDecl>(D))
2686  return false;
2687  }
2688 
2689  return true;
2690 }
2691 
2692 
2693 /// Diagnoses obvious problems with the use of the given declaration
2694 /// as an expression. This is only actually called for lookups that
2695 /// were not overloaded, and it doesn't promise that the declaration
2696 /// will in fact be used.
2697 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2698  if (D->isInvalidDecl())
2699  return true;
2700 
2701  if (isa<TypedefNameDecl>(D)) {
2702  S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2703  return true;
2704  }
2705 
2706  if (isa<ObjCInterfaceDecl>(D)) {
2707  S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2708  return true;
2709  }
2710 
2711  if (isa<NamespaceDecl>(D)) {
2712  S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2713  return true;
2714  }
2715 
2716  return false;
2717 }
2718 
2720  LookupResult &R, bool NeedsADL,
2721  bool AcceptInvalidDecl) {
2722  // If this is a single, fully-resolved result and we don't need ADL,
2723  // just build an ordinary singleton decl ref.
2724  if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2725  return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2726  R.getRepresentativeDecl(), nullptr,
2727  AcceptInvalidDecl);
2728 
2729  // We only need to check the declaration if there's exactly one
2730  // result, because in the overloaded case the results can only be
2731  // functions and function templates.
2732  if (R.isSingleResult() &&
2733  CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2734  return ExprError();
2735 
2736  // Otherwise, just build an unresolved lookup expression. Suppress
2737  // any lookup-related diagnostics; we'll hash these out later, when
2738  // we've picked a target.
2739  R.suppressDiagnostics();
2740 
2743  SS.getWithLocInContext(Context),
2744  R.getLookupNameInfo(),
2745  NeedsADL, R.isOverloadedResult(),
2746  R.begin(), R.end());
2747 
2748  return ULE;
2749 }
2750 
2751 static void
2753  ValueDecl *var, DeclContext *DC);
2754 
2755 /// \brief Complete semantic analysis for a reference to the given declaration.
2757  const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2758  NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2759  bool AcceptInvalidDecl) {
2760  assert(D && "Cannot refer to a NULL declaration");
2761  assert(!isa<FunctionTemplateDecl>(D) &&
2762  "Cannot refer unambiguously to a function template");
2763 
2764  SourceLocation Loc = NameInfo.getLoc();
2765  if (CheckDeclInExpr(*this, Loc, D))
2766  return ExprError();
2767 
2768  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2769  // Specifically diagnose references to class templates that are missing
2770  // a template argument list.
2771  Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2772  << Template << SS.getRange();
2773  Diag(Template->getLocation(), diag::note_template_decl_here);
2774  return ExprError();
2775  }
2776 
2777  // Make sure that we're referring to a value.
2778  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2779  if (!VD) {
2780  Diag(Loc, diag::err_ref_non_value)
2781  << D << SS.getRange();
2782  Diag(D->getLocation(), diag::note_declared_at);
2783  return ExprError();
2784  }
2785 
2786  // Check whether this declaration can be used. Note that we suppress
2787  // this check when we're going to perform argument-dependent lookup
2788  // on this function name, because this might not be the function
2789  // that overload resolution actually selects.
2790  if (DiagnoseUseOfDecl(VD, Loc))
2791  return ExprError();
2792 
2793  // Only create DeclRefExpr's for valid Decl's.
2794  if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2795  return ExprError();
2796 
2797  // Handle members of anonymous structs and unions. If we got here,
2798  // and the reference is to a class member indirect field, then this
2799  // must be the subject of a pointer-to-member expression.
2800  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2801  if (!indirectField->isCXXClassMember())
2802  return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2803  indirectField);
2804 
2805  {
2806  QualType type = VD->getType();
2807  if (type.isNull())
2808  return ExprError();
2809  if (auto *FPT = type->getAs<FunctionProtoType>()) {
2810  // C++ [except.spec]p17:
2811  // An exception-specification is considered to be needed when:
2812  // - in an expression, the function is the unique lookup result or
2813  // the selected member of a set of overloaded functions.
2814  ResolveExceptionSpec(Loc, FPT);
2815  type = VD->getType();
2816  }
2817  ExprValueKind valueKind = VK_RValue;
2818 
2819  switch (D->getKind()) {
2820  // Ignore all the non-ValueDecl kinds.
2821 #define ABSTRACT_DECL(kind)
2822 #define VALUE(type, base)
2823 #define DECL(type, base) \
2824  case Decl::type:
2825 #include "clang/AST/DeclNodes.inc"
2826  llvm_unreachable("invalid value decl kind");
2827 
2828  // These shouldn't make it here.
2829  case Decl::ObjCAtDefsField:
2830  case Decl::ObjCIvar:
2831  llvm_unreachable("forming non-member reference to ivar?");
2832 
2833  // Enum constants are always r-values and never references.
2834  // Unresolved using declarations are dependent.
2835  case Decl::EnumConstant:
2836  case Decl::UnresolvedUsingValue:
2837  case Decl::OMPDeclareReduction:
2838  valueKind = VK_RValue;
2839  break;
2840 
2841  // Fields and indirect fields that got here must be for
2842  // pointer-to-member expressions; we just call them l-values for
2843  // internal consistency, because this subexpression doesn't really
2844  // exist in the high-level semantics.
2845  case Decl::Field:
2846  case Decl::IndirectField:
2847  assert(getLangOpts().CPlusPlus &&
2848  "building reference to field in C?");
2849 
2850  // These can't have reference type in well-formed programs, but
2851  // for internal consistency we do this anyway.
2852  type = type.getNonReferenceType();
2853  valueKind = VK_LValue;
2854  break;
2855 
2856  // Non-type template parameters are either l-values or r-values
2857  // depending on the type.
2858  case Decl::NonTypeTemplateParm: {
2859  if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2860  type = reftype->getPointeeType();
2861  valueKind = VK_LValue; // even if the parameter is an r-value reference
2862  break;
2863  }
2864 
2865  // For non-references, we need to strip qualifiers just in case
2866  // the template parameter was declared as 'const int' or whatever.
2867  valueKind = VK_RValue;
2868  type = type.getUnqualifiedType();
2869  break;
2870  }
2871 
2872  case Decl::Var:
2873  case Decl::VarTemplateSpecialization:
2874  case Decl::VarTemplatePartialSpecialization:
2875  case Decl::Decomposition:
2876  case Decl::OMPCapturedExpr:
2877  // In C, "extern void blah;" is valid and is an r-value.
2878  if (!getLangOpts().CPlusPlus &&
2879  !type.hasQualifiers() &&
2880  type->isVoidType()) {
2881  valueKind = VK_RValue;
2882  break;
2883  }
2884  // fallthrough
2885 
2886  case Decl::ImplicitParam:
2887  case Decl::ParmVar: {
2888  // These are always l-values.
2889  valueKind = VK_LValue;
2890  type = type.getNonReferenceType();
2891 
2892  // FIXME: Does the addition of const really only apply in
2893  // potentially-evaluated contexts? Since the variable isn't actually
2894  // captured in an unevaluated context, it seems that the answer is no.
2895  if (!isUnevaluatedContext()) {
2896  QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2897  if (!CapturedType.isNull())
2898  type = CapturedType;
2899  }
2900 
2901  break;
2902  }
2903 
2904  case Decl::Binding: {
2905  // These are always lvalues.
2906  valueKind = VK_LValue;
2907  type = type.getNonReferenceType();
2908  // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2909  // decides how that's supposed to work.
2910  auto *BD = cast<BindingDecl>(VD);
2911  if (BD->getDeclContext()->isFunctionOrMethod() &&
2912  BD->getDeclContext() != CurContext)
2913  diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2914  break;
2915  }
2916 
2917  case Decl::Function: {
2918  if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2919  if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2920  type = Context.BuiltinFnTy;
2921  valueKind = VK_RValue;
2922  break;
2923  }
2924  }
2925 
2926  const FunctionType *fty = type->castAs<FunctionType>();
2927 
2928  // If we're referring to a function with an __unknown_anytype
2929  // result type, make the entire expression __unknown_anytype.
2930  if (fty->getReturnType() == Context.UnknownAnyTy) {
2931  type = Context.UnknownAnyTy;
2932  valueKind = VK_RValue;
2933  break;
2934  }
2935 
2936  // Functions are l-values in C++.
2937  if (getLangOpts().CPlusPlus) {
2938  valueKind = VK_LValue;
2939  break;
2940  }
2941 
2942  // C99 DR 316 says that, if a function type comes from a
2943  // function definition (without a prototype), that type is only
2944  // used for checking compatibility. Therefore, when referencing
2945  // the function, we pretend that we don't have the full function
2946  // type.
2947  if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2948  isa<FunctionProtoType>(fty))
2949  type = Context.getFunctionNoProtoType(fty->getReturnType(),
2950  fty->getExtInfo());
2951 
2952  // Functions are r-values in C.
2953  valueKind = VK_RValue;
2954  break;
2955  }
2956 
2957  case Decl::CXXDeductionGuide:
2958  llvm_unreachable("building reference to deduction guide");
2959 
2960  case Decl::MSProperty:
2961  valueKind = VK_LValue;
2962  break;
2963 
2964  case Decl::CXXMethod:
2965  // If we're referring to a method with an __unknown_anytype
2966  // result type, make the entire expression __unknown_anytype.
2967  // This should only be possible with a type written directly.
2968  if (const FunctionProtoType *proto
2969  = dyn_cast<FunctionProtoType>(VD->getType()))
2970  if (proto->getReturnType() == Context.UnknownAnyTy) {
2971  type = Context.UnknownAnyTy;
2972  valueKind = VK_RValue;
2973  break;
2974  }
2975 
2976  // C++ methods are l-values if static, r-values if non-static.
2977  if (cast<CXXMethodDecl>(VD)->isStatic()) {
2978  valueKind = VK_LValue;
2979  break;
2980  }
2981  // fallthrough
2982 
2983  case Decl::CXXConversion:
2984  case Decl::CXXDestructor:
2985  case Decl::CXXConstructor:
2986  valueKind = VK_RValue;
2987  break;
2988  }
2989 
2990  return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2991  TemplateArgs);
2992  }
2993 }
2994 
2995 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2996  SmallString<32> &Target) {
2997  Target.resize(CharByteWidth * (Source.size() + 1));
2998  char *ResultPtr = &Target[0];
2999  const llvm::UTF8 *ErrorPtr;
3000  bool success =
3001  llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3002  (void)success;
3003  assert(success);
3004  Target.resize(ResultPtr - &Target[0]);
3005 }
3006 
3009  // Pick the current block, lambda, captured statement or function.
3010  Decl *currentDecl = nullptr;
3011  if (const BlockScopeInfo *BSI = getCurBlock())
3012  currentDecl = BSI->TheDecl;
3013  else if (const LambdaScopeInfo *LSI = getCurLambda())
3014  currentDecl = LSI->CallOperator;
3015  else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3016  currentDecl = CSI->TheCapturedDecl;
3017  else
3018  currentDecl = getCurFunctionOrMethodDecl();
3019 
3020  if (!currentDecl) {
3021  Diag(Loc, diag::ext_predef_outside_function);
3022  currentDecl = Context.getTranslationUnitDecl();
3023  }
3024 
3025  QualType ResTy;
3026  StringLiteral *SL = nullptr;
3027  if (cast<DeclContext>(currentDecl)->isDependentContext())
3028  ResTy = Context.DependentTy;
3029  else {
3030  // Pre-defined identifiers are of type char[x], where x is the length of
3031  // the string.
3032  auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3033  unsigned Length = Str.length();
3034 
3035  llvm::APInt LengthI(32, Length + 1);
3036  if (IT == PredefinedExpr::LFunction) {
3037  ResTy = Context.WideCharTy.withConst();
3038  SmallString<32> RawChars;
3040  Str, RawChars);
3041  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3042  /*IndexTypeQuals*/ 0);
3043  SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3044  /*Pascal*/ false, ResTy, Loc);
3045  } else {
3046  ResTy = Context.CharTy.withConst();
3047  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3048  /*IndexTypeQuals*/ 0);
3049  SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3050  /*Pascal*/ false, ResTy, Loc);
3051  }
3052  }
3053 
3054  return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3055 }
3056 
3059 
3060  switch (Kind) {
3061  default: llvm_unreachable("Unknown simple primary expr!");
3062  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3063  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3064  case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3065  case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3066  case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3067  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3068  }
3069 
3070  return BuildPredefinedExpr(Loc, IT);
3071 }
3072 
3074  SmallString<16> CharBuffer;
3075  bool Invalid = false;
3076  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3077  if (Invalid)
3078  return ExprError();
3079 
3080  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3081  PP, Tok.getKind());
3082  if (Literal.hadError())
3083  return ExprError();
3084 
3085  QualType Ty;
3086  if (Literal.isWide())
3087  Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3088  else if (Literal.isUTF16())
3089  Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3090  else if (Literal.isUTF32())
3091  Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3092  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3093  Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3094  else
3095  Ty = Context.CharTy; // 'x' -> char in C++
3096 
3098  if (Literal.isWide())
3100  else if (Literal.isUTF16())
3102  else if (Literal.isUTF32())
3104  else if (Literal.isUTF8())
3106 
3107  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3108  Tok.getLocation());
3109 
3110  if (Literal.getUDSuffix().empty())
3111  return Lit;
3112 
3113  // We're building a user-defined literal.
3114  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3115  SourceLocation UDSuffixLoc =
3116  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3117 
3118  // Make sure we're allowed user-defined literals here.
3119  if (!UDLScope)
3120  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3121 
3122  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3123  // operator "" X (ch)
3124  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3125  Lit, Tok.getLocation());
3126 }
3127 
3129  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3130  return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3131  Context.IntTy, Loc);
3132 }
3133 
3135  QualType Ty, SourceLocation Loc) {
3136  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3137 
3138  using llvm::APFloat;
3139  APFloat Val(Format);
3140 
3141  APFloat::opStatus result = Literal.GetFloatValue(Val);
3142 
3143  // Overflow is always an error, but underflow is only an error if
3144  // we underflowed to zero (APFloat reports denormals as underflow).
3145  if ((result & APFloat::opOverflow) ||
3146  ((result & APFloat::opUnderflow) && Val.isZero())) {
3147  unsigned diagnostic;
3148  SmallString<20> buffer;
3149  if (result & APFloat::opOverflow) {
3150  diagnostic = diag::warn_float_overflow;
3151  APFloat::getLargest(Format).toString(buffer);
3152  } else {
3153  diagnostic = diag::warn_float_underflow;
3154  APFloat::getSmallest(Format).toString(buffer);
3155  }
3156 
3157  S.Diag(Loc, diagnostic)
3158  << Ty
3159  << StringRef(buffer.data(), buffer.size());
3160  }
3161 
3162  bool isExact = (result == APFloat::opOK);
3163  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3164 }
3165 
3167  assert(E && "Invalid expression");
3168 
3169  if (E->isValueDependent())
3170  return false;
3171 
3172  QualType QT = E->getType();
3173  if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3174  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3175  return true;
3176  }
3177 
3178  llvm::APSInt ValueAPS;
3179  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3180 
3181  if (R.isInvalid())
3182  return true;
3183 
3184  bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3185  if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3186  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3187  << ValueAPS.toString(10) << ValueIsPositive;
3188  return true;
3189  }
3190 
3191  return false;
3192 }
3193 
3195  // Fast path for a single digit (which is quite common). A single digit
3196  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3197  if (Tok.getLength() == 1) {
3198  const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3199  return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3200  }
3201 
3202  SmallString<128> SpellingBuffer;
3203  // NumericLiteralParser wants to overread by one character. Add padding to
3204  // the buffer in case the token is copied to the buffer. If getSpelling()
3205  // returns a StringRef to the memory buffer, it should have a null char at
3206  // the EOF, so it is also safe.
3207  SpellingBuffer.resize(Tok.getLength() + 1);
3208 
3209  // Get the spelling of the token, which eliminates trigraphs, etc.
3210  bool Invalid = false;
3211  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3212  if (Invalid)
3213  return ExprError();
3214 
3215  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3216  if (Literal.hadError)
3217  return ExprError();
3218 
3219  if (Literal.hasUDSuffix()) {
3220  // We're building a user-defined literal.
3221  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3222  SourceLocation UDSuffixLoc =
3223  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3224 
3225  // Make sure we're allowed user-defined literals here.
3226  if (!UDLScope)
3227  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3228 
3229  QualType CookedTy;
3230  if (Literal.isFloatingLiteral()) {
3231  // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3232  // long double, the literal is treated as a call of the form
3233  // operator "" X (f L)
3234  CookedTy = Context.LongDoubleTy;
3235  } else {
3236  // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3237  // unsigned long long, the literal is treated as a call of the form
3238  // operator "" X (n ULL)
3239  CookedTy = Context.UnsignedLongLongTy;
3240  }
3241 
3242  DeclarationName OpName =
3243  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3244  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3245  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3246 
3247  SourceLocation TokLoc = Tok.getLocation();
3248 
3249  // Perform literal operator lookup to determine if we're building a raw
3250  // literal or a cooked one.
3251  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3252  switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3253  /*AllowRaw*/ true, /*AllowTemplate*/ true,
3254  /*AllowStringTemplate*/ false,
3255  /*DiagnoseMissing*/ !Literal.isImaginary)) {
3256  case LOLR_ErrorNoDiagnostic:
3257  // Lookup failure for imaginary constants isn't fatal, there's still the
3258  // GNU extension producing _Complex types.
3259  break;
3260  case LOLR_Error:
3261  return ExprError();
3262  case LOLR_Cooked: {
3263  Expr *Lit;
3264  if (Literal.isFloatingLiteral()) {
3265  Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3266  } else {
3267  llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3268  if (Literal.GetIntegerValue(ResultVal))
3269  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3270  << /* Unsigned */ 1;
3271  Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3272  Tok.getLocation());
3273  }
3274  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3275  }
3276 
3277  case LOLR_Raw: {
3278  // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3279  // literal is treated as a call of the form
3280  // operator "" X ("n")
3281  unsigned Length = Literal.getUDSuffixOffset();
3282  QualType StrTy = Context.getConstantArrayType(
3283  Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3284  ArrayType::Normal, 0);
3285  Expr *Lit = StringLiteral::Create(
3286  Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3287  /*Pascal*/false, StrTy, &TokLoc, 1);
3288  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3289  }
3290 
3291  case LOLR_Template: {
3292  // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3293  // template), L is treated as a call fo the form
3294  // operator "" X <'c1', 'c2', ... 'ck'>()
3295  // where n is the source character sequence c1 c2 ... ck.
3296  TemplateArgumentListInfo ExplicitArgs;
3297  unsigned CharBits = Context.getIntWidth(Context.CharTy);
3298  bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3299  llvm::APSInt Value(CharBits, CharIsUnsigned);
3300  for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3301  Value = TokSpelling[I];
3302  TemplateArgument Arg(Context, Value, Context.CharTy);
3303  TemplateArgumentLocInfo ArgInfo;
3304  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3305  }
3306  return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3307  &ExplicitArgs);
3308  }
3309  case LOLR_StringTemplate:
3310  llvm_unreachable("unexpected literal operator lookup result");
3311  }
3312  }
3313 
3314  Expr *Res;
3315 
3316  if (Literal.isFloatingLiteral()) {
3317  QualType Ty;
3318  if (Literal.isHalf){
3319  if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3320  Ty = Context.HalfTy;
3321  else {
3322  Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3323  return ExprError();
3324  }
3325  } else if (Literal.isFloat)
3326  Ty = Context.FloatTy;
3327  else if (Literal.isLong)
3328  Ty = Context.LongDoubleTy;
3329  else if (Literal.isFloat16)
3330  Ty = Context.Float16Ty;
3331  else if (Literal.isFloat128)
3332  Ty = Context.Float128Ty;
3333  else
3334  Ty = Context.DoubleTy;
3335 
3336  Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3337 
3338  if (Ty == Context.DoubleTy) {
3339  if (getLangOpts().SinglePrecisionConstants) {
3340  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3341  if (BTy->getKind() != BuiltinType::Float) {
3342  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3343  }
3344  } else if (getLangOpts().OpenCL &&
3345  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3346  // Impose single-precision float type when cl_khr_fp64 is not enabled.
3347  Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3348  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3349  }
3350  }
3351  } else if (!Literal.isIntegerLiteral()) {
3352  return ExprError();
3353  } else {
3354  QualType Ty;
3355 
3356  // 'long long' is a C99 or C++11 feature.
3357  if (!getLangOpts().C99 && Literal.isLongLong) {
3358  if (getLangOpts().CPlusPlus)
3359  Diag(Tok.getLocation(),
3360  getLangOpts().CPlusPlus11 ?
3361  diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3362  else
3363  Diag(Tok.getLocation(), diag::ext_c99_longlong);
3364  }
3365 
3366  // Get the value in the widest-possible width.
3367  unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3368  llvm::APInt ResultVal(MaxWidth, 0);
3369 
3370  if (Literal.GetIntegerValue(ResultVal)) {
3371  // If this value didn't fit into uintmax_t, error and force to ull.
3372  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3373  << /* Unsigned */ 1;
3374  Ty = Context.UnsignedLongLongTy;
3375  assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3376  "long long is not intmax_t?");
3377  } else {
3378  // If this value fits into a ULL, try to figure out what else it fits into
3379  // according to the rules of C99 6.4.4.1p5.
3380 
3381  // Octal, Hexadecimal, and integers with a U suffix are allowed to
3382  // be an unsigned int.
3383  bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3384 
3385  // Check from smallest to largest, picking the smallest type we can.
3386  unsigned Width = 0;
3387 
3388  // Microsoft specific integer suffixes are explicitly sized.
3389  if (Literal.MicrosoftInteger) {
3390  if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3391  Width = 8;
3392  Ty = Context.CharTy;
3393  } else {
3394  Width = Literal.MicrosoftInteger;
3395  Ty = Context.getIntTypeForBitwidth(Width,
3396  /*Signed=*/!Literal.isUnsigned);
3397  }
3398  }
3399 
3400  if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3401  // Are int/unsigned possibilities?
3402  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3403 
3404  // Does it fit in a unsigned int?
3405  if (ResultVal.isIntN(IntSize)) {
3406  // Does it fit in a signed int?
3407  if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3408  Ty = Context.IntTy;
3409  else if (AllowUnsigned)
3410  Ty = Context.UnsignedIntTy;
3411  Width = IntSize;
3412  }
3413  }
3414 
3415  // Are long/unsigned long possibilities?
3416  if (Ty.isNull() && !Literal.isLongLong) {
3417  unsigned LongSize = Context.getTargetInfo().getLongWidth();
3418 
3419  // Does it fit in a unsigned long?
3420  if (ResultVal.isIntN(LongSize)) {
3421  // Does it fit in a signed long?
3422  if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3423  Ty = Context.LongTy;
3424  else if (AllowUnsigned)
3425  Ty = Context.UnsignedLongTy;
3426  // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3427  // is compatible.
3428  else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3429  const unsigned LongLongSize =
3430  Context.getTargetInfo().getLongLongWidth();
3431  Diag(Tok.getLocation(),
3432  getLangOpts().CPlusPlus
3433  ? Literal.isLong
3434  ? diag::warn_old_implicitly_unsigned_long_cxx
3435  : /*C++98 UB*/ diag::
3436  ext_old_implicitly_unsigned_long_cxx
3437  : diag::warn_old_implicitly_unsigned_long)
3438  << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3439  : /*will be ill-formed*/ 1);
3440  Ty = Context.UnsignedLongTy;
3441  }
3442  Width = LongSize;
3443  }
3444  }
3445 
3446  // Check long long if needed.
3447  if (Ty.isNull()) {
3448  unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3449 
3450  // Does it fit in a unsigned long long?
3451  if (ResultVal.isIntN(LongLongSize)) {
3452  // Does it fit in a signed long long?
3453  // To be compatible with MSVC, hex integer literals ending with the
3454  // LL or i64 suffix are always signed in Microsoft mode.
3455  if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3456  (getLangOpts().MSVCCompat && Literal.isLongLong)))
3457  Ty = Context.LongLongTy;
3458  else if (AllowUnsigned)
3459  Ty = Context.UnsignedLongLongTy;
3460  Width = LongLongSize;
3461  }
3462  }
3463 
3464  // If we still couldn't decide a type, we probably have something that
3465  // does not fit in a signed long long, but has no U suffix.
3466  if (Ty.isNull()) {
3467  Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3468  Ty = Context.UnsignedLongLongTy;
3469  Width = Context.getTargetInfo().getLongLongWidth();
3470  }
3471 
3472  if (ResultVal.getBitWidth() != Width)
3473  ResultVal = ResultVal.trunc(Width);
3474  }
3475  Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3476  }
3477 
3478  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3479  if (Literal.isImaginary) {
3480  Res = new (Context) ImaginaryLiteral(Res,
3481  Context.getComplexType(Res->getType()));
3482 
3483  Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3484  }
3485  return Res;
3486 }
3487 
3489  assert(E && "ActOnParenExpr() missing expr");
3490  return new (Context) ParenExpr(L, R, E);
3491 }
3492 
3494  SourceLocation Loc,
3495  SourceRange ArgRange) {
3496  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3497  // scalar or vector data type argument..."
3498  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3499  // type (C99 6.2.5p18) or void.
3500  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3501  S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3502  << T << ArgRange;
3503  return true;
3504  }
3505 
3506  assert((T->isVoidType() || !T->isIncompleteType()) &&
3507  "Scalar types should always be complete");
3508  return false;
3509 }
3510 
3512  SourceLocation Loc,
3513  SourceRange ArgRange,
3514  UnaryExprOrTypeTrait TraitKind) {
3515  // Invalid types must be hard errors for SFINAE in C++.
3516  if (S.LangOpts.CPlusPlus)
3517  return true;
3518 
3519  // C99 6.5.3.4p1:
3520  if (T->isFunctionType() &&
3521  (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3522  // sizeof(function)/alignof(function) is allowed as an extension.
3523  S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3524  << TraitKind << ArgRange;
3525  return false;
3526  }
3527 
3528  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3529  // this is an error (OpenCL v1.1 s6.3.k)
3530  if (T->isVoidType()) {
3531  unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3532  : diag::ext_sizeof_alignof_void_type;
3533  S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3534  return false;
3535  }
3536 
3537  return true;
3538 }
3539 
3541  SourceLocation Loc,
3542  SourceRange ArgRange,
3543  UnaryExprOrTypeTrait TraitKind) {
3544  // Reject sizeof(interface) and sizeof(interface<proto>) if the
3545  // runtime doesn't allow it.
3547  S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3548  << T << (TraitKind == UETT_SizeOf)
3549  << ArgRange;
3550  return true;
3551  }
3552 
3553  return false;
3554 }
3555 
3556 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3557 /// pointer type is equal to T) and emit a warning if it is.
3559  Expr *E) {
3560  // Don't warn if the operation changed the type.
3561  if (T != E->getType())
3562  return;
3563 
3564  // Now look for array decays.
3565  ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3566  if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3567  return;
3568 
3569  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3570  << ICE->getType()
3571  << ICE->getSubExpr()->getType();
3572 }
3573 
3574 /// \brief Check the constraints on expression operands to unary type expression
3575 /// and type traits.
3576 ///
3577 /// Completes any types necessary and validates the constraints on the operand
3578 /// expression. The logic mostly mirrors the type-based overload, but may modify
3579 /// the expression as it completes the type for that expression through template
3580 /// instantiation, etc.
3582  UnaryExprOrTypeTrait ExprKind) {
3583  QualType ExprTy = E->getType();
3584  assert(!ExprTy->isReferenceType());
3585 
3586  if (ExprKind == UETT_VecStep)
3587  return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3588  E->getSourceRange());
3589 
3590  // Whitelist some types as extensions
3591  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3592  E->getSourceRange(), ExprKind))
3593  return false;
3594 
3595  // 'alignof' applied to an expression only requires the base element type of
3596  // the expression to be complete. 'sizeof' requires the expression's type to
3597  // be complete (and will attempt to complete it if it's an array of unknown
3598  // bound).
3599  if (ExprKind == UETT_AlignOf) {
3600  if (RequireCompleteType(E->getExprLoc(),
3601  Context.getBaseElementType(E->getType()),
3602  diag::err_sizeof_alignof_incomplete_type, ExprKind,
3603  E->getSourceRange()))
3604  return true;
3605  } else {
3606  if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3607  ExprKind, E->getSourceRange()))
3608  return true;
3609  }
3610 
3611  // Completing the expression's type may have changed it.
3612  ExprTy = E->getType();
3613  assert(!ExprTy->isReferenceType());
3614 
3615  if (ExprTy->isFunctionType()) {
3616  Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3617  << ExprKind << E->getSourceRange();
3618  return true;
3619  }
3620 
3621  // The operand for sizeof and alignof is in an unevaluated expression context,
3622  // so side effects could result in unintended consequences.
3623  if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3624  !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3625  Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3626 
3627  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3628  E->getSourceRange(), ExprKind))
3629  return true;
3630 
3631  if (ExprKind == UETT_SizeOf) {
3632  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3633  if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3634  QualType OType = PVD->getOriginalType();
3635  QualType Type = PVD->getType();
3636  if (Type->isPointerType() && OType->isArrayType()) {
3637  Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3638  << Type << OType;
3639  Diag(PVD->getLocation(), diag::note_declared_at);
3640  }
3641  }
3642  }
3643 
3644  // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3645  // decays into a pointer and returns an unintended result. This is most
3646  // likely a typo for "sizeof(array) op x".
3647  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3648  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3649  BO->getLHS());
3650  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3651  BO->getRHS());
3652  }
3653  }
3654 
3655  return false;
3656 }
3657 
3658 /// \brief Check the constraints on operands to unary expression and type
3659 /// traits.
3660 ///
3661 /// This will complete any types necessary, and validate the various constraints
3662 /// on those operands.
3663 ///
3664 /// The UsualUnaryConversions() function is *not* called by this routine.
3665 /// C99 6.3.2.1p[2-4] all state:
3666 /// Except when it is the operand of the sizeof operator ...
3667 ///
3668 /// C++ [expr.sizeof]p4
3669 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3670 /// standard conversions are not applied to the operand of sizeof.
3671 ///
3672 /// This policy is followed for all of the unary trait expressions.
3674  SourceLocation OpLoc,
3675  SourceRange ExprRange,
3676  UnaryExprOrTypeTrait ExprKind) {
3677  if (ExprType->isDependentType())
3678  return false;
3679 
3680  // C++ [expr.sizeof]p2:
3681  // When applied to a reference or a reference type, the result
3682  // is the size of the referenced type.
3683  // C++11 [expr.alignof]p3:
3684  // When alignof is applied to a reference type, the result
3685  // shall be the alignment of the referenced type.
3686  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3687  ExprType = Ref->getPointeeType();
3688 
3689  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3690  // When alignof or _Alignof is applied to an array type, the result
3691  // is the alignment of the element type.
3692  if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3693  ExprType = Context.getBaseElementType(ExprType);
3694 
3695  if (ExprKind == UETT_VecStep)
3696  return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3697 
3698  // Whitelist some types as extensions
3699  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3700  ExprKind))
3701  return false;
3702 
3703  if (RequireCompleteType(OpLoc, ExprType,
3704  diag::err_sizeof_alignof_incomplete_type,
3705  ExprKind, ExprRange))
3706  return true;
3707 
3708  if (ExprType->isFunctionType()) {
3709  Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3710  << ExprKind << ExprRange;
3711  return true;
3712  }
3713 
3714  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3715  ExprKind))
3716  return true;
3717 
3718  return false;
3719 }
3720 
3721 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3722  E = E->IgnoreParens();
3723 
3724  // Cannot know anything else if the expression is dependent.
3725  if (E->isTypeDependent())
3726  return false;
3727 
3728  if (E->getObjectKind() == OK_BitField) {
3729  S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3730  << 1 << E->getSourceRange();
3731  return true;
3732  }
3733 
3734  ValueDecl *D = nullptr;
3735  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3736  D = DRE->getDecl();
3737  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3738  D = ME->getMemberDecl();
3739  }
3740 
3741  // If it's a field, require the containing struct to have a
3742  // complete definition so that we can compute the layout.
3743  //
3744  // This can happen in C++11 onwards, either by naming the member
3745  // in a way that is not transformed into a member access expression
3746  // (in an unevaluated operand, for instance), or by naming the member
3747  // in a trailing-return-type.
3748  //
3749  // For the record, since __alignof__ on expressions is a GCC
3750  // extension, GCC seems to permit this but always gives the
3751  // nonsensical answer 0.
3752  //
3753  // We don't really need the layout here --- we could instead just
3754  // directly check for all the appropriate alignment-lowing
3755  // attributes --- but that would require duplicating a lot of
3756  // logic that just isn't worth duplicating for such a marginal
3757  // use-case.
3758  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3759  // Fast path this check, since we at least know the record has a
3760  // definition if we can find a member of it.
3761  if (!FD->getParent()->isCompleteDefinition()) {
3762  S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3763  << E->getSourceRange();
3764  return true;
3765  }
3766 
3767  // Otherwise, if it's a field, and the field doesn't have
3768  // reference type, then it must have a complete type (or be a
3769  // flexible array member, which we explicitly want to
3770  // white-list anyway), which makes the following checks trivial.
3771  if (!FD->getType()->isReferenceType())
3772  return false;
3773  }
3774 
3776 }
3777 
3779  E = E->IgnoreParens();
3780 
3781  // Cannot know anything else if the expression is dependent.
3782  if (E->isTypeDependent())
3783  return false;
3784 
3785  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3786 }
3787 
3789  CapturingScopeInfo *CSI) {
3790  assert(T->isVariablyModifiedType());
3791  assert(CSI != nullptr);
3792 
3793  // We're going to walk down into the type and look for VLA expressions.
3794  do {
3795  const Type *Ty = T.getTypePtr();
3796  switch (Ty->getTypeClass()) {
3797 #define TYPE(Class, Base)
3798 #define ABSTRACT_TYPE(Class, Base)
3799 #define NON_CANONICAL_TYPE(Class, Base)
3800 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3801 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3802 #include "clang/AST/TypeNodes.def"
3803  T = QualType();
3804  break;
3805  // These types are never variably-modified.
3806  case Type::Builtin:
3807  case Type::Complex:
3808  case Type::Vector:
3809  case Type::ExtVector:
3810  case Type::Record:
3811  case Type::Enum:
3812  case Type::Elaborated:
3813  case Type::TemplateSpecialization:
3814  case Type::ObjCObject:
3815  case Type::ObjCInterface:
3816  case Type::ObjCObjectPointer:
3817  case Type::ObjCTypeParam:
3818  case Type::Pipe:
3819  llvm_unreachable("type class is never variably-modified!");
3820  case Type::Adjusted:
3821  T = cast<AdjustedType>(Ty)->getOriginalType();
3822  break;
3823  case Type::Decayed:
3824  T = cast<DecayedType>(Ty)->getPointeeType();
3825  break;
3826  case Type::Pointer:
3827  T = cast<PointerType>(Ty)->getPointeeType();
3828  break;
3829  case Type::BlockPointer:
3830  T = cast<BlockPointerType>(Ty)->getPointeeType();
3831  break;
3832  case Type::LValueReference:
3833  case Type::RValueReference:
3834  T = cast<ReferenceType>(Ty)->getPointeeType();
3835  break;
3836  case Type::MemberPointer:
3837  T = cast<MemberPointerType>(Ty)->getPointeeType();
3838  break;
3839  case Type::ConstantArray:
3840  case Type::IncompleteArray:
3841  // Losing element qualification here is fine.
3842  T = cast<ArrayType>(Ty)->getElementType();
3843  break;
3844  case Type::VariableArray: {
3845  // Losing element qualification here is fine.
3846  const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3847 
3848  // Unknown size indication requires no size computation.
3849  // Otherwise, evaluate and record it.
3850  if (auto Size = VAT->getSizeExpr()) {
3851  if (!CSI->isVLATypeCaptured(VAT)) {
3852  RecordDecl *CapRecord = nullptr;
3853  if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3854  CapRecord = LSI->Lambda;
3855  } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3856  CapRecord = CRSI->TheRecordDecl;
3857  }
3858  if (CapRecord) {
3859  auto ExprLoc = Size->getExprLoc();
3860  auto SizeType = Context.getSizeType();
3861  // Build the non-static data member.
3862  auto Field =
3863  FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3864  /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3865  /*BW*/ nullptr, /*Mutable*/ false,
3866  /*InitStyle*/ ICIS_NoInit);
3867  Field->setImplicit(true);
3868  Field->setAccess(AS_private);
3869  Field->setCapturedVLAType(VAT);
3870  CapRecord->addDecl(Field);
3871 
3872  CSI->addVLATypeCapture(ExprLoc, SizeType);
3873  }
3874  }
3875  }
3876  T = VAT->getElementType();
3877  break;
3878  }
3879  case Type::FunctionProto:
3880  case Type::FunctionNoProto:
3881  T = cast<FunctionType>(Ty)->getReturnType();
3882  break;
3883  case Type::Paren:
3884  case Type::TypeOf:
3885  case Type::UnaryTransform:
3886  case Type::Attributed:
3887  case Type::SubstTemplateTypeParm:
3888  case Type::PackExpansion:
3889  // Keep walking after single level desugaring.
3890  T = T.getSingleStepDesugaredType(Context);
3891  break;
3892  case Type::Typedef:
3893  T = cast<TypedefType>(Ty)->desugar();
3894  break;
3895  case Type::Decltype:
3896  T = cast<DecltypeType>(Ty)->desugar();
3897  break;
3898  case Type::Auto:
3899  case Type::DeducedTemplateSpecialization:
3900  T = cast<DeducedType>(Ty)->getDeducedType();
3901  break;
3902  case Type::TypeOfExpr:
3903  T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3904  break;
3905  case Type::Atomic:
3906  T = cast<AtomicType>(Ty)->getValueType();
3907  break;
3908  }
3909  } while (!T.isNull() && T->isVariablyModifiedType());
3910 }
3911 
3912 /// \brief Build a sizeof or alignof expression given a type operand.
3913 ExprResult
3915  SourceLocation OpLoc,
3916  UnaryExprOrTypeTrait ExprKind,
3917  SourceRange R) {
3918  if (!TInfo)
3919  return ExprError();
3920 
3921  QualType T = TInfo->getType();
3922 
3923  if (!T->isDependentType() &&
3924  CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3925  return ExprError();
3926 
3927  if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3928  if (auto *TT = T->getAs<TypedefType>()) {
3929  for (auto I = FunctionScopes.rbegin(),
3930  E = std::prev(FunctionScopes.rend());
3931  I != E; ++I) {
3932  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3933  if (CSI == nullptr)
3934  break;
3935  DeclContext *DC = nullptr;
3936  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3937  DC = LSI->CallOperator;
3938  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3939  DC = CRSI->TheCapturedDecl;
3940  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3941  DC = BSI->TheDecl;
3942  if (DC) {
3943  if (DC->containsDecl(TT->getDecl()))
3944  break;
3945  captureVariablyModifiedType(Context, T, CSI);
3946  }
3947  }
3948  }
3949  }
3950 
3951  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3952  return new (Context) UnaryExprOrTypeTraitExpr(
3953  ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3954 }
3955 
3956 /// \brief Build a sizeof or alignof expression given an expression
3957 /// operand.
3958 ExprResult
3960  UnaryExprOrTypeTrait ExprKind) {
3961  ExprResult PE = CheckPlaceholderExpr(E);
3962  if (PE.isInvalid())
3963  return ExprError();
3964 
3965  E = PE.get();
3966 
3967  // Verify that the operand is valid.
3968  bool isInvalid = false;
3969  if (E->isTypeDependent()) {
3970  // Delay type-checking for type-dependent expressions.
3971  } else if (ExprKind == UETT_AlignOf) {
3972  isInvalid = CheckAlignOfExpr(*this, E);
3973  } else if (ExprKind == UETT_VecStep) {
3974  isInvalid = CheckVecStepExpr(E);
3975  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3976  Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3977  isInvalid = true;
3978  } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
3979  Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3980  isInvalid = true;
3981  } else {
3982  isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3983  }
3984 
3985  if (isInvalid)
3986  return ExprError();
3987 
3988  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3989  PE = TransformToPotentiallyEvaluated(E);
3990  if (PE.isInvalid()) return ExprError();
3991  E = PE.get();
3992  }
3993 
3994  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3995  return new (Context) UnaryExprOrTypeTraitExpr(
3996  ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3997 }
3998 
3999 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4000 /// expr and the same for @c alignof and @c __alignof
4001 /// Note that the ArgRange is invalid if isType is false.
4002 ExprResult
4004  UnaryExprOrTypeTrait ExprKind, bool IsType,
4005  void *TyOrEx, SourceRange ArgRange) {
4006  // If error parsing type, ignore.
4007  if (!TyOrEx) return ExprError();
4008 
4009  if (IsType) {
4010  TypeSourceInfo *TInfo;
4011  (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4012  return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4013  }
4014 
4015  Expr *ArgEx = (Expr *)TyOrEx;
4016  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4017  return Result;
4018 }
4019 
4021  bool IsReal) {
4022  if (V.get()->isTypeDependent())
4023  return S.Context.DependentTy;
4024 
4025  // _Real and _Imag are only l-values for normal l-values.
4026  if (V.get()->getObjectKind() != OK_Ordinary) {
4027  V = S.DefaultLvalueConversion(V.get());
4028  if (V.isInvalid())
4029  return QualType();
4030  }
4031 
4032  // These operators return the element type of a complex type.
4033  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4034  return CT->getElementType();
4035 
4036  // Otherwise they pass through real integer and floating point types here.
4037  if (V.get()->getType()->isArithmeticType())
4038  return V.get()->getType();
4039 
4040  // Test for placeholders.
4041  ExprResult PR = S.CheckPlaceholderExpr(V.get());
4042  if (PR.isInvalid()) return QualType();
4043  if (PR.get() != V.get()) {
4044  V = PR;
4045  return CheckRealImagOperand(S, V, Loc, IsReal);
4046  }
4047 
4048  // Reject anything else.
4049  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4050  << (IsReal ? "__real" : "__imag");
4051  return QualType();
4052 }
4053 
4054 
4055 
4056 ExprResult
4058  tok::TokenKind Kind, Expr *Input) {
4059  UnaryOperatorKind Opc;
4060  switch (Kind) {
4061  default: llvm_unreachable("Unknown unary op!");
4062  case tok::plusplus: Opc = UO_PostInc; break;
4063  case tok::minusminus: Opc = UO_PostDec; break;
4064  }
4065 
4066  // Since this might is a postfix expression, get rid of ParenListExprs.
4067  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4068  if (Result.isInvalid()) return ExprError();
4069  Input = Result.get();
4070 
4071  return BuildUnaryOp(S, OpLoc, Opc, Input);
4072 }
4073 
4074 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4075 ///
4076 /// \return true on error
4078  SourceLocation opLoc,
4079  Expr *op) {
4080  assert(op->getType()->isObjCObjectPointerType());
4082  !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4083  return false;
4084 
4085  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4086  << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4087  << op->getSourceRange();
4088  return true;
4089 }
4090 
4092  auto *BaseNoParens = Base->IgnoreParens();
4093  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4094  return MSProp->getPropertyDecl()->getType()->isArrayType();
4095  return isa<MSPropertySubscriptExpr>(BaseNoParens);
4096 }
4097 
4098 ExprResult
4100  Expr *idx, SourceLocation rbLoc) {
4101  if (base && !base->getType().isNull() &&
4102  base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4103  return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4104  /*Length=*/nullptr, rbLoc);
4105 
4106  // Since this might be a postfix expression, get rid of ParenListExprs.
4107  if (isa<ParenListExpr>(base)) {
4108  ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4109  if (result.isInvalid()) return ExprError();
4110  base = result.get();
4111  }
4112 
4113  // Handle any non-overload placeholder types in the base and index
4114  // expressions. We can't handle overloads here because the other
4115  // operand might be an overloadable type, in which case the overload
4116  // resolution for the operator overload should get the first crack
4117  // at the overload.
4118  bool IsMSPropertySubscript = false;
4119  if (base->getType()->isNonOverloadPlaceholderType()) {
4120  IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4121  if (!IsMSPropertySubscript) {
4122  ExprResult result = CheckPlaceholderExpr(base);
4123  if (result.isInvalid())
4124  return ExprError();
4125  base = result.get();
4126  }
4127  }
4128  if (idx->getType()->isNonOverloadPlaceholderType()) {
4129  ExprResult result = CheckPlaceholderExpr(idx);
4130  if (result.isInvalid()) return ExprError();
4131  idx = result.get();
4132  }
4133 
4134  // Build an unanalyzed expression if either operand is type-dependent.
4135  if (getLangOpts().CPlusPlus &&
4136  (base->isTypeDependent() || idx->isTypeDependent())) {
4137  return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4138  VK_LValue, OK_Ordinary, rbLoc);
4139  }
4140 
4141  // MSDN, property (C++)
4142  // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4143  // This attribute can also be used in the declaration of an empty array in a
4144  // class or structure definition. For example:
4145  // __declspec(property(get=GetX, put=PutX)) int x[];
4146  // The above statement indicates that x[] can be used with one or more array
4147  // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4148  // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4149  if (IsMSPropertySubscript) {
4150  // Build MS property subscript expression if base is MS property reference
4151  // or MS property subscript.
4152  return new (Context) MSPropertySubscriptExpr(
4153  base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4154  }
4155 
4156  // Use C++ overloaded-operator rules if either operand has record
4157  // type. The spec says to do this if either type is *overloadable*,
4158  // but enum types can't declare subscript operators or conversion
4159  // operators, so there's nothing interesting for overload resolution
4160  // to do if there aren't any record types involved.
4161  //
4162  // ObjC pointers have their own subscripting logic that is not tied
4163  // to overload resolution and so should not take this path.
4164  if (getLangOpts().CPlusPlus &&
4165  (base->getType()->isRecordType() ||
4166  (!base->getType()->isObjCObjectPointerType() &&
4167  idx->getType()->isRecordType()))) {
4168  return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4169  }
4170 
4171  return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4172 }
4173 
4175  Expr *LowerBound,
4176  SourceLocation ColonLoc, Expr *Length,
4177  SourceLocation RBLoc) {
4178  if (Base->getType()->isPlaceholderType() &&
4180  BuiltinType::OMPArraySection)) {
4181  ExprResult Result = CheckPlaceholderExpr(Base);
4182  if (Result.isInvalid())
4183  return ExprError();
4184  Base = Result.get();
4185  }
4186  if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4187  ExprResult Result = CheckPlaceholderExpr(LowerBound);
4188  if (Result.isInvalid())
4189  return ExprError();
4190  Result = DefaultLvalueConversion(Result.get());
4191  if (Result.isInvalid())
4192  return ExprError();
4193  LowerBound = Result.get();
4194  }
4195  if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4196  ExprResult Result = CheckPlaceholderExpr(Length);
4197  if (Result.isInvalid())
4198  return ExprError();
4199  Result = DefaultLvalueConversion(Result.get());
4200  if (Result.isInvalid())
4201  return ExprError();
4202  Length = Result.get();
4203  }
4204 
4205  // Build an unanalyzed expression if either operand is type-dependent.
4206  if (Base->isTypeDependent() ||
4207  (LowerBound &&
4208  (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4209  (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4210  return new (Context)
4211  OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4212  VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4213  }
4214 
4215  // Perform default conversions.
4217  QualType ResultTy;
4218  if (OriginalTy->isAnyPointerType()) {
4219  ResultTy = OriginalTy->getPointeeType();
4220  } else if (OriginalTy->isArrayType()) {
4221  ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4222  } else {
4223  return ExprError(
4224  Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4225  << Base->getSourceRange());
4226  }
4227  // C99 6.5.2.1p1
4228  if (LowerBound) {
4229  auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4230  LowerBound);
4231  if (Res.isInvalid())
4232  return ExprError(Diag(LowerBound->getExprLoc(),
4233  diag::err_omp_typecheck_section_not_integer)
4234  << 0 << LowerBound->getSourceRange());
4235  LowerBound = Res.get();
4236 
4237  if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4238  LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4239  Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4240  << 0 << LowerBound->getSourceRange();
4241  }
4242  if (Length) {
4243  auto Res =
4244  PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4245  if (Res.isInvalid())
4246  return ExprError(Diag(Length->getExprLoc(),
4247  diag::err_omp_typecheck_section_not_integer)
4248  << 1 << Length->getSourceRange());
4249  Length = Res.get();
4250 
4251  if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4252  Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4253  Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4254  << 1 << Length->getSourceRange();
4255  }
4256 
4257  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4258  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4259  // type. Note that functions are not objects, and that (in C99 parlance)
4260  // incomplete types are not object types.
4261  if (ResultTy->isFunctionType()) {
4262  Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4263  << ResultTy << Base->getSourceRange();
4264  return ExprError();
4265  }
4266 
4267  if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4268  diag::err_omp_section_incomplete_type, Base))
4269  return ExprError();
4270 
4271  if (LowerBound && !OriginalTy->isAnyPointerType()) {
4272  llvm::APSInt LowerBoundValue;
4273  if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4274  // OpenMP 4.5, [2.4 Array Sections]
4275  // The array section must be a subset of the original array.
4276  if (LowerBoundValue.isNegative()) {
4277  Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4278  << LowerBound->getSourceRange();
4279  return ExprError();
4280  }
4281  }
4282  }
4283 
4284  if (Length) {
4285  llvm::APSInt LengthValue;
4286  if (Length->EvaluateAsInt(LengthValue, Context)) {
4287  // OpenMP 4.5, [2.4 Array Sections]
4288  // The length must evaluate to non-negative integers.
4289  if (LengthValue.isNegative()) {
4290  Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4291  << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4292  << Length->getSourceRange();
4293  return ExprError();
4294  }
4295  }
4296  } else if (ColonLoc.isValid() &&
4297  (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4298  !OriginalTy->isVariableArrayType()))) {
4299  // OpenMP 4.5, [2.4 Array Sections]
4300  // When the size of the array dimension is not known, the length must be
4301  // specified explicitly.
4302  Diag(ColonLoc, diag::err_omp_section_length_undefined)
4303  << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4304  return ExprError();
4305  }
4306 
4307  if (!Base->getType()->isSpecificPlaceholderType(
4308  BuiltinType::OMPArraySection)) {
4309  ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4310  if (Result.isInvalid())
4311  return ExprError();
4312  Base = Result.get();
4313  }
4314  return new (Context)
4315  OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4316  VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4317 }
4318 
4319 ExprResult
4321  Expr *Idx, SourceLocation RLoc) {
4322  Expr *LHSExp = Base;
4323  Expr *RHSExp = Idx;
4324 
4325  ExprValueKind VK = VK_LValue;
4327 
4328  // Per C++ core issue 1213, the result is an xvalue if either operand is
4329  // a non-lvalue array, and an lvalue otherwise.
4330  if (getLangOpts().CPlusPlus11 &&
4331  ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4332  (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4333  VK = VK_XValue;
4334 
4335  // Perform default conversions.
4336  if (!LHSExp->getType()->getAs<VectorType>()) {
4337  ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4338  if (Result.isInvalid())
4339  return ExprError();
4340  LHSExp = Result.get();
4341  }
4342  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4343  if (Result.isInvalid())
4344  return ExprError();
4345  RHSExp = Result.get();
4346 
4347  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4348 
4349  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4350  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4351  // in the subscript position. As a result, we need to derive the array base
4352  // and index from the expression types.
4353  Expr *BaseExpr, *IndexExpr;
4354  QualType ResultType;
4355  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4356  BaseExpr = LHSExp;
4357  IndexExpr = RHSExp;
4358  ResultType = Context.DependentTy;
4359  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4360  BaseExpr = LHSExp;
4361  IndexExpr = RHSExp;
4362  ResultType = PTy->getPointeeType();
4363  } else if (const ObjCObjectPointerType *PTy =
4364  LHSTy->getAs<ObjCObjectPointerType>()) {
4365  BaseExpr = LHSExp;
4366  IndexExpr = RHSExp;
4367 
4368  // Use custom logic if this should be the pseudo-object subscript
4369  // expression.
4370  if (!LangOpts.isSubscriptPointerArithmetic())
4371  return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4372  nullptr);
4373 
4374  ResultType = PTy->getPointeeType();
4375  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4376  // Handle the uncommon case of "123[Ptr]".
4377  BaseExpr = RHSExp;
4378  IndexExpr = LHSExp;
4379  ResultType = PTy->getPointeeType();
4380  } else if (const ObjCObjectPointerType *PTy =
4381  RHSTy->getAs<ObjCObjectPointerType>()) {
4382  // Handle the uncommon case of "123[Ptr]".
4383  BaseExpr = RHSExp;
4384  IndexExpr = LHSExp;
4385  ResultType = PTy->getPointeeType();
4386  if (!LangOpts.isSubscriptPointerArithmetic()) {
4387  Diag(LLoc, diag::err_subscript_nonfragile_interface)
4388  << ResultType << BaseExpr->getSourceRange();
4389  return ExprError();
4390  }
4391  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4392  BaseExpr = LHSExp; // vectors: V[123]
4393  IndexExpr = RHSExp;
4394  VK = LHSExp->getValueKind();
4395  if (VK != VK_RValue)
4396  OK = OK_VectorComponent;
4397 
4398  // FIXME: need to deal with const...
4399  ResultType = VTy->getElementType();
4400  } else if (LHSTy->isArrayType()) {
4401  // If we see an array that wasn't promoted by
4402  // DefaultFunctionArrayLvalueConversion, it must be an array that
4403  // wasn't promoted because of the C90 rule that doesn't
4404  // allow promoting non-lvalue arrays. Warn, then
4405  // force the promotion here.
4406  Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4407  LHSExp->getSourceRange();
4408  LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4409  CK_ArrayToPointerDecay).get();
4410  LHSTy = LHSExp->getType();
4411 
4412  BaseExpr = LHSExp;
4413  IndexExpr = RHSExp;
4414  ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4415  } else if (RHSTy->isArrayType()) {
4416  // Same as previous, except for 123[f().a] case
4417  Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4418  RHSExp->getSourceRange();
4419  RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4420  CK_ArrayToPointerDecay).get();
4421  RHSTy = RHSExp->getType();
4422 
4423  BaseExpr = RHSExp;
4424  IndexExpr = LHSExp;
4425  ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4426  } else {
4427  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4428  << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4429  }
4430  // C99 6.5.2.1p1
4431  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4432  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4433  << IndexExpr->getSourceRange());
4434 
4435  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4436  IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4437  && !IndexExpr->isTypeDependent())
4438  Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4439 
4440  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4441  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4442  // type. Note that Functions are not objects, and that (in C99 parlance)
4443  // incomplete types are not object types.
4444  if (ResultType->isFunctionType()) {
4445  Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4446  << ResultType << BaseExpr->getSourceRange();
4447  return ExprError();
4448  }
4449 
4450  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4451  // GNU extension: subscripting on pointer to void
4452  Diag(LLoc, diag::ext_gnu_subscript_void_type)
4453  << BaseExpr->getSourceRange();
4454 
4455  // C forbids expressions of unqualified void type from being l-values.
4456  // See IsCForbiddenLValueType.
4457  if (!ResultType.hasQualifiers()) VK = VK_RValue;
4458  } else if (!ResultType->isDependentType() &&
4459  RequireCompleteType(LLoc, ResultType,
4460  diag::err_subscript_incomplete_type, BaseExpr))
4461  return ExprError();
4462 
4463  assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4464  !ResultType.isCForbiddenLValueType());
4465 
4466  return new (Context)
4467  ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4468 }
4469 
4471  ParmVarDecl *Param) {
4472  if (Param->hasUnparsedDefaultArg()) {
4473  Diag(CallLoc,
4474  diag::err_use_of_default_argument_to_function_declared_later) <<
4475  FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4476  Diag(UnparsedDefaultArgLocs[Param],
4477  diag::note_default_argument_declared_here);
4478  return true;
4479  }
4480 
4481  if (Param->hasUninstantiatedDefaultArg()) {
4482  Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4483 
4485  *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4486 
4487  // Instantiate the expression.
4488  //
4489  // FIXME: Pass in a correct Pattern argument, otherwise
4490  // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4491  //
4492  // template<typename T>
4493  // struct A {
4494  // static int FooImpl();
4495  //
4496  // template<typename Tp>
4497  // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4498  // // template argument list [[T], [Tp]], should be [[Tp]].
4499  // friend A<Tp> Foo(int a);
4500  // };
4501  //
4502  // template<typename T>
4503  // A<T> Foo(int a = A<T>::FooImpl());
4504  MultiLevelTemplateArgumentList MutiLevelArgList
4505  = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4506 
4507  InstantiatingTemplate Inst(*this, CallLoc, Param,
4508  MutiLevelArgList.getInnermost());
4509  if (Inst.isInvalid())
4510  return true;
4511  if (Inst.isAlreadyInstantiating()) {
4512  Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4513  Param->setInvalidDecl();
4514  return true;
4515  }
4516 
4517  ExprResult Result;
4518  {
4519  // C++ [dcl.fct.default]p5:
4520  // The names in the [default argument] expression are bound, and
4521  // the semantic constraints are checked, at the point where the
4522  // default argument expression appears.
4523  ContextRAII SavedContext(*this, FD);
4524  LocalInstantiationScope Local(*this);
4525  Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4526  /*DirectInit*/false);
4527  }
4528  if (Result.isInvalid())
4529  return true;
4530 
4531  // Check the expression as an initializer for the parameter.
4532  InitializedEntity Entity
4533  = InitializedEntity::InitializeParameter(Context, Param);
4536  /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4537  Expr *ResultE = Result.getAs<Expr>();
4538 
4539  InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4540  Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4541  if (Result.isInvalid())
4542  return true;
4543 
4544  Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4545  Param->getOuterLocStart());
4546  if (Result.isInvalid())
4547  return true;
4548 
4549  // Remember the instantiated default argument.
4550  Param->setDefaultArg(Result.getAs<Expr>());
4551  if (ASTMutationListener *L = getASTMutationListener()) {
4552  L->DefaultArgumentInstantiated(Param);
4553  }
4554  }
4555 
4556  // If the default argument expression is not set yet, we are building it now.
4557  if (!Param->hasInit()) {
4558  Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4559  Param->setInvalidDecl();
4560  return true;
4561  }
4562 
4563  // If the default expression creates temporaries, we need to
4564  // push them to the current stack of expression temporaries so they'll
4565  // be properly destroyed.
4566  // FIXME: We should really be rebuilding the default argument with new
4567  // bound temporaries; see the comment in PR5810.
4568  // We don't need to do that with block decls, though, because
4569  // blocks in default argument expression can never capture anything.
4570  if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4571  // Set the "needs cleanups" bit regardless of whether there are
4572  // any explicit objects.
4573  Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4574 
4575  // Append all the objects to the cleanup list. Right now, this
4576  // should always be a no-op, because blocks in default argument
4577  // expressions should never be able to capture anything.
4578  assert(!Init->getNumObjects() &&
4579  "default argument expression has capturing blocks?");
4580  }
4581 
4582  // We already type-checked the argument, so we know it works.
4583  // Just mark all of the declarations in this potentially-evaluated expression
4584  // as being "referenced".
4585  MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4586  /*SkipLocalVariables=*/true);
4587  return false;
4588 }
4589 
4591  FunctionDecl *FD, ParmVarDecl *Param) {
4592  if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4593  return ExprError();
4594  return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4595 }
4596 
4599  Expr *Fn) {
4600  if (Proto && Proto->isVariadic()) {
4601  if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4602  return VariadicConstructor;
4603  else if (Fn && Fn->getType()->isBlockPointerType())
4604  return VariadicBlock;
4605  else if (FDecl) {
4606  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4607  if (Method->isInstance())
4608  return VariadicMethod;
4609  } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4610  return VariadicMethod;
4611  return VariadicFunction;
4612  }
4613  return VariadicDoesNotApply;
4614 }
4615 
4616 namespace {
4617 class FunctionCallCCC : public FunctionCallFilterCCC {
4618 public:
4619  FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4620  unsigned NumArgs, MemberExpr *ME)
4621  : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4622  FunctionName(FuncName) {}
4623 
4624  bool ValidateCandidate(const TypoCorrection &candidate) override {
4625  if (!candidate.getCorrectionSpecifier() ||
4626  candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4627  return false;
4628  }
4629 
4630  return FunctionCallFilterCCC::ValidateCandidate(candidate);
4631  }
4632 
4633 private:
4634  const IdentifierInfo *const FunctionName;
4635 };
4636 }
4637 
4639  FunctionDecl *FDecl,
4640  ArrayRef<Expr *> Args) {
4641  MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4642  DeclarationName FuncName = FDecl->getDeclName();
4643  SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4644 
4645  if (TypoCorrection Corrected = S.CorrectTypo(
4646  DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4647  S.getScopeForContext(S.CurContext), nullptr,
4648  llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4649  Args.size(), ME),
4651  if (NamedDecl *ND = Corrected.getFoundDecl()) {
4652  if (Corrected.isOverloaded()) {
4655  for (NamedDecl *CD : Corrected) {
4656  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4657  S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4658  OCS);
4659  }
4660  switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4661  case OR_Success:
4662  ND = Best->FoundDecl;
4663  Corrected.setCorrectionDecl(ND);
4664  break;
4665  default:
4666  break;
4667  }
4668  }
4669  ND = ND->getUnderlyingDecl();
4670  if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4671  return Corrected;
4672  }
4673  }
4674  return TypoCorrection();
4675 }
4676 
4677 /// ConvertArgumentsForCall - Converts the arguments specified in
4678 /// Args/NumArgs to the parameter types of the function FDecl with
4679 /// function prototype Proto. Call is the call expression itself, and
4680 /// Fn is the function expression. For a C++ member function, this
4681 /// routine does not attempt to convert the object argument. Returns
4682 /// true if the call is ill-formed.
4683 bool
4685  FunctionDecl *FDecl,
4686  const FunctionProtoType *Proto,
4687  ArrayRef<Expr *> Args,
4688  SourceLocation RParenLoc,
4689  bool IsExecConfig) {
4690  // Bail out early if calling a builtin with custom typechecking.
4691  if (FDecl)
4692  if (unsigned ID = FDecl->getBuiltinID())
4693  if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4694  return false;
4695 
4696  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4697  // assignment, to the types of the corresponding parameter, ...
4698  unsigned NumParams = Proto->getNumParams();
4699  bool Invalid = false;
4700  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4701  unsigned FnKind = Fn->getType()->isBlockPointerType()
4702  ? 1 /* block */
4703  : (IsExecConfig ? 3 /* kernel function (exec config) */
4704  : 0 /* function */);
4705 
4706  // If too few arguments are available (and we don't have default
4707  // arguments for the remaining parameters), don't make the call.
4708  if (Args.size() < NumParams) {
4709  if (Args.size() < MinArgs) {
4710  TypoCorrection TC;
4711  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4712  unsigned diag_id =
4713  MinArgs == NumParams && !Proto->isVariadic()
4714  ? diag::err_typecheck_call_too_few_args_suggest
4715  : diag::err_typecheck_call_too_few_args_at_least_suggest;
4716  diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4717  << static_cast<unsigned>(Args.size())
4718  << TC.getCorrectionRange());
4719  } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4720  Diag(RParenLoc,
4721  MinArgs == NumParams && !Proto->isVariadic()
4722  ? diag::err_typecheck_call_too_few_args_one
4723  : diag::err_typecheck_call_too_few_args_at_least_one)
4724  << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4725  else
4726  Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4727  ? diag::err_typecheck_call_too_few_args
4728  : diag::err_typecheck_call_too_few_args_at_least)
4729  << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4730  << Fn->getSourceRange();
4731 
4732  // Emit the location of the prototype.
4733  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4734  Diag(FDecl->getLocStart(), diag::note_callee_decl)
4735  << FDecl;
4736 
4737  return true;
4738  }
4739  Call->setNumArgs(Context, NumParams);
4740  }
4741 
4742  // If too many are passed and not variadic, error on the extras and drop
4743  // them.
4744  if (Args.size() > NumParams) {
4745  if (!Proto->isVariadic()) {
4746  TypoCorrection TC;
4747  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4748  unsigned diag_id =
4749  MinArgs == NumParams && !Proto->isVariadic()
4750  ? diag::err_typecheck_call_too_many_args_suggest
4751  : diag::err_typecheck_call_too_many_args_at_most_suggest;
4752  diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4753  << static_cast<unsigned>(Args.size())
4754  << TC.getCorrectionRange());
4755  } else if (NumParams == 1 && FDecl &&
4756  FDecl->getParamDecl(0)->getDeclName())
4757  Diag(Args[NumParams]->getLocStart(),
4758  MinArgs == NumParams
4759  ? diag::err_typecheck_call_too_many_args_one
4760  : diag::err_typecheck_call_too_many_args_at_most_one)
4761  << FnKind << FDecl->getParamDecl(0)
4762  << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4763  << SourceRange(Args[NumParams]->getLocStart(),
4764  Args.back()->getLocEnd());
4765  else
4766  Diag(Args[NumParams]->getLocStart(),
4767  MinArgs == NumParams
4768  ? diag::err_typecheck_call_too_many_args
4769  : diag::err_typecheck_call_too_many_args_at_most)
4770  << FnKind << NumParams << static_cast<unsigned>(Args.size())
4771  << Fn->getSourceRange()
4772  << SourceRange(Args[NumParams]->getLocStart(),
4773  Args.back()->getLocEnd());
4774 
4775  // Emit the location of the prototype.
4776  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4777  Diag(FDecl->getLocStart(), diag::note_callee_decl)
4778  << FDecl;
4779 
4780  // This deletes the extra arguments.
4781  Call->setNumArgs(Context, NumParams);
4782  return true;
4783  }
4784  }
4785  SmallVector<Expr *, 8> AllArgs;
4786  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4787 
4788  Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4789  Proto, 0, Args, AllArgs, CallType);
4790  if (Invalid)
4791  return true;
4792  unsigned TotalNumArgs = AllArgs.size();
4793  for (unsigned i = 0; i < TotalNumArgs; ++i)
4794  Call->setArg(i, AllArgs[i]);
4795 
4796  return false;
4797 }
4798 
4800  const FunctionProtoType *Proto,
4801  unsigned FirstParam, ArrayRef<Expr *> Args,
4802  SmallVectorImpl<Expr *> &AllArgs,
4803  VariadicCallType CallType, bool AllowExplicit,
4804  bool IsListInitialization) {
4805  unsigned NumParams = Proto->getNumParams();
4806  bool Invalid = false;
4807  size_t ArgIx = 0;
4808  // Continue to check argument types (even if we have too few/many args).
4809  for (unsigned i = FirstParam; i < NumParams; i++) {
4810  QualType ProtoArgType = Proto->getParamType(i);
4811 
4812  Expr *Arg;
4813  ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4814  if (ArgIx < Args.size()) {
4815  Arg = Args[ArgIx++];
4816 
4817  if (RequireCompleteType(Arg->getLocStart(),
4818  ProtoArgType,
4819  diag::err_call_incomplete_argument, Arg))
4820  return true;
4821 
4822  // Strip the unbridged-cast placeholder expression off, if applicable.
4823  bool CFAudited = false;
4824  if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4825  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4826  (!Param || !Param->hasAttr<CFConsumedAttr>()))
4827  Arg = stripARCUnbridgedCast(Arg);
4828  else if (getLangOpts().ObjCAutoRefCount &&
4829  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4830  (!Param || !Param->hasAttr<CFConsumedAttr>()))
4831  CFAudited = true;
4832 
4833  InitializedEntity Entity =
4834  Param ? InitializedEntity::InitializeParameter(Context, Param,
4835  ProtoArgType)
4837  Context, ProtoArgType, Proto->isParamConsumed(i));
4838 
4839  // Remember that parameter belongs to a CF audited API.
4840  if (CFAudited)
4841  Entity.setParameterCFAudited();
4842 
4843  ExprResult ArgE = PerformCopyInitialization(
4844  Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4845  if (ArgE.isInvalid())
4846  return true;
4847 
4848  Arg = ArgE.getAs<Expr>();
4849  } else {
4850  assert(Param && "can't use default arguments without a known callee");
4851 
4852  ExprResult ArgExpr =
4853  BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4854  if (ArgExpr.isInvalid())
4855  return true;
4856 
4857  Arg = ArgExpr.getAs<Expr>();
4858  }
4859 
4860  // Check for array bounds violations for each argument to the call. This
4861  // check only triggers warnings when the argument isn't a more complex Expr
4862  // with its own checking, such as a BinaryOperator.
4863  CheckArrayAccess(Arg);
4864 
4865  // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4866  CheckStaticArrayArgument(CallLoc, Param, Arg);
4867 
4868  AllArgs.push_back(Arg);
4869  }
4870 
4871  // If this is a variadic call, handle args passed through "...".
4872  if (CallType != VariadicDoesNotApply) {
4873  // Assume that extern "C" functions with variadic arguments that
4874  // return __unknown_anytype aren't *really* variadic.
4875  if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4876  FDecl->isExternC()) {
4877  for (Expr *A : Args.slice(ArgIx)) {
4878  QualType paramType; // ignored
4879  ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4880  Invalid |= arg.isInvalid();
4881  AllArgs.push_back(arg.get());
4882  }
4883 
4884  // Otherwise do argument promotion, (C99 6.5.2.2p7).
4885  } else {
4886  for (Expr *A : Args.slice(ArgIx)) {
4887  ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4888  Invalid |= Arg.isInvalid();
4889  AllArgs.push_back(Arg.get());
4890  }
4891  }
4892 
4893  // Check for array bounds violations.
4894  for (Expr *A : Args.slice(ArgIx))
4895  CheckArrayAccess(A);
4896  }
4897  return Invalid;
4898 }
4899 
4901  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4902  if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4903  TL = DTL.getOriginalLoc();
4904  if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4905  S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4906  << ATL.getLocalSourceRange();
4907 }
4908 
4909 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4910 /// array parameter, check that it is non-null, and that if it is formed by
4911 /// array-to-pointer decay, the underlying array is sufficiently large.
4912 ///
4913 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4914 /// array type derivation, then for each call to the function, the value of the
4915 /// corresponding actual argument shall provide access to the first element of
4916 /// an array with at least as many elements as specified by the size expression.
4917 void
4919  ParmVarDecl *Param,
4920  const Expr *ArgExpr) {
4921  // Static array parameters are not supported in C++.
4922  if (!Param || getLangOpts().CPlusPlus)
4923  return;
4924 
4925  QualType OrigTy = Param->getOriginalType();
4926 
4927  const ArrayType *AT = Context.getAsArrayType(OrigTy);
4928  if (!AT || AT->getSizeModifier() != ArrayType::Static)
4929  return;
4930 
4931  if (ArgExpr->isNullPointerConstant(Context,
4933  Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4934  DiagnoseCalleeStaticArrayParam(*this, Param);
4935  return;
4936  }
4937 
4938  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4939  if (!CAT)
4940  return;
4941 
4942  const ConstantArrayType *ArgCAT =
4943  Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4944  if (!ArgCAT)
4945  return;
4946 
4947  if (ArgCAT->getSize().ult(CAT->getSize())) {
4948  Diag(CallLoc, diag::warn_static_array_too_small)
4949  << ArgExpr->getSourceRange()
4950  << (unsigned) ArgCAT->getSize().getZExtValue()
4951  << (unsigned) CAT->getSize().getZExtValue();
4952  DiagnoseCalleeStaticArrayParam(*this, Param);
4953  }
4954 }
4955 
4956 /// Given a function expression of unknown-any type, try to rebuild it
4957 /// to have a function type.
4959 
4960 /// Is the given type a placeholder that we need to lower out
4961 /// immediately during argument processing?
4963  // Placeholders are never sugared.
4964  const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4965  if (!placeholder) return false;
4966 
4967  switch (placeholder->getKind()) {
4968  // Ignore all the non-placeholder types.
4969 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4970  case BuiltinType::Id:
4971 #include "clang/Basic/OpenCLImageTypes.def"
4972 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4973 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4974 #include "clang/AST/BuiltinTypes.def"
4975  return false;
4976 
4977  // We cannot lower out overload sets; they might validly be resolved
4978  // by the call machinery.
4979  case BuiltinType::Overload:
4980  return false;
4981 
4982  // Unbridged casts in ARC can be handled in some call positions and
4983  // should be left in place.
4984  case BuiltinType::ARCUnbridgedCast:
4985  return false;
4986 
4987  // Pseudo-objects should be converted as soon as possible.
4988  case BuiltinType::PseudoObject:
4989  return true;
4990 
4991  // The debugger mode could theoretically but currently does not try
4992  // to resolve unknown-typed arguments based on known parameter types.
4993  case BuiltinType::UnknownAny:
4994  return true;
4995 
4996  // These are always invalid as call arguments and should be reported.
4997  case BuiltinType::BoundMember:
4998  case BuiltinType::BuiltinFn:
4999  case BuiltinType::OMPArraySection:
5000  return true;
5001 
5002  }
5003  llvm_unreachable("bad builtin type kind");
5004 }
5005 
5006 /// Check an argument list for placeholders that we won't try to
5007 /// handle later.
5009  // Apply this processing to all the arguments at once instead of
5010  // dying at the first failure.
5011  bool hasInvalid = false;
5012  for (size_t i = 0, e = args.size(); i != e; i++) {
5013  if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5014  ExprResult result = S.CheckPlaceholderExpr(args[i]);
5015  if (result.isInvalid()) hasInvalid = true;
5016  else args[i] = result.get();
5017  } else if (hasInvalid) {
5018  (void)S.CorrectDelayedTyposInExpr(args[i]);
5019  }
5020  }
5021  return hasInvalid;
5022 }
5023 
5024 /// If a builtin function has a pointer argument with no explicit address
5025 /// space, then it should be able to accept a pointer to any address
5026 /// space as input. In order to do this, we need to replace the
5027 /// standard builtin declaration with one that uses the same address space
5028 /// as the call.
5029 ///
5030 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5031 /// it does not contain any pointer arguments without
5032 /// an address space qualifer. Otherwise the rewritten
5033 /// FunctionDecl is returned.
5034 /// TODO: Handle pointer return types.
5036  const FunctionDecl *FDecl,
5037  MultiExprArg ArgExprs) {
5038 
5039  QualType DeclType = FDecl->getType();
5040  const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5041 
5042  if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5043  !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5044  return nullptr;
5045 
5046  bool NeedsNewDecl = false;
5047  unsigned i = 0;
5048  SmallVector<QualType, 8> OverloadParams;
5049 
5050  for (QualType ParamType : FT->param_types()) {
5051 
5052  // Convert array arguments to pointer to simplify type lookup.
5053  ExprResult ArgRes =
5054  Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5055  if (ArgRes.isInvalid())
5056  return nullptr;
5057  Expr *Arg = ArgRes.get();
5058  QualType ArgType = Arg->getType();
5059  if (!ParamType->isPointerType() ||
5060  ParamType.getQualifiers().hasAddressSpace() ||
5061  !ArgType->isPointerType() ||
5062  !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5063  OverloadParams.push_back(ParamType);
5064  continue;
5065  }
5066 
5067  NeedsNewDecl = true;
5068  LangAS AS = ArgType->getPointeeType().getAddressSpace();
5069 
5070  QualType PointeeType = ParamType->getPointeeType();
5071  PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5072  OverloadParams.push_back(Context.getPointerType(PointeeType));
5073  }
5074 
5075  if (!NeedsNewDecl)
5076  return nullptr;
5077 
5079  QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5080  OverloadParams, EPI);
5082  FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5083  FDecl->getLocation(),
5084  FDecl->getLocation(),
5085  FDecl->getIdentifier(),
5086  OverloadTy,
5087  /*TInfo=*/nullptr,
5088  SC_Extern, false,
5089  /*hasPrototype=*/true);
5091  FT = cast<FunctionProtoType>(OverloadTy);
5092  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5093  QualType ParamType = FT->getParamType(i);
5094  ParmVarDecl *Parm =
5095  ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5096  SourceLocation(), nullptr, ParamType,
5097  /*TInfo=*/nullptr, SC_None, nullptr);
5098  Parm->setScopeInfo(0, i);
5099  Params.push_back(Parm);
5100  }
5101  OverloadDecl->setParams(Params);
5102  return OverloadDecl;
5103 }
5104 
5105 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5106  FunctionDecl *Callee,
5107  MultiExprArg ArgExprs) {
5108  // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5109  // similar attributes) really don't like it when functions are called with an
5110  // invalid number of args.
5111  if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5112  /*PartialOverloading=*/false) &&
5113  !Callee->isVariadic())
5114  return;
5115  if (Callee->getMinRequiredArguments() > ArgExprs.size())
5116  return;
5117 
5118  if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5119  S.Diag(Fn->getLocStart(),
5120  isa<CXXMethodDecl>(Callee)
5121  ? diag::err_ovl_no_viable_member_function_in_call
5122  : diag::err_ovl_no_viable_function_in_call)
5123  << Callee << Callee->getSourceRange();
5124  S.Diag(Callee->getLocation(),
5125  diag::note_ovl_candidate_disabled_by_function_cond_attr)
5126  << Attr->getCond()->getSourceRange() << Attr->getMessage();
5127  return;
5128  }
5129 }
5130 
5132  const UnresolvedMemberExpr *const UME, Sema &S) {
5133 
5134  const auto GetFunctionLevelDCIfCXXClass =
5135  [](Sema &S) -> const CXXRecordDecl * {
5136  const DeclContext *const DC = S.getFunctionLevelDeclContext();
5137  if (!DC || !DC->getParent())
5138  return nullptr;
5139 
5140  // If the call to some member function was made from within a member
5141  // function body 'M' return return 'M's parent.
5142  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5143  return MD->getParent()->getCanonicalDecl();
5144  // else the call was made from within a default member initializer of a
5145  // class, so return the class.
5146  if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5147  return RD->getCanonicalDecl();
5148  return nullptr;
5149  };
5150  // If our DeclContext is neither a member function nor a class (in the
5151  // case of a lambda in a default member initializer), we can't have an
5152  // enclosing 'this'.
5153 
5154  const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5155  if (!CurParentClass)
5156  return false;
5157 
5158  // The naming class for implicit member functions call is the class in which
5159  // name lookup starts.
5160  const CXXRecordDecl *const NamingClass =
5161  UME->getNamingClass()->getCanonicalDecl();
5162  assert(NamingClass && "Must have naming class even for implicit access");
5163 
5164  // If the unresolved member functions were found in a 'naming class' that is
5165  // related (either the same or derived from) to the class that contains the
5166  // member function that itself contained the implicit member access.
5167 
5168  return CurParentClass == NamingClass ||
5169  CurParentClass->isDerivedFrom(NamingClass);
5170 }
5171 
5172 static void
5174  Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5175 
5176  if (!UME)
5177  return;
5178 
5179  LambdaScopeInfo *const CurLSI = S.getCurLambda();
5180  // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5181  // already been captured, or if this is an implicit member function call (if
5182  // it isn't, an attempt to capture 'this' should already have been made).
5183  if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5184  !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5185  return;
5186 
5187  // Check if the naming class in which the unresolved members were found is
5188  // related (same as or is a base of) to the enclosing class.
5189 
5191  return;
5192 
5193 
5194  DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5195  // If the enclosing function is not dependent, then this lambda is
5196  // capture ready, so if we can capture this, do so.
5197  if (!EnclosingFunctionCtx->isDependentContext()) {
5198  // If the current lambda and all enclosing lambdas can capture 'this' -
5199  // then go ahead and capture 'this' (since our unresolved overload set
5200  // contains at least one non-static member function).
5201  if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5202  S.CheckCXXThisCapture(CallLoc);
5203  } else if (S.CurContext->isDependentContext()) {
5204  // ... since this is an implicit member reference, that might potentially
5205  // involve a 'this' capture, mark 'this' for potential capture in
5206  // enclosing lambdas.
5207  if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5208  CurLSI->addPotentialThisCapture(CallLoc);
5209  }
5210 }
5211 
5212 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5213 /// This provides the location of the left/right parens and a list of comma
5214 /// locations.
5216  MultiExprArg ArgExprs, SourceLocation RParenLoc,
5217  Expr *ExecConfig, bool IsExecConfig) {
5218  // Since this might be a postfix expression, get rid of ParenListExprs.
5219  ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5220  if (Result.isInvalid()) return ExprError();
5221  Fn = Result.get();
5222 
5223  if (checkArgsForPlaceholders(*this, ArgExprs))
5224  return ExprError();
5225 
5226  if (getLangOpts().CPlusPlus) {
5227  // If this is a pseudo-destructor expression, build the call immediately.
5228  if (isa<CXXPseudoDestructorExpr>(Fn)) {
5229  if (!ArgExprs.empty()) {
5230  // Pseudo-destructor calls should not have any arguments.
5231  Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5233  SourceRange(ArgExprs.front()->getLocStart(),
5234  ArgExprs.back()->getLocEnd()));
5235  }
5236 
5237  return new (Context)
5238  CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5239  }
5240  if (Fn->getType() == Context.PseudoObjectTy) {
5241  ExprResult result = CheckPlaceholderExpr(Fn);
5242  if (result.isInvalid()) return ExprError();
5243  Fn = result.get();
5244  }
5245 
5246  // Determine whether this is a dependent call inside a C++ template,
5247  // in which case we won't do any semantic analysis now.
5248  bool Dependent = false;
5249  if (Fn->isTypeDependent())
5250  Dependent = true;
5251  else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5252  Dependent = true;
5253 
5254  if (Dependent) {
5255  if (ExecConfig) {
5256  return new (Context) CUDAKernelCallExpr(
5257  Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5258  Context.DependentTy, VK_RValue, RParenLoc);
5259  } else {
5260 
5262  *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5263  Fn->getLocStart());
5264 
5265  return new (Context) CallExpr(
5266  Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5267  }
5268  }
5269 
5270  // Determine whether this is a call to an object (C++ [over.call.object]).
5271  if (Fn->getType()->isRecordType())
5272  return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5273  RParenLoc);
5274 
5275  if (Fn->getType() == Context.UnknownAnyTy) {
5276  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5277  if (result.isInvalid()) return ExprError();
5278  Fn = result.get();
5279  }
5280 
5281  if (Fn->getType() == Context.BoundMemberTy) {
5282  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5283  RParenLoc);
5284  }
5285  }
5286 
5287  // Check for overloaded calls. This can happen even in C due to extensions.
5288  if (Fn->getType() == Context.OverloadTy) {
5290 
5291  // We aren't supposed to apply this logic if there's an '&' involved.
5292  if (!find.HasFormOfMemberPointer) {
5293  if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5294  return new (Context) CallExpr(
5295  Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5296  OverloadExpr *ovl = find.Expression;
5297  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5298  return BuildOverloadedCallExpr(
5299  Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5300  /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5301  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5302  RParenLoc);
5303  }
5304  }
5305 
5306  // If we're directly calling a function, get the appropriate declaration.
5307  if (Fn->getType() == Context.UnknownAnyTy) {
5308  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5309  if (result.isInvalid()) return ExprError();
5310  Fn = result.get();
5311  }
5312 
5313  Expr *NakedFn = Fn->IgnoreParens();
5314 
5315  bool CallingNDeclIndirectly = false;
5316  NamedDecl *NDecl = nullptr;
5317  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5318  if (UnOp->getOpcode() == UO_AddrOf) {
5319  CallingNDeclIndirectly = true;
5320  NakedFn = UnOp->getSubExpr()->IgnoreParens();
5321  }
5322  }
5323 
5324  if (isa<DeclRefExpr>(NakedFn)) {
5325  NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5326 
5327  FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5328  if (FDecl && FDecl->getBuiltinID()) {
5329  // Rewrite the function decl for this builtin by replacing parameters
5330  // with no explicit address space with the address space of the arguments
5331  // in ArgExprs.
5332  if ((FDecl =
5333  rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5334  NDecl = FDecl;
5335  Fn = DeclRefExpr::Create(
5336  Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5337  SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5338  }
5339  }
5340  } else if (isa<MemberExpr>(NakedFn))
5341  NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5342 
5343  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5344  if (CallingNDeclIndirectly &&
5345  !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5346  Fn->getLocStart()))
5347  return ExprError();
5348 
5349  if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5350  return ExprError();
5351 
5352  checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5353  }
5354 
5355  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5356  ExecConfig, IsExecConfig);
5357 }
5358 
5359 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5360 ///
5361 /// __builtin_astype( value, dst type )
5362 ///
5364  SourceLocation BuiltinLoc,
5365  SourceLocation RParenLoc) {
5366  ExprValueKind VK = VK_RValue;
5368  QualType DstTy = GetTypeFromParser(ParsedDestTy);
5369  QualType SrcTy = E->getType();
5370  if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5371  return ExprError(Diag(BuiltinLoc,
5372  diag::err_invalid_astype_of_different_size)
5373  << DstTy
5374  << SrcTy
5375  << E->getSourceRange());
5376  return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5377 }
5378 
5379 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5380 /// provided arguments.
5381 ///
5382 /// __builtin_convertvector( value, dst type )
5383 ///
5385  SourceLocation BuiltinLoc,
5386  SourceLocation RParenLoc) {
5387  TypeSourceInfo *TInfo;
5388  GetTypeFromParser(ParsedDestTy, &TInfo);
5389  return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5390 }
5391 
5392 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5393 /// i.e. an expression not of \p OverloadTy. The expression should
5394 /// unary-convert to an expression of function-pointer or
5395 /// block-pointer type.
5396 ///
5397 /// \param NDecl the declaration being called, if available
5398 ExprResult
5400  SourceLocation LParenLoc,
5401  ArrayRef<Expr *> Args,
5402  SourceLocation RParenLoc,
5403  Expr *Config, bool IsExecConfig) {
5404  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5405  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5406 
5407  // Functions with 'interrupt' attribute cannot be called directly.
5408  if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5409  Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5410  return ExprError();
5411  }
5412 
5413  // Interrupt handlers don't save off the VFP regs automatically on ARM,
5414  // so there's some risk when calling out to non-interrupt handler functions
5415  // that the callee might not preserve them. This is easy to diagnose here,
5416  // but can be very challenging to debug.
5417  if (auto *Caller = getCurFunctionDecl())
5418  if (Caller->hasAttr<ARMInterruptAttr>()) {
5419  bool VFP = Context.getTargetInfo().hasFeature("vfp");
5420  if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5421  Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5422  }
5423 
5424  // Promote the function operand.
5425  // We special-case function promotion here because we only allow promoting
5426  // builtin functions to function pointers in the callee of a call.
5427  ExprResult Result;
5428  if (BuiltinID &&
5429  Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5430  Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5431  CK_BuiltinFnToFnPtr).get();
5432  } else {
5433  Result = CallExprUnaryConversions(Fn);
5434  }
5435  if (Result.isInvalid())
5436  return ExprError();
5437  Fn = Result.get();
5438 
5439  // Make the call expr early, before semantic checks. This guarantees cleanup
5440  // of arguments and function on error.
5441  CallExpr *TheCall;
5442  if (Config)
5443  TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5444  cast<CallExpr>(Config), Args,
5445  Context.BoolTy, VK_RValue,
5446  RParenLoc);
5447  else
5448  TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5449  VK_RValue, RParenLoc);
5450 
5451  if (!getLangOpts().CPlusPlus) {
5452  // C cannot always handle TypoExpr nodes in builtin calls and direct
5453  // function calls as their argument checking don't necessarily handle
5454  // dependent types properly, so make sure any TypoExprs have been
5455  // dealt with.
5456  ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5457  if (!Result.isUsable()) return ExprError();
5458  TheCall = dyn_cast<CallExpr>(Result.get());
5459  if (!TheCall) return Result;
5460  Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5461  }
5462 
5463  // Bail out early if calling a builtin with custom typechecking.
5464  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5465  return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5466 
5467  retry:
5468  const FunctionType *FuncT;
5469  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5470  // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5471  // have type pointer to function".
5472  FuncT = PT->getPointeeType()->getAs<FunctionType>();
5473  if (!FuncT)
5474  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5475  << Fn->getType() << Fn->getSourceRange());
5476  } else if (const BlockPointerType *BPT =
5477  Fn->getType()->getAs<BlockPointerType>()) {
5478  FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5479  } else {
5480  // Handle calls to expressions of unknown-any type.
5481  if (Fn->getType() == Context.UnknownAnyTy) {
5482  ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5483  if (rewrite.isInvalid()) return ExprError();
5484  Fn = rewrite.get();
5485  TheCall->setCallee(Fn);
5486  goto retry;
5487  }
5488 
5489  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5490  << Fn->getType() << Fn->getSourceRange());
5491  }
5492 
5493  if (getLangOpts().CUDA) {
5494  if (Config) {
5495  // CUDA: Kernel calls must be to global functions
5496  if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5497  return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5498  << FDecl->getName() << Fn->getSourceRange());
5499 
5500  // CUDA: Kernel function must have 'void' return type
5501  if (!FuncT->getReturnType()->isVoidType())
5502  return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5503  << Fn->getType() << Fn->getSourceRange());
5504  } else {
5505  // CUDA: Calls to global functions must be configured
5506  if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5507  return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5508  << FDecl->getName() << Fn->getSourceRange());
5509  }
5510  }
5511 
5512  // Check for a valid return type
5513  if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5514  FDecl))
5515  return ExprError();
5516 
5517  // We know the result type of the call, set it.
5518  TheCall->setType(FuncT->getCallResultType(Context));
5520 
5521  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5522  if (Proto) {
5523  if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5524  IsExecConfig))
5525  return ExprError();
5526  } else {
5527  assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5528 
5529  if (FDecl) {
5530  // Check if we have too few/too many template arguments, based
5531  // on our knowledge of the function definition.
5532  const FunctionDecl *Def = nullptr;
5533  if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5534  Proto = Def->getType()->getAs<FunctionProtoType>();
5535  if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5536  Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5537  << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5538  }
5539 
5540  // If the function we're calling isn't a function prototype, but we have
5541  // a function prototype from a prior declaratiom, use that prototype.
5542  if (!FDecl->hasPrototype())
5543  Proto = FDecl->getType()->getAs<FunctionProtoType>();
5544  }
5545 
5546  // Promote the arguments (C99 6.5.2.2p6).
5547  for (unsigned i = 0, e = Args.size(); i != e; i++) {
5548  Expr *Arg = Args[i];
5549 
5550  if (Proto && i < Proto->getNumParams()) {
5551