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