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