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