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