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