clang  9.0.0svn
SemaExpr.cpp
Go to the documentation of this file.
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/FixedPoint.h"
31 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Overload.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54  // See if this is an auto-typed variable whose initializer we are parsing.
55  if (ParsingInitForAutoVars.count(D))
56  return false;
57 
58  // See if this is a deleted function.
59  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60  if (FD->isDeleted())
61  return false;
62 
63  // If the function has a deduced return type, and we can't deduce it,
64  // then we can't use it either.
65  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66  DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67  return false;
68 
69  // See if this is an aligned allocation/deallocation function that is
70  // unavailable.
71  if (TreatUnavailableAsInvalid &&
72  isUnavailableAlignedAllocationFunction(*FD))
73  return false;
74  }
75 
76  // See if this function is unavailable.
77  if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
78  cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
79  return false;
80 
81  return true;
82 }
83 
85  // Warn if this is used but marked unused.
86  if (const auto *A = D->getAttr<UnusedAttr>()) {
87  // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
88  // should diagnose them.
89  if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
90  A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
91  const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
92  if (DC && !DC->hasAttr<UnusedAttr>())
93  S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
94  }
95  }
96 }
97 
98 /// Emit a note explaining that this function is deleted.
100  assert(Decl->isDeleted());
101 
102  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
103 
104  if (Method && Method->isDeleted() && Method->isDefaulted()) {
105  // If the method was explicitly defaulted, point at that declaration.
106  if (!Method->isImplicit())
107  Diag(Decl->getLocation(), diag::note_implicitly_deleted);
108 
109  // Try to diagnose why this special member function was implicitly
110  // deleted. This might fail, if that reason no longer applies.
111  CXXSpecialMember CSM = getSpecialMember(Method);
112  if (CSM != CXXInvalid)
113  ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
114 
115  return;
116  }
117 
118  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
119  if (Ctor && Ctor->isInheritingConstructor())
120  return NoteDeletedInheritingConstructor(Ctor);
121 
122  Diag(Decl->getLocation(), diag::note_availability_specified_here)
123  << Decl << 1;
124 }
125 
126 /// Determine whether a FunctionDecl was ever declared with an
127 /// explicit storage class.
129  for (auto I : D->redecls()) {
130  if (I->getStorageClass() != SC_None)
131  return true;
132  }
133  return false;
134 }
135 
136 /// Check whether we're in an extern inline function and referring to a
137 /// variable or function with internal linkage (C11 6.7.4p3).
138 ///
139 /// This is only a warning because we used to silently accept this code, but
140 /// in many cases it will not behave correctly. This is not enabled in C++ mode
141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
142 /// and so while there may still be user mistakes, most of the time we can't
143 /// prove that there are errors.
145  const NamedDecl *D,
146  SourceLocation Loc) {
147  // This is disabled under C++; there are too many ways for this to fire in
148  // contexts where the warning is a false positive, or where it is technically
149  // correct but benign.
150  if (S.getLangOpts().CPlusPlus)
151  return;
152 
153  // Check if this is an inlined function or method.
154  FunctionDecl *Current = S.getCurFunctionDecl();
155  if (!Current)
156  return;
157  if (!Current->isInlined())
158  return;
159  if (!Current->isExternallyVisible())
160  return;
161 
162  // Check if the decl has internal linkage.
163  if (D->getFormalLinkage() != InternalLinkage)
164  return;
165 
166  // Downgrade from ExtWarn to Extension if
167  // (1) the supposedly external inline function is in the main file,
168  // and probably won't be included anywhere else.
169  // (2) the thing we're referencing is a pure function.
170  // (3) the thing we're referencing is another inline function.
171  // This last can give us false negatives, but it's better than warning on
172  // wrappers for simple C library functions.
173  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
174  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
175  if (!DowngradeWarning && UsedFn)
176  DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
177 
178  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
179  : diag::ext_internal_in_extern_inline)
180  << /*IsVar=*/!UsedFn << D;
181 
183 
184  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
185  << D;
186 }
187 
189  const FunctionDecl *First = Cur->getFirstDecl();
190 
191  // Suggest "static" on the function, if possible.
192  if (!hasAnyExplicitStorageClass(First)) {
193  SourceLocation DeclBegin = First->getSourceRange().getBegin();
194  Diag(DeclBegin, diag::note_convert_inline_to_static)
195  << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
196  }
197 }
198 
199 /// Determine whether the use of this declaration is valid, and
200 /// emit any corresponding diagnostics.
201 ///
202 /// This routine diagnoses various problems with referencing
203 /// declarations that can occur when using a declaration. For example,
204 /// it might warn if a deprecated or unavailable declaration is being
205 /// used, or produce an error (and return true) if a C++0x deleted
206 /// function is being used.
207 ///
208 /// \returns true if there was an error (this declaration cannot be
209 /// referenced), false otherwise.
210 ///
212  const ObjCInterfaceDecl *UnknownObjCClass,
213  bool ObjCPropertyAccess,
214  bool AvoidPartialAvailabilityChecks,
215  ObjCInterfaceDecl *ClassReceiver) {
216  SourceLocation Loc = Locs.front();
217  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
218  // If there were any diagnostics suppressed by template argument deduction,
219  // emit them now.
220  auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
221  if (Pos != SuppressedDiagnostics.end()) {
222  for (const PartialDiagnosticAt &Suppressed : Pos->second)
223  Diag(Suppressed.first, Suppressed.second);
224 
225  // Clear out the list of suppressed diagnostics, so that we don't emit
226  // them again for this specialization. However, we don't obsolete this
227  // entry from the table, because we want to avoid ever emitting these
228  // diagnostics again.
229  Pos->second.clear();
230  }
231 
232  // C++ [basic.start.main]p3:
233  // The function 'main' shall not be used within a program.
234  if (cast<FunctionDecl>(D)->isMain())
235  Diag(Loc, diag::ext_main_used);
236 
237  diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
238  }
239 
240  // See if this is an auto-typed variable whose initializer we are parsing.
241  if (ParsingInitForAutoVars.count(D)) {
242  if (isa<BindingDecl>(D)) {
243  Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
244  << D->getDeclName();
245  } else {
246  Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
247  << D->getDeclName() << cast<VarDecl>(D)->getType();
248  }
249  return true;
250  }
251 
252  // See if this is a deleted function.
253  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
254  if (FD->isDeleted()) {
255  auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
256  if (Ctor && Ctor->isInheritingConstructor())
257  Diag(Loc, diag::err_deleted_inherited_ctor_use)
258  << Ctor->getParent()
259  << Ctor->getInheritedConstructor().getConstructor()->getParent();
260  else
261  Diag(Loc, diag::err_deleted_function_use);
262  NoteDeletedFunction(FD);
263  return true;
264  }
265 
266  // If the function has a deduced return type, and we can't deduce it,
267  // then we can't use it either.
268  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
269  DeduceReturnType(FD, Loc))
270  return true;
271 
272  if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
273  return true;
274  }
275 
276  if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
277  // Lambdas are only default-constructible or assignable in C++2a onwards.
278  if (MD->getParent()->isLambda() &&
279  ((isa<CXXConstructorDecl>(MD) &&
280  cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
281  MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
282  Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
283  << !isa<CXXConstructorDecl>(MD);
284  }
285  }
286 
287  auto getReferencedObjCProp = [](const NamedDecl *D) ->
288  const ObjCPropertyDecl * {
289  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
290  return MD->findPropertyDecl();
291  return nullptr;
292  };
293  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
294  if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
295  return true;
296  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
297  return true;
298  }
299 
300  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
301  // Only the variables omp_in and omp_out are allowed in the combiner.
302  // Only the variables omp_priv and omp_orig are allowed in the
303  // initializer-clause.
304  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
305  if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
306  isa<VarDecl>(D)) {
307  Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
308  << getCurFunction()->HasOMPDeclareReductionCombiner;
309  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
310  return true;
311  }
312 
313  // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
314  // List-items in map clauses on this construct may only refer to the declared
315  // variable var and entities that could be referenced by a procedure defined
316  // at the same location
317  auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
318  if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
319  isa<VarDecl>(D)) {
320  Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
321  << DMD->getVarName().getAsString();
322  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
323  return true;
324  }
325 
326  DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
327  AvoidPartialAvailabilityChecks, ClassReceiver);
328 
329  DiagnoseUnusedOfDecl(*this, D, Loc);
330 
332 
333  return false;
334 }
335 
336 /// DiagnoseSentinelCalls - This routine checks whether a call or
337 /// message-send is to a declaration with the sentinel attribute, and
338 /// if so, it checks that the requirements of the sentinel are
339 /// satisfied.
341  ArrayRef<Expr *> Args) {
342  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
343  if (!attr)
344  return;
345 
346  // The number of formal parameters of the declaration.
347  unsigned numFormalParams;
348 
349  // The kind of declaration. This is also an index into a %select in
350  // the diagnostic.
351  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
352 
353  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
354  numFormalParams = MD->param_size();
355  calleeType = CT_Method;
356  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
357  numFormalParams = FD->param_size();
358  calleeType = CT_Function;
359  } else if (isa<VarDecl>(D)) {
360  QualType type = cast<ValueDecl>(D)->getType();
361  const FunctionType *fn = nullptr;
362  if (const PointerType *ptr = type->getAs<PointerType>()) {
363  fn = ptr->getPointeeType()->getAs<FunctionType>();
364  if (!fn) return;
365  calleeType = CT_Function;
366  } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
367  fn = ptr->getPointeeType()->castAs<FunctionType>();
368  calleeType = CT_Block;
369  } else {
370  return;
371  }
372 
373  if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
374  numFormalParams = proto->getNumParams();
375  } else {
376  numFormalParams = 0;
377  }
378  } else {
379  return;
380  }
381 
382  // "nullPos" is the number of formal parameters at the end which
383  // effectively count as part of the variadic arguments. This is
384  // useful if you would prefer to not have *any* formal parameters,
385  // but the language forces you to have at least one.
386  unsigned nullPos = attr->getNullPos();
387  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
388  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
389 
390  // The number of arguments which should follow the sentinel.
391  unsigned numArgsAfterSentinel = attr->getSentinel();
392 
393  // If there aren't enough arguments for all the formal parameters,
394  // the sentinel, and the args after the sentinel, complain.
395  if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
396  Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
397  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
398  return;
399  }
400 
401  // Otherwise, find the sentinel expression.
402  Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
403  if (!sentinelExpr) return;
404  if (sentinelExpr->isValueDependent()) return;
405  if (Context.isSentinelNullExpr(sentinelExpr)) return;
406 
407  // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
408  // or 'NULL' if those are actually defined in the context. Only use
409  // 'nil' for ObjC methods, where it's much more likely that the
410  // variadic arguments form a list of object pointers.
411  SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
412  std::string NullValue;
413  if (calleeType == CT_Method && PP.isMacroDefined("nil"))
414  NullValue = "nil";
415  else if (getLangOpts().CPlusPlus11)
416  NullValue = "nullptr";
417  else if (PP.isMacroDefined("NULL"))
418  NullValue = "NULL";
419  else
420  NullValue = "(void*) 0";
421 
422  if (MissingNilLoc.isInvalid())
423  Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
424  else
425  Diag(MissingNilLoc, diag::warn_missing_sentinel)
426  << int(calleeType)
427  << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
428  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
429 }
430 
432  return E ? E->getSourceRange() : SourceRange();
433 }
434 
435 //===----------------------------------------------------------------------===//
436 // Standard Promotions and Conversions
437 //===----------------------------------------------------------------------===//
438 
439 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
441  // Handle any placeholder expressions which made it here.
442  if (E->getType()->isPlaceholderType()) {
443  ExprResult result = CheckPlaceholderExpr(E);
444  if (result.isInvalid()) return ExprError();
445  E = result.get();
446  }
447 
448  QualType Ty = E->getType();
449  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
450 
451  if (Ty->isFunctionType()) {
452  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
453  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
454  if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
455  return ExprError();
456 
457  E = ImpCastExprToType(E, Context.getPointerType(Ty),
458  CK_FunctionToPointerDecay).get();
459  } else if (Ty->isArrayType()) {
460  // In C90 mode, arrays only promote to pointers if the array expression is
461  // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
462  // type 'array of type' is converted to an expression that has type 'pointer
463  // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
464  // that has type 'array of type' ...". The relevant change is "an lvalue"
465  // (C90) to "an expression" (C99).
466  //
467  // C++ 4.2p1:
468  // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
469  // T" can be converted to an rvalue of type "pointer to T".
470  //
471  if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
472  E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
473  CK_ArrayToPointerDecay).get();
474  }
475  return E;
476 }
477 
479  // Check to see if we are dereferencing a null pointer. If so,
480  // and if not volatile-qualified, this is undefined behavior that the
481  // optimizer will delete, so warn about it. People sometimes try to use this
482  // to get a deterministic trap and are surprised by clang's behavior. This
483  // only handles the pattern "*null", which is a very syntactic check.
484  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
485  if (UO->getOpcode() == UO_Deref &&
486  UO->getSubExpr()->IgnoreParenCasts()->
487  isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
488  !UO->getType().isVolatileQualified()) {
489  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
490  S.PDiag(diag::warn_indirection_through_null)
491  << UO->getSubExpr()->getSourceRange());
492  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
493  S.PDiag(diag::note_indirection_through_null));
494  }
495 }
496 
497 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
498  SourceLocation AssignLoc,
499  const Expr* RHS) {
500  const ObjCIvarDecl *IV = OIRE->getDecl();
501  if (!IV)
502  return;
503 
504  DeclarationName MemberName = IV->getDeclName();
505  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
506  if (!Member || !Member->isStr("isa"))
507  return;
508 
509  const Expr *Base = OIRE->getBase();
510  QualType BaseType = Base->getType();
511  if (OIRE->isArrow())
512  BaseType = BaseType->getPointeeType();
513  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
514  if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
515  ObjCInterfaceDecl *ClassDeclared = nullptr;
516  ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
517  if (!ClassDeclared->getSuperClass()
518  && (*ClassDeclared->ivar_begin()) == IV) {
519  if (RHS) {
520  NamedDecl *ObjectSetClass =
522  &S.Context.Idents.get("object_setClass"),
524  if (ObjectSetClass) {
525  SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
526  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
528  "object_setClass(")
530  SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
531  << FixItHint::CreateInsertion(RHSLocEnd, ")");
532  }
533  else
534  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
535  } else {
536  NamedDecl *ObjectGetClass =
538  &S.Context.Idents.get("object_getClass"),
540  if (ObjectGetClass)
541  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
543  "object_getClass(")
545  SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
546  else
547  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
548  }
549  S.Diag(IV->getLocation(), diag::note_ivar_decl);
550  }
551  }
552 }
553 
555  // Handle any placeholder expressions which made it here.
556  if (E->getType()->isPlaceholderType()) {
557  ExprResult result = CheckPlaceholderExpr(E);
558  if (result.isInvalid()) return ExprError();
559  E = result.get();
560  }
561 
562  // C++ [conv.lval]p1:
563  // A glvalue of a non-function, non-array type T can be
564  // converted to a prvalue.
565  if (!E->isGLValue()) return E;
566 
567  QualType T = E->getType();
568  assert(!T.isNull() && "r-value conversion on typeless expression?");
569 
570  // We don't want to throw lvalue-to-rvalue casts on top of
571  // expressions of certain types in C++.
572  if (getLangOpts().CPlusPlus &&
573  (E->getType() == Context.OverloadTy ||
574  T->isDependentType() ||
575  T->isRecordType()))
576  return E;
577 
578  // The C standard is actually really unclear on this point, and
579  // DR106 tells us what the result should be but not why. It's
580  // generally best to say that void types just doesn't undergo
581  // lvalue-to-rvalue at all. Note that expressions of unqualified
582  // 'void' type are never l-values, but qualified void can be.
583  if (T->isVoidType())
584  return E;
585 
586  // OpenCL usually rejects direct accesses to values of 'half' type.
587  if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
588  T->isHalfType()) {
589  Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
590  << 0 << T;
591  return ExprError();
592  }
593 
595  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
596  NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
597  &Context.Idents.get("object_getClass"),
598  SourceLocation(), LookupOrdinaryName);
599  if (ObjectGetClass)
600  Diag(E->getExprLoc(), diag::warn_objc_isa_use)
601  << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
603  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
604  else
605  Diag(E->getExprLoc(), diag::warn_objc_isa_use);
606  }
607  else if (const ObjCIvarRefExpr *OIRE =
608  dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
609  DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
610 
611  // C++ [conv.lval]p1:
612  // [...] If T is a non-class type, the type of the prvalue is the
613  // cv-unqualified version of T. Otherwise, the type of the
614  // rvalue is T.
615  //
616  // C99 6.3.2.1p2:
617  // If the lvalue has qualified type, the value has the unqualified
618  // version of the type of the lvalue; otherwise, the value has the
619  // type of the lvalue.
620  if (T.hasQualifiers())
621  T = T.getUnqualifiedType();
622 
623  // Under the MS ABI, lock down the inheritance model now.
624  if (T->isMemberPointerType() &&
625  Context.getTargetInfo().getCXXABI().isMicrosoft())
626  (void)isCompleteType(E->getExprLoc(), T);
627 
628  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  // In Microsoft mode, if we are performing lookup from within a friend
1994  // function definition declared at class scope then we must set
1995  // DC to the lexical parent to be able to search into the parent
1996  // class.
1997  if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1998  cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1999  DC->getLexicalParent()->isRecord())
2000  DC = DC->getLexicalParent();
2001  else
2002  DC = DC->getParent();
2003  }
2004 
2005  // We didn't find anything, so try to correct for a typo.
2006  TypoCorrection Corrected;
2007  if (S && Out) {
2008  SourceLocation TypoLoc = R.getNameLoc();
2009  assert(!ExplicitTemplateArgs &&
2010  "Diagnosing an empty lookup with explicit template args!");
2011  *Out = CorrectTypoDelayed(
2012  R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2013  [=](const TypoCorrection &TC) {
2014  emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2015  diagnostic, diagnostic_suggest);
2016  },
2017  nullptr, CTK_ErrorRecovery);
2018  if (*Out)
2019  return true;
2020  } else if (S &&
2021  (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2022  S, &SS, CCC, CTK_ErrorRecovery))) {
2023  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2024  bool DroppedSpecifier =
2025  Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2026  R.setLookupName(Corrected.getCorrection());
2027 
2028  bool AcceptableWithRecovery = false;
2029  bool AcceptableWithoutRecovery = false;
2030  NamedDecl *ND = Corrected.getFoundDecl();
2031  if (ND) {
2032  if (Corrected.isOverloaded()) {
2036  for (NamedDecl *CD : Corrected) {
2037  if (FunctionTemplateDecl *FTD =
2038  dyn_cast<FunctionTemplateDecl>(CD))
2039  AddTemplateOverloadCandidate(
2040  FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2041  Args, OCS);
2042  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2043  if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2044  AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2045  Args, OCS);
2046  }
2047  switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2048  case OR_Success:
2049  ND = Best->FoundDecl;
2050  Corrected.setCorrectionDecl(ND);
2051  break;
2052  default:
2053  // FIXME: Arbitrarily pick the first declaration for the note.
2054  Corrected.setCorrectionDecl(ND);
2055  break;
2056  }
2057  }
2058  R.addDecl(ND);
2059  if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2060  CXXRecordDecl *Record = nullptr;
2061  if (Corrected.getCorrectionSpecifier()) {
2062  const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2063  Record = Ty->getAsCXXRecordDecl();
2064  }
2065  if (!Record)
2066  Record = cast<CXXRecordDecl>(
2067  ND->getDeclContext()->getRedeclContext());
2068  R.setNamingClass(Record);
2069  }
2070 
2071  auto *UnderlyingND = ND->getUnderlyingDecl();
2072  AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2073  isa<FunctionTemplateDecl>(UnderlyingND);
2074  // FIXME: If we ended up with a typo for a type name or
2075  // Objective-C class name, we're in trouble because the parser
2076  // is in the wrong place to recover. Suggest the typo
2077  // correction, but don't make it a fix-it since we're not going
2078  // to recover well anyway.
2079  AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2080  getAsTypeTemplateDecl(UnderlyingND) ||
2081  isa<ObjCInterfaceDecl>(UnderlyingND);
2082  } else {
2083  // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2084  // because we aren't able to recover.
2085  AcceptableWithoutRecovery = true;
2086  }
2087 
2088  if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2089  unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2090  ? diag::note_implicit_param_decl
2091  : diag::note_previous_decl;
2092  if (SS.isEmpty())
2093  diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2094  PDiag(NoteID), AcceptableWithRecovery);
2095  else
2096  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2097  << Name << computeDeclContext(SS, false)
2098  << DroppedSpecifier << SS.getRange(),
2099  PDiag(NoteID), AcceptableWithRecovery);
2100 
2101  // Tell the callee whether to try to recover.
2102  return !AcceptableWithRecovery;
2103  }
2104  }
2105  R.clear();
2106 
2107  // Emit a special diagnostic for failed member lookups.
2108  // FIXME: computing the declaration context might fail here (?)
2109  if (!SS.isEmpty()) {
2110  Diag(R.getNameLoc(), diag::err_no_member)
2111  << Name << computeDeclContext(SS, false)
2112  << SS.getRange();
2113  return true;
2114  }
2115 
2116  // Give up, we can't recover.
2117  Diag(R.getNameLoc(), diagnostic) << Name;
2118  return true;
2119 }
2120 
2121 /// In Microsoft mode, if we are inside a template class whose parent class has
2122 /// dependent base classes, and we can't resolve an unqualified identifier, then
2123 /// assume the identifier is a member of a dependent base class. We can only
2124 /// recover successfully in static methods, instance methods, and other contexts
2125 /// where 'this' is available. This doesn't precisely match MSVC's
2126 /// instantiation model, but it's close enough.
2127 static Expr *
2129  DeclarationNameInfo &NameInfo,
2130  SourceLocation TemplateKWLoc,
2131  const TemplateArgumentListInfo *TemplateArgs) {
2132  // Only try to recover from lookup into dependent bases in static methods or
2133  // contexts where 'this' is available.
2134  QualType ThisType = S.getCurrentThisType();
2135  const CXXRecordDecl *RD = nullptr;
2136  if (!ThisType.isNull())
2137  RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2138  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2139  RD = MD->getParent();
2140  if (!RD || !RD->hasAnyDependentBases())
2141  return nullptr;
2142 
2143  // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2144  // is available, suggest inserting 'this->' as a fixit.
2145  SourceLocation Loc = NameInfo.getLoc();
2146  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2147  DB << NameInfo.getName() << RD;
2148 
2149  if (!ThisType.isNull()) {
2150  DB << FixItHint::CreateInsertion(Loc, "this->");
2152  Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2153  /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2154  /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2155  }
2156 
2157  // Synthesize a fake NNS that points to the derived class. This will
2158  // perform name lookup during template instantiation.
2159  CXXScopeSpec SS;
2160  auto *NNS =
2161  NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2162  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2164  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2165  TemplateArgs);
2166 }
2167 
2168 ExprResult
2170  SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2171  bool HasTrailingLParen, bool IsAddressOfOperand,
2173  bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2174  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2175  "cannot be direct & operand and have a trailing lparen");
2176  if (SS.isInvalid())
2177  return ExprError();
2178 
2179  TemplateArgumentListInfo TemplateArgsBuffer;
2180 
2181  // Decompose the UnqualifiedId into the following data.
2182  DeclarationNameInfo NameInfo;
2183  const TemplateArgumentListInfo *TemplateArgs;
2184  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2185 
2186  DeclarationName Name = NameInfo.getName();
2187  IdentifierInfo *II = Name.getAsIdentifierInfo();
2188  SourceLocation NameLoc = NameInfo.getLoc();
2189 
2190  if (II && II->isEditorPlaceholder()) {
2191  // FIXME: When typed placeholders are supported we can create a typed
2192  // placeholder expression node.
2193  return ExprError();
2194  }
2195 
2196  // C++ [temp.dep.expr]p3:
2197  // An id-expression is type-dependent if it contains:
2198  // -- an identifier that was declared with a dependent type,
2199  // (note: handled after lookup)
2200  // -- a template-id that is dependent,
2201  // (note: handled in BuildTemplateIdExpr)
2202  // -- a conversion-function-id that specifies a dependent type,
2203  // -- a nested-name-specifier that contains a class-name that
2204  // names a dependent type.
2205  // Determine whether this is a member of an unknown specialization;
2206  // we need to handle these differently.
2207  bool DependentID = false;
2209  Name.getCXXNameType()->isDependentType()) {
2210  DependentID = true;
2211  } else if (SS.isSet()) {
2212  if (DeclContext *DC = computeDeclContext(SS, false)) {
2213  if (RequireCompleteDeclContext(SS, DC))
2214  return ExprError();
2215  } else {
2216  DependentID = true;
2217  }
2218  }
2219 
2220  if (DependentID)
2221  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2222  IsAddressOfOperand, TemplateArgs);
2223 
2224  // Perform the required lookup.
2225  LookupResult R(*this, NameInfo,
2227  ? LookupObjCImplicitSelfParam
2228  : LookupOrdinaryName);
2229  if (TemplateKWLoc.isValid() || TemplateArgs) {
2230  // Lookup the template name again to correctly establish the context in
2231  // which it was found. This is really unfortunate as we already did the
2232  // lookup to determine that it was a template name in the first place. If
2233  // this becomes a performance hit, we can work harder to preserve those
2234  // results until we get here but it's likely not worth it.
2235  bool MemberOfUnknownSpecialization;
2236  AssumedTemplateKind AssumedTemplate;
2237  if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2238  MemberOfUnknownSpecialization, TemplateKWLoc,
2239  &AssumedTemplate))
2240  return ExprError();
2241 
2242  if (MemberOfUnknownSpecialization ||
2244  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2245  IsAddressOfOperand, TemplateArgs);
2246  } else {
2247  bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2248  LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2249 
2250  // If the result might be in a dependent base class, this is a dependent
2251  // id-expression.
2253  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2254  IsAddressOfOperand, TemplateArgs);
2255 
2256  // If this reference is in an Objective-C method, then we need to do
2257  // some special Objective-C lookup, too.
2258  if (IvarLookupFollowUp) {
2259  ExprResult E(LookupInObjCMethod(R, S, II, true));
2260  if (E.isInvalid())
2261  return ExprError();
2262 
2263  if (Expr *Ex = E.getAs<Expr>())
2264  return Ex;
2265  }
2266  }
2267 
2268  if (R.isAmbiguous())
2269  return ExprError();
2270 
2271  // This could be an implicitly declared function reference (legal in C90,
2272  // extension in C99, forbidden in C++).
2273  if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2274  NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2275  if (D) R.addDecl(D);
2276  }
2277 
2278  // Determine whether this name might be a candidate for
2279  // argument-dependent lookup.
2280  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2281 
2282  if (R.empty() && !ADL) {
2283  if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2284  if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2285  TemplateKWLoc, TemplateArgs))
2286  return E;
2287  }
2288 
2289  // Don't diagnose an empty lookup for inline assembly.
2290  if (IsInlineAsmIdentifier)
2291  return ExprError();
2292 
2293  // If this name wasn't predeclared and if this is not a function
2294  // call, diagnose the problem.
2295  TypoExpr *TE = nullptr;
2296  DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2297  : nullptr);
2298  DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2299  assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2300  "Typo correction callback misconfigured");
2301  if (CCC) {
2302  // Make sure the callback knows what the typo being diagnosed is.
2303  CCC->setTypoName(II);
2304  if (SS.isValid())
2305  CCC->setTypoNNS(SS.getScopeRep());
2306  }
2307  // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2308  // a template name, but we happen to have always already looked up the name
2309  // before we get here if it must be a template name.
2310  if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2311  None, &TE)) {
2312  if (TE && KeywordReplacement) {
2313  auto &State = getTypoExprState(TE);
2314  auto BestTC = State.Consumer->getNextCorrection();
2315  if (BestTC.isKeyword()) {
2316  auto *II = BestTC.getCorrectionAsIdentifierInfo();
2317  if (State.DiagHandler)
2318  State.DiagHandler(BestTC);
2319  KeywordReplacement->startToken();
2320  KeywordReplacement->setKind(II->getTokenID());
2321  KeywordReplacement->setIdentifierInfo(II);
2322  KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2323  // Clean up the state associated with the TypoExpr, since it has
2324  // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2325  clearDelayedTypo(TE);
2326  // Signal that a correction to a keyword was performed by returning a
2327  // valid-but-null ExprResult.
2328  return (Expr*)nullptr;
2329  }
2330  State.Consumer->resetCorrectionStream();
2331  }
2332  return TE ? TE : ExprError();
2333  }
2334 
2335  assert(!R.empty() &&
2336  "DiagnoseEmptyLookup returned false but added no results");
2337 
2338  // If we found an Objective-C instance variable, let
2339  // LookupInObjCMethod build the appropriate expression to
2340  // reference the ivar.
2341  if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2342  R.clear();
2343  ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2344  // In a hopelessly buggy code, Objective-C instance variable
2345  // lookup fails and no expression will be built to reference it.
2346  if (!E.isInvalid() && !E.get())
2347  return ExprError();
2348  return E;
2349  }
2350  }
2351 
2352  // This is guaranteed from this point on.
2353  assert(!R.empty() || ADL);
2354 
2355  // Check whether this might be a C++ implicit instance member access.
2356  // C++ [class.mfct.non-static]p3:
2357  // When an id-expression that is not part of a class member access
2358  // syntax and not used to form a pointer to member is used in the
2359  // body of a non-static member function of class X, if name lookup
2360  // resolves the name in the id-expression to a non-static non-type
2361  // member of some class C, the id-expression is transformed into a
2362  // class member access expression using (*this) as the
2363  // postfix-expression to the left of the . operator.
2364  //
2365  // But we don't actually need to do this for '&' operands if R
2366  // resolved to a function or overloaded function set, because the
2367  // expression is ill-formed if it actually works out to be a
2368  // non-static member function:
2369  //
2370  // C++ [expr.ref]p4:
2371  // Otherwise, if E1.E2 refers to a non-static member function. . .
2372  // [t]he expression can be used only as the left-hand operand of a
2373  // member function call.
2374  //
2375  // There are other safeguards against such uses, but it's important
2376  // to get this right here so that we don't end up making a
2377  // spuriously dependent expression if we're inside a dependent
2378  // instance method.
2379  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2380  bool MightBeImplicitMember;
2381  if (!IsAddressOfOperand)
2382  MightBeImplicitMember = true;
2383  else if (!SS.isEmpty())
2384  MightBeImplicitMember = false;
2385  else if (R.isOverloadedResult())
2386  MightBeImplicitMember = false;
2387  else if (R.isUnresolvableResult())
2388  MightBeImplicitMember = true;
2389  else
2390  MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2391  isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2392  isa<MSPropertyDecl>(R.getFoundDecl());
2393 
2394  if (MightBeImplicitMember)
2395  return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2396  R, TemplateArgs, S);
2397  }
2398 
2399  if (TemplateArgs || TemplateKWLoc.isValid()) {
2400 
2401  // In C++1y, if this is a variable template id, then check it
2402  // in BuildTemplateIdExpr().
2403  // The single lookup result must be a variable template declaration.
2405  Id.TemplateId->Kind == TNK_Var_template) {
2406  assert(R.getAsSingle<VarTemplateDecl>() &&
2407  "There should only be one declaration found.");
2408  }
2409 
2410  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2411  }
2412 
2413  return BuildDeclarationNameExpr(SS, R, ADL);
2414 }
2415 
2416 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2417 /// declaration name, generally during template instantiation.
2418 /// There's a large number of things which don't need to be done along
2419 /// this path.
2421  CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2422  bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2423  DeclContext *DC = computeDeclContext(SS, false);
2424  if (!DC)
2425  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2426  NameInfo, /*TemplateArgs=*/nullptr);
2427 
2428  if (RequireCompleteDeclContext(SS, DC))
2429  return ExprError();
2430 
2431  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2432  LookupQualifiedName(R, DC);
2433 
2434  if (R.isAmbiguous())
2435  return ExprError();
2436 
2438  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2439  NameInfo, /*TemplateArgs=*/nullptr);
2440 
2441  if (R.empty()) {
2442  Diag(NameInfo.getLoc(), diag::err_no_member)
2443  << NameInfo.getName() << DC << SS.getRange();
2444  return ExprError();
2445  }
2446 
2447  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2448  // Diagnose a missing typename if this resolved unambiguously to a type in
2449  // a dependent context. If we can recover with a type, downgrade this to
2450  // a warning in Microsoft compatibility mode.
2451  unsigned DiagID = diag::err_typename_missing;
2452  if (RecoveryTSI && getLangOpts().MSVCCompat)
2453  DiagID = diag::ext_typename_missing;
2454  SourceLocation Loc = SS.getBeginLoc();
2455  auto D = Diag(Loc, DiagID);
2456  D << SS.getScopeRep() << NameInfo.getName().getAsString()
2457  << SourceRange(Loc, NameInfo.getEndLoc());
2458 
2459  // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2460  // context.
2461  if (!RecoveryTSI)
2462  return ExprError();
2463 
2464  // Only issue the fixit if we're prepared to recover.
2465  D << FixItHint::CreateInsertion(Loc, "typename ");
2466 
2467  // Recover by pretending this was an elaborated type.
2468  QualType Ty = Context.getTypeDeclType(TD);
2469  TypeLocBuilder TLB;
2470  TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2471 
2472  QualType ET = getElaboratedType(ETK_None, SS, Ty);
2473  ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2475  QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2476 
2477  *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2478 
2479  return ExprEmpty();
2480  }
2481 
2482  // Defend against this resolving to an implicit member access. We usually
2483  // won't get here if this might be a legitimate a class member (we end up in
2484  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2485  // a pointer-to-member or in an unevaluated context in C++11.
2486  if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2487  return BuildPossibleImplicitMemberExpr(SS,
2488  /*TemplateKWLoc=*/SourceLocation(),
2489  R, /*TemplateArgs=*/nullptr, S);
2490 
2491  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2492 }
2493 
2494 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2495 /// detected that we're currently inside an ObjC method. Perform some
2496 /// additional lookup.
2497 ///
2498 /// Ideally, most of this would be done by lookup, but there's
2499 /// actually quite a lot of extra work involved.
2500 ///
2501 /// Returns a null sentinel to indicate trivial success.
2502 ExprResult
2504  IdentifierInfo *II, bool AllowBuiltinCreation) {
2505  SourceLocation Loc = Lookup.getNameLoc();
2506  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2507 
2508  // Check for error condition which is already reported.
2509  if (!CurMethod)
2510  return ExprError();
2511 
2512  // There are two cases to handle here. 1) scoped lookup could have failed,
2513  // in which case we should look for an ivar. 2) scoped lookup could have
2514  // found a decl, but that decl is outside the current instance method (i.e.
2515  // a global variable). In these two cases, we do a lookup for an ivar with
2516  // this name, if the lookup sucedes, we replace it our current decl.
2517 
2518  // If we're in a class method, we don't normally want to look for
2519  // ivars. But if we don't find anything else, and there's an
2520  // ivar, that's an error.
2521  bool IsClassMethod = CurMethod->isClassMethod();
2522 
2523  bool LookForIvars;
2524  if (Lookup.empty())
2525  LookForIvars = true;
2526  else if (IsClassMethod)
2527  LookForIvars = false;
2528  else
2529  LookForIvars = (Lookup.isSingleResult() &&
2531  ObjCInterfaceDecl *IFace = nullptr;
2532  if (LookForIvars) {
2533  IFace = CurMethod->getClassInterface();
2534  ObjCInterfaceDecl *ClassDeclared;
2535  ObjCIvarDecl *IV = nullptr;
2536  if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2537  // Diagnose using an ivar in a class method.
2538  if (IsClassMethod)
2539  return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2540  << IV->getDeclName());
2541 
2542  // If we're referencing an invalid decl, just return this as a silent
2543  // error node. The error diagnostic was already emitted on the decl.
2544  if (IV->isInvalidDecl())
2545  return ExprError();
2546 
2547  // Check if referencing a field with __attribute__((deprecated)).
2548  if (DiagnoseUseOfDecl(IV, Loc))
2549  return ExprError();
2550 
2551  // Diagnose the use of an ivar outside of the declaring class.
2552  if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2553  !declaresSameEntity(ClassDeclared, IFace) &&
2554  !getLangOpts().DebuggerSupport)
2555  Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2556 
2557  // FIXME: This should use a new expr for a direct reference, don't
2558  // turn this into Self->ivar, just return a BareIVarExpr or something.
2559  IdentifierInfo &II = Context.Idents.get("self");
2560  UnqualifiedId SelfName;
2561  SelfName.setIdentifier(&II, SourceLocation());
2563  CXXScopeSpec SelfScopeSpec;
2564  SourceLocation TemplateKWLoc;
2565  ExprResult SelfExpr =
2566  ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2567  /*HasTrailingLParen=*/false,
2568  /*IsAddressOfOperand=*/false);
2569  if (SelfExpr.isInvalid())
2570  return ExprError();
2571 
2572  SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2573  if (SelfExpr.isInvalid())
2574  return ExprError();
2575 
2576  MarkAnyDeclReferenced(Loc, IV, true);
2577 
2578  ObjCMethodFamily MF = CurMethod->getMethodFamily();
2579  if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2580  !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2581  Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2582 
2583  ObjCIvarRefExpr *Result = new (Context)
2584  ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2585  IV->getLocation(), SelfExpr.get(), true, true);
2586 
2587  if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2588  if (!isUnevaluatedContext() &&
2589  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2590  getCurFunction()->recordUseOfWeak(Result);
2591  }
2592  if (getLangOpts().ObjCAutoRefCount)
2593  if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2594  ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2595 
2596  return Result;
2597  }
2598  } else if (CurMethod->isInstanceMethod()) {
2599  // We should warn if a local variable hides an ivar.
2600  if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2601  ObjCInterfaceDecl *ClassDeclared;
2602  if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2603  if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2604  declaresSameEntity(IFace, ClassDeclared))
2605  Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2606  }
2607  }
2608  } else if (Lookup.isSingleResult() &&
2610  // If accessing a stand-alone ivar in a class method, this is an error.
2611  if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2612  return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2613  << IV->getDeclName());
2614  }
2615 
2616  if (Lookup.empty() && II && AllowBuiltinCreation) {
2617  // FIXME. Consolidate this with similar code in LookupName.
2618  if (unsigned BuiltinID = II->getBuiltinID()) {
2619  if (!(getLangOpts().CPlusPlus &&
2620  Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2621  NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2622  S, Lookup.isForRedeclaration(),
2623  Lookup.getNameLoc());
2624  if (D) Lookup.addDecl(D);
2625  }
2626  }
2627  }
2628  // Sentinel value saying that we didn't do anything special.
2629  return ExprResult((Expr *)nullptr);
2630 }
2631 
2632 /// Cast a base object to a member's actual type.
2633 ///
2634 /// Logically this happens in three phases:
2635 ///
2636 /// * First we cast from the base type to the naming class.
2637 /// The naming class is the class into which we were looking
2638 /// when we found the member; it's the qualifier type if a
2639 /// qualifier was provided, and otherwise it's the base type.
2640 ///
2641 /// * Next we cast from the naming class to the declaring class.
2642 /// If the member we found was brought into a class's scope by
2643 /// a using declaration, this is that class; otherwise it's
2644 /// the class declaring the member.
2645 ///
2646 /// * Finally we cast from the declaring class to the "true"
2647 /// declaring class of the member. This conversion does not
2648 /// obey access control.
2649 ExprResult
2651  NestedNameSpecifier *Qualifier,
2652  NamedDecl *FoundDecl,
2653  NamedDecl *Member) {
2654  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2655  if (!RD)
2656  return From;
2657 
2658  QualType DestRecordType;
2659  QualType DestType;
2660  QualType FromRecordType;
2661  QualType FromType = From->getType();
2662  bool PointerConversions = false;
2663  if (isa<FieldDecl>(Member)) {
2664  DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2665  auto FromPtrType = FromType->getAs<PointerType>();
2666  DestRecordType = Context.getAddrSpaceQualType(
2667  DestRecordType, FromPtrType
2668  ? FromType->getPointeeType().getAddressSpace()
2669  : FromType.getAddressSpace());
2670 
2671  if (FromPtrType) {
2672  DestType = Context.getPointerType(DestRecordType);
2673  FromRecordType = FromPtrType->getPointeeType();
2674  PointerConversions = true;
2675  } else {
2676  DestType = DestRecordType;
2677  FromRecordType = FromType;
2678  }
2679  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2680  if (Method->isStatic())
2681  return From;
2682 
2683  DestType = Method->getThisType();
2684  DestRecordType = DestType->getPointeeType();
2685 
2686  if (FromType->getAs<PointerType>()) {
2687  FromRecordType = FromType->getPointeeType();
2688  PointerConversions = true;
2689  } else {
2690  FromRecordType = FromType;
2691  DestType = DestRecordType;
2692  }
2693  } else {
2694  // No conversion necessary.
2695  return From;
2696  }
2697 
2698  if (DestType->isDependentType() || FromType->isDependentType())
2699  return From;
2700 
2701  // If the unqualified types are the same, no conversion is necessary.
2702  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2703  return From;
2704 
2705  SourceRange FromRange = From->getSourceRange();
2706  SourceLocation FromLoc = FromRange.getBegin();
2707 
2708  ExprValueKind VK = From->getValueKind();
2709 
2710  // C++ [class.member.lookup]p8:
2711  // [...] Ambiguities can often be resolved by qualifying a name with its
2712  // class name.
2713  //
2714  // If the member was a qualified name and the qualified referred to a
2715  // specific base subobject type, we'll cast to that intermediate type
2716  // first and then to the object in which the member is declared. That allows
2717  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2718  //
2719  // class Base { public: int x; };
2720  // class Derived1 : public Base { };
2721  // class Derived2 : public Base { };
2722  // class VeryDerived : public Derived1, public Derived2 { void f(); };
2723  //
2724  // void VeryDerived::f() {
2725  // x = 17; // error: ambiguous base subobjects
2726  // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2727  // }
2728  if (Qualifier && Qualifier->getAsType()) {
2729  QualType QType = QualType(Qualifier->getAsType(), 0);
2730  assert(QType->isRecordType() && "lookup done with non-record type");
2731 
2732  QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2733 
2734  // In C++98, the qualifier type doesn't actually have to be a base
2735  // type of the object type, in which case we just ignore it.
2736  // Otherwise build the appropriate casts.
2737  if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2738  CXXCastPath BasePath;
2739  if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2740  FromLoc, FromRange, &BasePath))
2741  return ExprError();
2742 
2743  if (PointerConversions)
2744  QType = Context.getPointerType(QType);
2745  From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2746  VK, &BasePath).get();
2747 
2748  FromType = QType;
2749  FromRecordType = QRecordType;
2750 
2751  // If the qualifier type was the same as the destination type,
2752  // we're done.
2753  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2754  return From;
2755  }
2756  }
2757 
2758  bool IgnoreAccess = false;
2759 
2760  // If we actually found the member through a using declaration, cast
2761  // down to the using declaration's type.
2762  //
2763  // Pointer equality is fine here because only one declaration of a
2764  // class ever has member declarations.
2765  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2766  assert(isa<UsingShadowDecl>(FoundDecl));
2767  QualType URecordType = Context.getTypeDeclType(
2768  cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2769 
2770  // We only need to do this if the naming-class to declaring-class
2771  // conversion is non-trivial.
2772  if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2773  assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2774  CXXCastPath BasePath;
2775  if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2776  FromLoc, FromRange, &BasePath))
2777  return ExprError();
2778 
2779  QualType UType = URecordType;
2780  if (PointerConversions)
2781  UType = Context.getPointerType(UType);
2782  From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2783  VK, &BasePath).get();
2784  FromType = UType;
2785  FromRecordType = URecordType;
2786  }
2787 
2788  // We don't do access control for the conversion from the
2789  // declaring class to the true declaring class.
2790  IgnoreAccess = true;
2791  }
2792 
2793  CXXCastPath BasePath;
2794  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2795  FromLoc, FromRange, &BasePath,
2796  IgnoreAccess))
2797  return ExprError();
2798 
2799  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2800  VK, &BasePath);
2801 }
2802 
2804  const LookupResult &R,
2805  bool HasTrailingLParen) {
2806  // Only when used directly as the postfix-expression of a call.
2807  if (!HasTrailingLParen)
2808  return false;
2809 
2810  // Never if a scope specifier was provided.
2811  if (SS.isSet())
2812  return false;
2813 
2814  // Only in C++ or ObjC++.
2815  if (!getLangOpts().CPlusPlus)
2816  return false;
2817 
2818  // Turn off ADL when we find certain kinds of declarations during
2819  // normal lookup:
2820  for (NamedDecl *D : R) {
2821  // C++0x [basic.lookup.argdep]p3:
2822  // -- a declaration of a class member
2823  // Since using decls preserve this property, we check this on the
2824  // original decl.
2825  if (D->isCXXClassMember())
2826  return false;
2827 
2828  // C++0x [basic.lookup.argdep]p3:
2829  // -- a block-scope function declaration that is not a
2830  // using-declaration
2831  // NOTE: we also trigger this for function templates (in fact, we
2832  // don't check the decl type at all, since all other decl types
2833  // turn off ADL anyway).
2834  if (isa<UsingShadowDecl>(D))
2835  D = cast<UsingShadowDecl>(D)->getTargetDecl();
2836  else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2837  return false;
2838 
2839  // C++0x [basic.lookup.argdep]p3:
2840  // -- a declaration that is neither a function or a function
2841  // template
2842  // And also for builtin functions.
2843  if (isa<FunctionDecl>(D)) {
2844  FunctionDecl *FDecl = cast<FunctionDecl>(D);
2845 
2846  // But also builtin functions.
2847  if (FDecl->getBuiltinID() && FDecl->isImplicit())
2848  return false;
2849  } else if (!isa<FunctionTemplateDecl>(D))
2850  return false;
2851  }
2852 
2853  return true;
2854 }
2855 
2856 
2857 /// Diagnoses obvious problems with the use of the given declaration
2858 /// as an expression. This is only actually called for lookups that
2859 /// were not overloaded, and it doesn't promise that the declaration
2860 /// will in fact be used.
2861 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2862  if (D->isInvalidDecl())
2863  return true;
2864 
2865  if (isa<TypedefNameDecl>(D)) {
2866  S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2867  return true;
2868  }
2869 
2870  if (isa<ObjCInterfaceDecl>(D)) {
2871  S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2872  return true;
2873  }
2874 
2875  if (isa<NamespaceDecl>(D)) {
2876  S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2877  return true;
2878  }
2879 
2880  return false;
2881 }
2882 
2883 // Certain multiversion types should be treated as overloaded even when there is
2884 // only one result.
2886  assert(R.isSingleResult() && "Expected only a single result");
2887  const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2888  return FD &&
2889  (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2890 }
2891 
2893  LookupResult &R, bool NeedsADL,
2894  bool AcceptInvalidDecl) {
2895  // If this is a single, fully-resolved result and we don't need ADL,
2896  // just build an ordinary singleton decl ref.
2897  if (!NeedsADL && R.isSingleResult() &&
2900  return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2901  R.getRepresentativeDecl(), nullptr,
2902  AcceptInvalidDecl);
2903 
2904  // We only need to check the declaration if there's exactly one
2905  // result, because in the overloaded case the results can only be
2906  // functions and function templates.
2908  CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2909  return ExprError();
2910 
2911  // Otherwise, just build an unresolved lookup expression. Suppress
2912  // any lookup-related diagnostics; we'll hash these out later, when
2913  // we've picked a target.
2914  R.suppressDiagnostics();
2915 
2918  SS.getWithLocInContext(Context),
2919  R.getLookupNameInfo(),
2920  NeedsADL, R.isOverloadedResult(),
2921  R.begin(), R.end());
2922 
2923  return ULE;
2924 }
2925 
2926 static void
2928  ValueDecl *var, DeclContext *DC);
2929 
2930 /// Complete semantic analysis for a reference to the given declaration.
2932  const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2933  NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2934  bool AcceptInvalidDecl) {
2935  assert(D && "Cannot refer to a NULL declaration");
2936  assert(!isa<FunctionTemplateDecl>(D) &&
2937  "Cannot refer unambiguously to a function template");
2938 
2939  SourceLocation Loc = NameInfo.getLoc();
2940  if (CheckDeclInExpr(*this, Loc, D))
2941  return ExprError();
2942 
2943  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2944  // Specifically diagnose references to class templates that are missing
2945  // a template argument list.
2946  diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2947  return ExprError();
2948  }
2949 
2950  // Make sure that we're referring to a value.
2951  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2952  if (!VD) {
2953  Diag(Loc, diag::err_ref_non_value)
2954  << D << SS.getRange();
2955  Diag(D->getLocation(), diag::note_declared_at);
2956  return ExprError();
2957  }
2958 
2959  // Check whether this declaration can be used. Note that we suppress
2960  // this check when we're going to perform argument-dependent lookup
2961  // on this function name, because this might not be the function
2962  // that overload resolution actually selects.
2963  if (DiagnoseUseOfDecl(VD, Loc))
2964  return ExprError();
2965 
2966  // Only create DeclRefExpr's for valid Decl's.
2967  if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2968  return ExprError();
2969 
2970  // Handle members of anonymous structs and unions. If we got here,
2971  // and the reference is to a class member indirect field, then this
2972  // must be the subject of a pointer-to-member expression.
2973  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2974  if (!indirectField->isCXXClassMember())
2975  return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2976  indirectField);
2977 
2978  {
2979  QualType type = VD->getType();
2980  if (type.isNull())
2981  return ExprError();
2982  if (auto *FPT = type->getAs<FunctionProtoType>()) {
2983  // C++ [except.spec]p17:
2984  // An exception-specification is considered to be needed when:
2985  // - in an expression, the function is the unique lookup result or
2986  // the selected member of a set of overloaded functions.
2987  ResolveExceptionSpec(Loc, FPT);
2988  type = VD->getType();
2989  }
2990  ExprValueKind valueKind = VK_RValue;
2991 
2992  switch (D->getKind()) {
2993  // Ignore all the non-ValueDecl kinds.
2994 #define ABSTRACT_DECL(kind)
2995 #define VALUE(type, base)
2996 #define DECL(type, base) \
2997  case Decl::type:
2998 #include "clang/AST/DeclNodes.inc"
2999  llvm_unreachable("invalid value decl kind");
3000 
3001  // These shouldn't make it here.
3002  case Decl::ObjCAtDefsField:
3003  llvm_unreachable("forming non-member reference to ivar?");
3004 
3005  // Enum constants are always r-values and never references.
3006  // Unresolved using declarations are dependent.
3007  case Decl::EnumConstant:
3008  case Decl::UnresolvedUsingValue:
3009  case Decl::OMPDeclareReduction:
3010  case Decl::OMPDeclareMapper:
3011  valueKind = VK_RValue;
3012  break;
3013 
3014  // Fields and indirect fields that got here must be for
3015  // pointer-to-member expressions; we just call them l-values for
3016  // internal consistency, because this subexpression doesn't really
3017  // exist in the high-level semantics.
3018  case Decl::Field:
3019  case Decl::IndirectField:
3020  case Decl::ObjCIvar:
3021  assert(getLangOpts().CPlusPlus &&
3022  "building reference to field in C?");
3023 
3024  // These can't have reference type in well-formed programs, but
3025  // for internal consistency we do this anyway.
3026  type = type.getNonReferenceType();
3027  valueKind = VK_LValue;
3028  break;
3029 
3030  // Non-type template parameters are either l-values or r-values
3031  // depending on the type.
3032  case Decl::NonTypeTemplateParm: {
3033  if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3034  type = reftype->getPointeeType();
3035  valueKind = VK_LValue; // even if the parameter is an r-value reference
3036  break;
3037  }
3038 
3039  // For non-references, we need to strip qualifiers just in case
3040  // the template parameter was declared as 'const int' or whatever.
3041  valueKind = VK_RValue;
3042  type = type.getUnqualifiedType();
3043  break;
3044  }
3045 
3046  case Decl::Var:
3047  case Decl::VarTemplateSpecialization:
3048  case Decl::VarTemplatePartialSpecialization:
3049  case Decl::Decomposition:
3050  case Decl::OMPCapturedExpr:
3051  // In C, "extern void blah;" is valid and is an r-value.
3052  if (!getLangOpts().CPlusPlus &&
3053  !type.hasQualifiers() &&
3054  type->isVoidType()) {
3055  valueKind = VK_RValue;
3056  break;
3057  }
3058  LLVM_FALLTHROUGH;
3059 
3060  case Decl::ImplicitParam:
3061  case Decl::ParmVar: {
3062  // These are always l-values.
3063  valueKind = VK_LValue;
3064  type = type.getNonReferenceType();
3065 
3066  // FIXME: Does the addition of const really only apply in
3067  // potentially-evaluated contexts? Since the variable isn't actually
3068  // captured in an unevaluated context, it seems that the answer is no.
3069  if (!isUnevaluatedContext()) {
3070  QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3071  if (!CapturedType.isNull())
3072  type = CapturedType;
3073  }
3074 
3075  break;
3076  }
3077 
3078  case Decl::Binding: {
3079  // These are always lvalues.
3080  valueKind = VK_LValue;
3081  type = type.getNonReferenceType();
3082  // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3083  // decides how that's supposed to work.
3084  auto *BD = cast<BindingDecl>(VD);
3085  if (BD->getDeclContext() != CurContext) {
3086  auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3087  if (DD && DD->hasLocalStorage())
3088  diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3089  }
3090  break;
3091  }
3092 
3093  case Decl::Function: {
3094  if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3095  if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3096  type = Context.BuiltinFnTy;
3097  valueKind = VK_RValue;
3098  break;
3099  }
3100  }
3101 
3102  const FunctionType *fty = type->castAs<FunctionType>();
3103 
3104  // If we're referring to a function with an __unknown_anytype
3105  // result type, make the entire expression __unknown_anytype.
3106  if (fty->getReturnType() == Context.UnknownAnyTy) {
3107  type = Context.UnknownAnyTy;
3108  valueKind = VK_RValue;
3109  break;
3110  }
3111 
3112  // Functions are l-values in C++.
3113  if (getLangOpts().CPlusPlus) {
3114  valueKind = VK_LValue;
3115  break;
3116  }
3117 
3118  // C99 DR 316 says that, if a function type comes from a
3119  // function definition (without a prototype), that type is only
3120  // used for checking compatibility. Therefore, when referencing
3121  // the function, we pretend that we don't have the full function
3122  // type.
3123  if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3124  isa<FunctionProtoType>(fty))
3125  type = Context.getFunctionNoProtoType(fty->getReturnType(),
3126  fty->getExtInfo());
3127 
3128  // Functions are r-values in C.
3129  valueKind = VK_RValue;
3130  break;
3131  }
3132 
3133  case Decl::CXXDeductionGuide:
3134  llvm_unreachable("building reference to deduction guide");
3135 
3136  case Decl::MSProperty:
3137  valueKind = VK_LValue;
3138  break;
3139 
3140  case Decl::CXXMethod:
3141  // If we're referring to a method with an __unknown_anytype
3142  // result type, make the entire expression __unknown_anytype.
3143  // This should only be possible with a type written directly.
3144  if (const FunctionProtoType *proto
3145  = dyn_cast<FunctionProtoType>(VD->getType()))
3146  if (proto->getReturnType() == Context.UnknownAnyTy) {
3147  type = Context.UnknownAnyTy;
3148  valueKind = VK_RValue;
3149  break;
3150  }
3151 
3152  // C++ methods are l-values if static, r-values if non-static.
3153  if (cast<CXXMethodDecl>(VD)->isStatic()) {
3154  valueKind = VK_LValue;
3155  break;
3156  }
3157  LLVM_FALLTHROUGH;
3158 
3159  case Decl::CXXConversion:
3160  case Decl::CXXDestructor:
3161  case Decl::CXXConstructor:
3162  valueKind = VK_RValue;
3163  break;
3164  }
3165 
3166  return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3167  /*FIXME: TemplateKWLoc*/ SourceLocation(),
3168  TemplateArgs);
3169  }
3170 }
3171 
3172 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3173  SmallString<32> &Target) {
3174  Target.resize(CharByteWidth * (Source.size() + 1));
3175  char *ResultPtr = &Target[0];
3176  const llvm::UTF8 *ErrorPtr;
3177  bool success =
3178  llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3179  (void)success;
3180  assert(success);
3181  Target.resize(ResultPtr - &Target[0]);
3182 }
3183 
3186  // Pick the current block, lambda, captured statement or function.
3187  Decl *currentDecl = nullptr;
3188  if (const BlockScopeInfo *BSI = getCurBlock())
3189  currentDecl = BSI->TheDecl;
3190  else if (const LambdaScopeInfo *LSI = getCurLambda())
3191  currentDecl = LSI->CallOperator;
3192  else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3193  currentDecl = CSI->TheCapturedDecl;
3194  else
3195  currentDecl = getCurFunctionOrMethodDecl();
3196 
3197  if (!currentDecl) {
3198  Diag(Loc, diag::ext_predef_outside_function);
3199  currentDecl = Context.getTranslationUnitDecl();
3200  }
3201 
3202  QualType ResTy;
3203  StringLiteral *SL = nullptr;
3204  if (cast<DeclContext>(currentDecl)->isDependentContext())
3205  ResTy = Context.DependentTy;
3206  else {
3207  // Pre-defined identifiers are of type char[x], where x is the length of
3208  // the string.
3209  auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3210  unsigned Length = Str.length();
3211 
3212  llvm::APInt LengthI(32, Length + 1);
3214  ResTy =
3216  SmallString<32> RawChars;
3218  Str, RawChars);
3219  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3220  /*IndexTypeQuals*/ 0);
3221  SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3222  /*Pascal*/ false, ResTy, Loc);
3223  } else {
3224  ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3225  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3226  /*IndexTypeQuals*/ 0);
3227  SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3228  /*Pascal*/ false, ResTy, Loc);
3229  }
3230  }
3231 
3232  return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3233 }
3234 
3237 
3238  switch (Kind) {
3239  default: llvm_unreachable("Unknown simple primary expr!");
3240  case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3241  case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3242  case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3243  case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3244  case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3245  case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3246  case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3247  }
3248 
3249  return BuildPredefinedExpr(Loc, IK);
3250 }
3251 
3253  SmallString<16> CharBuffer;
3254  bool Invalid = false;
3255  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3256  if (Invalid)
3257  return ExprError();
3258 
3259  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3260  PP, Tok.getKind());
3261  if (Literal.hadError())
3262  return ExprError();
3263 
3264  QualType Ty;
3265  if (Literal.isWide())
3266  Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3267  else if (Literal.isUTF8() && getLangOpts().Char8)
3268  Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3269  else if (Literal.isUTF16())
3270  Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3271  else if (Literal.isUTF32())
3272  Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3273  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3274  Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3275  else
3276  Ty = Context.CharTy; // 'x' -> char in C++
3277 
3279  if (Literal.isWide())
3281  else if (Literal.isUTF16())
3283  else if (Literal.isUTF32())
3285  else if (Literal.isUTF8())
3287 
3288  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3289  Tok.getLocation());
3290 
3291  if (Literal.getUDSuffix().empty())
3292  return Lit;
3293 
3294  // We're building a user-defined literal.
3295  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3296  SourceLocation UDSuffixLoc =
3297  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3298 
3299  // Make sure we're allowed user-defined literals here.
3300  if (!UDLScope)
3301  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3302 
3303  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3304  // operator "" X (ch)
3305  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3306  Lit, Tok.getLocation());
3307 }
3308 
3310  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3311  return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3312  Context.IntTy, Loc);
3313 }
3314 
3316  QualType Ty, SourceLocation Loc) {
3317  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3318 
3319  using llvm::APFloat;
3320  APFloat Val(Format);
3321 
3322  APFloat::opStatus result = Literal.GetFloatValue(Val);
3323 
3324  // Overflow is always an error, but underflow is only an error if
3325  // we underflowed to zero (APFloat reports denormals as underflow).
3326  if ((result & APFloat::opOverflow) ||
3327  ((result & APFloat::opUnderflow) && Val.isZero())) {
3328  unsigned diagnostic;
3329  SmallString<20> buffer;
3330  if (result & APFloat::opOverflow) {
3331  diagnostic = diag::warn_float_overflow;
3332  APFloat::getLargest(Format).toString(buffer);
3333  } else {
3334  diagnostic = diag::warn_float_underflow;
3335  APFloat::getSmallest(Format).toString(buffer);
3336  }
3337 
3338  S.Diag(Loc, diagnostic)
3339  << Ty
3340  << StringRef(buffer.data(), buffer.size());
3341  }
3342 
3343  bool isExact = (result == APFloat::opOK);
3344  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3345 }
3346 
3348  assert(E && "Invalid expression");
3349 
3350  if (E->isValueDependent())
3351  return false;
3352 
3353  QualType QT = E->getType();
3354  if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3355  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3356  return true;
3357  }
3358 
3359  llvm::APSInt ValueAPS;
3360  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3361 
3362  if (R.isInvalid())
3363  return true;
3364 
3365  bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3366  if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3367  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3368  << ValueAPS.toString(10) << ValueIsPositive;
3369  return true;
3370  }
3371 
3372  return false;
3373 }
3374 
3376  // Fast path for a single digit (which is quite common). A single digit
3377  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3378  if (Tok.getLength() == 1) {
3379  const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3380  return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3381  }
3382 
3383  SmallString<128> SpellingBuffer;
3384  // NumericLiteralParser wants to overread by one character. Add padding to
3385  // the buffer in case the token is copied to the buffer. If getSpelling()
3386  // returns a StringRef to the memory buffer, it should have a null char at
3387  // the EOF, so it is also safe.
3388  SpellingBuffer.resize(Tok.getLength() + 1);
3389 
3390  // Get the spelling of the token, which eliminates trigraphs, etc.
3391  bool Invalid = false;
3392  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3393  if (Invalid)
3394  return ExprError();
3395 
3396  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3397  if (Literal.hadError)
3398  return ExprError();
3399 
3400  if (Literal.hasUDSuffix()) {
3401  // We're building a user-defined literal.
3402  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3403  SourceLocation UDSuffixLoc =
3404  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3405 
3406  // Make sure we're allowed user-defined literals here.
3407  if (!UDLScope)
3408  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3409 
3410  QualType CookedTy;
3411  if (Literal.isFloatingLiteral()) {
3412  // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3413  // long double, the literal is treated as a call of the form
3414  // operator "" X (f L)
3415  CookedTy = Context.LongDoubleTy;
3416  } else {
3417  // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3418  // unsigned long long, the literal is treated as a call of the form
3419  // operator "" X (n ULL)
3420  CookedTy = Context.UnsignedLongLongTy;
3421  }
3422 
3423  DeclarationName OpName =
3424  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3425  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3426  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3427 
3428  SourceLocation TokLoc = Tok.getLocation();
3429 
3430  // Perform literal operator lookup to determine if we're building a raw
3431  // literal or a cooked one.
3432  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3433  switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3434  /*AllowRaw*/ true, /*AllowTemplate*/ true,
3435  /*AllowStringTemplate*/ false,
3436  /*DiagnoseMissing*/ !Literal.isImaginary)) {
3437  case LOLR_ErrorNoDiagnostic:
3438  // Lookup failure for imaginary constants isn't fatal, there's still the
3439  // GNU extension producing _Complex types.
3440  break;
3441  case LOLR_Error:
3442  return ExprError();
3443  case LOLR_Cooked: {
3444  Expr *Lit;
3445  if (Literal.isFloatingLiteral()) {
3446  Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3447  } else {
3448  llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3449  if (Literal.GetIntegerValue(ResultVal))
3450  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3451  << /* Unsigned */ 1;
3452  Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3453  Tok.getLocation());
3454  }
3455  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3456  }
3457 
3458  case LOLR_Raw: {
3459  // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3460  // literal is treated as a call of the form
3461  // operator "" X ("n")
3462  unsigned Length = Literal.getUDSuffixOffset();
3463  QualType StrTy = Context.getConstantArrayType(
3464  Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3465  llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3466  Expr *Lit = StringLiteral::Create(
3467  Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3468  /*Pascal*/false, StrTy, &TokLoc, 1);
3469  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3470  }
3471 
3472  case LOLR_Template: {
3473  // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3474  // template), L is treated as a call fo the form
3475  // operator "" X <'c1', 'c2', ... 'ck'>()
3476  // where n is the source character sequence c1 c2 ... ck.
3477  TemplateArgumentListInfo ExplicitArgs;
3478  unsigned CharBits = Context.getIntWidth(Context.CharTy);
3479  bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3480  llvm::APSInt Value(CharBits, CharIsUnsigned);
3481  for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3482  Value = TokSpelling[I];
3483  TemplateArgument Arg(Context, Value, Context.CharTy);
3484  TemplateArgumentLocInfo ArgInfo;
3485  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3486  }
3487  return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3488  &ExplicitArgs);
3489  }
3490  case LOLR_StringTemplate:
3491  llvm_unreachable("unexpected literal operator lookup result");
3492  }
3493  }
3494 
3495  Expr *Res;
3496 
3497  if (Literal.isFixedPointLiteral()) {
3498  QualType Ty;
3499 
3500  if (Literal.isAccum) {
3501  if (Literal.isHalf) {
3502  Ty = Context.ShortAccumTy;
3503  } else if (Literal.isLong) {
3504  Ty = Context.LongAccumTy;
3505  } else {
3506  Ty = Context.AccumTy;
3507  }
3508  } else if (Literal.isFract) {
3509  if (Literal.isHalf) {
3510  Ty = Context.ShortFractTy;
3511  } else if (Literal.isLong) {
3512  Ty = Context.LongFractTy;
3513  } else {
3514  Ty = Context.FractTy;
3515  }
3516  }
3517 
3518  if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3519 
3520  bool isSigned = !Literal.isUnsigned;
3521  unsigned scale = Context.getFixedPointScale(Ty);
3522  unsigned bit_width = Context.getTypeInfo(Ty).Width;
3523 
3524  llvm::APInt Val(bit_width, 0, isSigned);
3525  bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3526  bool ValIsZero = Val.isNullValue() && !Overflowed;
3527 
3528  auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3529  if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3530  // Clause 6.4.4 - The value of a constant shall be in the range of
3531  // representable values for its type, with exception for constants of a
3532  // fract type with a value of exactly 1; such a constant shall denote
3533  // the maximal value for the type.
3534  --Val;
3535  else if (Val.ugt(MaxVal) || Overflowed)
3536  Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3537 
3538  Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3539  Tok.getLocation(), scale);
3540  } else if (Literal.isFloatingLiteral()) {
3541  QualType Ty;
3542  if (Literal.isHalf){
3543  if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3544  Ty = Context.HalfTy;
3545  else {
3546  Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3547  return ExprError();
3548  }
3549  } else if (Literal.isFloat)
3550  Ty = Context.FloatTy;
3551  else if (Literal.isLong)
3552  Ty = Context.LongDoubleTy;
3553  else if (Literal.isFloat16)
3554  Ty = Context.Float16Ty;
3555  else if (Literal.isFloat128)
3556  Ty = Context.Float128Ty;
3557  else
3558  Ty = Context.DoubleTy;
3559 
3560  Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3561 
3562  if (Ty == Context.DoubleTy) {
3563  if (getLangOpts().SinglePrecisionConstants) {
3564  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3565  if (BTy->getKind() != BuiltinType::Float) {
3566  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3567  }
3568  } else if (getLangOpts().OpenCL &&
3569  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3570  // Impose single-precision float type when cl_khr_fp64 is not enabled.
3571  Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3572  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3573  }
3574  }
3575  } else if (!Literal.isIntegerLiteral()) {
3576  return ExprError();
3577  } else {
3578  QualType Ty;
3579 
3580  // 'long long' is a C99 or C++11 feature.
3581  if (!getLangOpts().C99 && Literal.isLongLong) {
3582  if (getLangOpts().CPlusPlus)
3583  Diag(Tok.getLocation(),
3584  getLangOpts().CPlusPlus11 ?
3585  diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3586  else
3587  Diag(Tok.getLocation(), diag::ext_c99_longlong);
3588  }
3589 
3590  // Get the value in the widest-possible width.
3591  unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3592  llvm::APInt ResultVal(MaxWidth, 0);
3593 
3594  if (Literal.GetIntegerValue(ResultVal)) {
3595  // If this value didn't fit into uintmax_t, error and force to ull.
3596  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3597  << /* Unsigned */ 1;
3598  Ty = Context.UnsignedLongLongTy;
3599  assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3600  "long long is not intmax_t?");
3601  } else {
3602  // If this value fits into a ULL, try to figure out what else it fits into
3603  // according to the rules of C99 6.4.4.1p5.
3604 
3605  // Octal, Hexadecimal, and integers with a U suffix are allowed to
3606  // be an unsigned int.
3607  bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3608 
3609  // Check from smallest to largest, picking the smallest type we can.
3610  unsigned Width = 0;
3611 
3612  // Microsoft specific integer suffixes are explicitly sized.
3613  if (Literal.MicrosoftInteger) {
3614  if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3615  Width = 8;
3616  Ty = Context.CharTy;
3617  } else {
3618  Width = Literal.MicrosoftInteger;
3619  Ty = Context.getIntTypeForBitwidth(Width,
3620  /*Signed=*/!Literal.isUnsigned);
3621  }
3622  }
3623 
3624  if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3625  // Are int/unsigned possibilities?
3626  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3627 
3628  // Does it fit in a unsigned int?
3629  if (ResultVal.isIntN(IntSize)) {
3630  // Does it fit in a signed int?
3631  if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3632  Ty = Context.IntTy;
3633  else if (AllowUnsigned)
3634  Ty = Context.UnsignedIntTy;
3635  Width = IntSize;
3636  }
3637  }
3638 
3639  // Are long/unsigned long possibilities?
3640  if (Ty.isNull() && !Literal.isLongLong) {
3641  unsigned LongSize = Context.getTargetInfo().getLongWidth();
3642 
3643  // Does it fit in a unsigned long?
3644  if (ResultVal.isIntN(LongSize)) {
3645  // Does it fit in a signed long?
3646  if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3647  Ty = Context.LongTy;
3648  else if (AllowUnsigned)
3649  Ty = Context.UnsignedLongTy;
3650  // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3651  // is compatible.
3652  else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3653  const unsigned LongLongSize =
3654  Context.getTargetInfo().getLongLongWidth();
3655  Diag(Tok.getLocation(),
3656  getLangOpts().CPlusPlus
3657  ? Literal.isLong
3658  ? diag::warn_old_implicitly_unsigned_long_cxx
3659  : /*C++98 UB*/ diag::
3660  ext_old_implicitly_unsigned_long_cxx
3661  : diag::warn_old_implicitly_unsigned_long)
3662  << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3663  : /*will be ill-formed*/ 1);
3664  Ty = Context.UnsignedLongTy;
3665  }
3666  Width = LongSize;
3667  }
3668  }
3669 
3670  // Check long long if needed.
3671  if (Ty.isNull()) {
3672  unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3673 
3674  // Does it fit in a unsigned long long?
3675  if (ResultVal.isIntN(LongLongSize)) {
3676  // Does it fit in a signed long long?
3677  // To be compatible with MSVC, hex integer literals ending with the
3678  // LL or i64 suffix are always signed in Microsoft mode.
3679  if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3680  (getLangOpts().MSVCCompat && Literal.isLongLong)))
3681  Ty = Context.LongLongTy;
3682  else if (AllowUnsigned)
3683  Ty = Context.UnsignedLongLongTy;
3684  Width = LongLongSize;
3685  }
3686  }
3687 
3688  // If we still couldn't decide a type, we probably have something that
3689  // does not fit in a signed long long, but has no U suffix.
3690  if (Ty.isNull()) {
3691  Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3692  Ty = Context.UnsignedLongLongTy;
3693  Width = Context.getTargetInfo().getLongLongWidth();
3694  }
3695 
3696  if (ResultVal.getBitWidth() != Width)
3697  ResultVal = ResultVal.trunc(Width);
3698  }
3699  Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3700  }
3701 
3702  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3703  if (Literal.isImaginary) {
3704  Res = new (Context) ImaginaryLiteral(Res,
3705  Context.getComplexType(Res->getType()));
3706 
3707  Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3708  }
3709  return Res;
3710 }
3711 
3713  assert(E && "ActOnParenExpr() missing expr");
3714  return new (Context) ParenExpr(L, R, E);
3715 }
3716 
3718  SourceLocation Loc,
3719  SourceRange ArgRange) {
3720  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3721  // scalar or vector data type argument..."
3722  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3723  // type (C99 6.2.5p18) or void.
3724  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3725  S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3726  << T << ArgRange;
3727  return true;
3728  }
3729 
3730  assert((T->isVoidType() || !T->isIncompleteType()) &&
3731  "Scalar types should always be complete");
3732  return false;
3733 }
3734 
3736  SourceLocation Loc,
3737  SourceRange ArgRange,
3738  UnaryExprOrTypeTrait TraitKind) {
3739  // Invalid types must be hard errors for SFINAE in C++.
3740  if (S.LangOpts.CPlusPlus)
3741  return true;
3742 
3743  // C99 6.5.3.4p1:
3744  if (T->isFunctionType() &&
3745  (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3746  TraitKind == UETT_PreferredAlignOf)) {
3747  // sizeof(function)/alignof(function) is allowed as an extension.
3748  S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3749  << TraitKind << ArgRange;
3750  return false;
3751  }
3752 
3753  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3754  // this is an error (OpenCL v1.1 s6.3.k)
3755  if (T->isVoidType()) {
3756  unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3757  : diag::ext_sizeof_alignof_void_type;
3758  S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3759  return false;
3760  }
3761 
3762  return true;
3763 }
3764 
3766  SourceLocation Loc,
3767  SourceRange ArgRange,
3768  UnaryExprOrTypeTrait TraitKind) {
3769  // Reject sizeof(interface) and sizeof(interface<proto>) if the
3770  // runtime doesn't allow it.
3772  S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3773  << T << (TraitKind == UETT_SizeOf)
3774  << ArgRange;
3775  return true;
3776  }
3777 
3778  return false;
3779 }
3780 
3781 /// Check whether E is a pointer from a decayed array type (the decayed
3782 /// pointer type is equal to T) and emit a warning if it is.
3784  Expr *E) {
3785  // Don't warn if the operation changed the type.
3786  if (T != E->getType())
3787  return;
3788 
3789  // Now look for array decays.
3790  ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3791  if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3792  return;
3793 
3794  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3795  << ICE->getType()
3796  << ICE->getSubExpr()->getType();
3797 }
3798 
3799 /// Check the constraints on expression operands to unary type expression
3800 /// and type traits.
3801 ///
3802 /// Completes any types necessary and validates the constraints on the operand
3803 /// expression. The logic mostly mirrors the type-based overload, but may modify
3804 /// the expression as it completes the type for that expression through template
3805 /// instantiation, etc.
3807  UnaryExprOrTypeTrait ExprKind) {
3808  QualType ExprTy = E->getType();
3809  assert(!ExprTy->isReferenceType());
3810 
3811  if (ExprKind == UETT_VecStep)
3812  return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3813  E->getSourceRange());
3814 
3815  // Whitelist some types as extensions
3816  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3817  E->getSourceRange(), ExprKind))
3818  return false;
3819 
3820  // 'alignof' applied to an expression only requires the base element type of
3821  // the expression to be complete. 'sizeof' requires the expression's type to
3822  // be complete (and will attempt to complete it if it's an array of unknown
3823  // bound).
3824  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3825  if (RequireCompleteType(E->getExprLoc(),
3826  Context.getBaseElementType(E->getType()),
3827  diag::err_sizeof_alignof_incomplete_type, ExprKind,
3828  E->getSourceRange()))
3829  return true;
3830  } else {
3831  if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3832  ExprKind, E->getSourceRange()))
3833  return true;
3834  }
3835 
3836  // Completing the expression's type may have changed it.
3837  ExprTy = E->getType();
3838  assert(!ExprTy->isReferenceType());
3839 
3840  if (ExprTy->isFunctionType()) {
3841  Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3842  << ExprKind << E->getSourceRange();
3843  return true;
3844  }
3845 
3846  // The operand for sizeof and alignof is in an unevaluated expression context,
3847  // so side effects could result in unintended consequences.
3848  if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3849  ExprKind == UETT_PreferredAlignOf) &&
3850  !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3851  Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3852 
3853  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3854  E->getSourceRange(), ExprKind))
3855  return true;
3856 
3857  if (ExprKind == UETT_SizeOf) {
3858  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3859  if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3860  QualType OType = PVD->getOriginalType();
3861  QualType Type = PVD->getType();
3862  if (Type->isPointerType() && OType->isArrayType()) {
3863  Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3864  << Type << OType;
3865  Diag(PVD->getLocation(), diag::note_declared_at);
3866  }
3867  }
3868  }
3869 
3870  // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3871  // decays into a pointer and returns an unintended result. This is most
3872  // likely a typo for "sizeof(array) op x".
3873  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3874  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3875  BO->getLHS());
3876  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3877  BO->getRHS());
3878  }
3879  }
3880 
3881  return false;
3882 }
3883 
3884 /// Check the constraints on operands to unary expression and type
3885 /// traits.
3886 ///
3887 /// This will complete any types necessary, and validate the various constraints
3888 /// on those operands.
3889 ///
3890 /// The UsualUnaryConversions() function is *not* called by this routine.
3891 /// C99 6.3.2.1p[2-4] all state:
3892 /// Except when it is the operand of the sizeof operator ...
3893 ///
3894 /// C++ [expr.sizeof]p4
3895 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3896 /// standard conversions are not applied to the operand of sizeof.
3897 ///
3898 /// This policy is followed for all of the unary trait expressions.
3900  SourceLocation OpLoc,
3901  SourceRange ExprRange,
3902  UnaryExprOrTypeTrait ExprKind) {
3903  if (ExprType->isDependentType())
3904  return false;
3905 
3906  // C++ [expr.sizeof]p2:
3907  // When applied to a reference or a reference type, the result
3908  // is the size of the referenced type.
3909  // C++11 [expr.alignof]p3:
3910  // When alignof is applied to a reference type, the result
3911  // shall be the alignment of the referenced type.
3912  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3913  ExprType = Ref->getPointeeType();
3914 
3915  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3916  // When alignof or _Alignof is applied to an array type, the result
3917  // is the alignment of the element type.
3918  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3919  ExprKind == UETT_OpenMPRequiredSimdAlign)
3920  ExprType = Context.getBaseElementType(ExprType);
3921 
3922  if (ExprKind == UETT_VecStep)
3923  return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3924 
3925  // Whitelist some types as extensions
3926  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3927  ExprKind))
3928  return false;
3929 
3930  if (RequireCompleteType(OpLoc, ExprType,
3931  diag::err_sizeof_alignof_incomplete_type,
3932  ExprKind, ExprRange))
3933  return true;
3934 
3935  if (ExprType->isFunctionType()) {
3936  Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3937  << ExprKind << ExprRange;
3938  return true;
3939  }
3940 
3941  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3942  ExprKind))
3943  return true;
3944 
3945  return false;
3946 }
3947 
3948 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3949  E = E->IgnoreParens();
3950 
3951  // Cannot know anything else if the expression is dependent.
3952  if (E->isTypeDependent())
3953  return false;
3954 
3955  if (E->getObjectKind() == OK_BitField) {
3956  S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3957  << 1 << E->getSourceRange();
3958  return true;
3959  }
3960 
3961  ValueDecl *D = nullptr;
3962  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3963  D = DRE->getDecl();
3964  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3965  D = ME->getMemberDecl();
3966  }
3967 
3968  // If it's a field, require the containing struct to have a
3969  // complete definition so that we can compute the layout.
3970  //
3971  // This can happen in C++11 onwards, either by naming the member
3972  // in a way that is not transformed into a member access expression
3973  // (in an unevaluated operand, for instance), or by naming the member
3974  // in a trailing-return-type.
3975  //
3976  // For the record, since __alignof__ on expressions is a GCC
3977  // extension, GCC seems to permit this but always gives the
3978  // nonsensical answer 0.
3979  //
3980  // We don't really need the layout here --- we could instead just
3981  // directly check for all the appropriate alignment-lowing
3982  // attributes --- but that would require duplicating a lot of
3983  // logic that just isn't worth duplicating for such a marginal
3984  // use-case.
3985  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3986  // Fast path this check, since we at least know the record has a
3987  // definition if we can find a member of it.
3988  if (!FD->getParent()->isCompleteDefinition()) {
3989  S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3990  << E->getSourceRange();
3991  return true;
3992  }
3993 
3994  // Otherwise, if it's a field, and the field doesn't have
3995  // reference type, then it must have a complete type (or be a
3996  // flexible array member, which we explicitly want to
3997  // white-list anyway), which makes the following checks trivial.
3998  if (!FD->getType()->isReferenceType())
3999  return false;
4000  }
4001 
4002  return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4003 }
4004 
4006  E = E->IgnoreParens();
4007 
4008  // Cannot know anything else if the expression is dependent.
4009  if (E->isTypeDependent())
4010  return false;
4011 
4012  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4013 }
4014 
4016  CapturingScopeInfo *CSI) {
4017  assert(T->isVariablyModifiedType());
4018  assert(CSI != nullptr);
4019 
4020  // We're going to walk down into the type and look for VLA expressions.
4021  do {
4022  const Type *Ty = T.getTypePtr();
4023  switch (Ty->getTypeClass()) {
4024 #define TYPE(Class, Base)
4025 #define ABSTRACT_TYPE(Class, Base)
4026 #define NON_CANONICAL_TYPE(Class, Base)
4027 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4028 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4029 #include "clang/AST/TypeNodes.def"
4030  T = QualType();
4031  break;
4032  // These types are never variably-modified.
4033  case Type::Builtin:
4034  case Type::Complex:
4035  case Type::Vector:
4036  case Type::ExtVector:
4037  case Type::Record:
4038  case Type::Enum:
4039  case Type::Elaborated:
4040  case Type::TemplateSpecialization:
4041  case Type::ObjCObject:
4042  case Type::ObjCInterface:
4043  case Type::ObjCObjectPointer:
4044  case Type::ObjCTypeParam:
4045  case Type::Pipe:
4046  llvm_unreachable("type class is never variably-modified!");
4047  case Type::Adjusted:
4048  T = cast<AdjustedType>(Ty)->getOriginalType();
4049  break;
4050  case Type::Decayed:
4051  T = cast<DecayedType>(Ty)->getPointeeType();
4052  break;
4053  case Type::Pointer:
4054  T = cast<PointerType>(Ty)->getPointeeType();
4055  break;
4056  case Type::BlockPointer:
4057  T = cast<BlockPointerType>(Ty)->getPointeeType();
4058  break;
4059  case Type::LValueReference:
4060  case Type::RValueReference:
4061  T = cast<ReferenceType>(Ty)->getPointeeType();
4062  break;
4063  case Type::MemberPointer:
4064  T = cast<MemberPointerType>(Ty)->getPointeeType();
4065  break;
4066  case Type::ConstantArray:
4067  case Type::IncompleteArray:
4068  // Losing element qualification here is fine.
4069  T = cast<ArrayType>(Ty)->getElementType();
4070  break;
4071  case Type::VariableArray: {
4072  // Losing element qualification here is fine.
4073  const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4074 
4075  // Unknown size indication requires no size computation.
4076  // Otherwise, evaluate and record it.
4077  auto Size = VAT->getSizeExpr();
4078  if (Size && !CSI->isVLATypeCaptured(VAT) &&
4079  (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4080  CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4081 
4082  T = VAT->getElementType();
4083  break;
4084  }
4085  case Type::FunctionProto:
4086  case Type::FunctionNoProto:
4087  T = cast<FunctionType>(Ty)->getReturnType();
4088  break;
4089  case Type::Paren:
4090  case Type::TypeOf:
4091  case Type::UnaryTransform:
4092  case Type::Attributed:
4093  case Type::SubstTemplateTypeParm:
4094  case Type::PackExpansion:
4095  case Type::MacroQualified:
4096  // Keep walking after single level desugaring.
4097  T = T.getSingleStepDesugaredType(Context);
4098  break;
4099  case Type::Typedef:
4100  T = cast<TypedefType>(Ty)->desugar();
4101  break;
4102  case Type::Decltype:
4103  T = cast<DecltypeType>(Ty)->desugar();
4104  break;
4105  case Type::Auto:
4106  case Type::DeducedTemplateSpecialization:
4107  T = cast<DeducedType>(Ty)->getDeducedType();
4108  break;
4109  case Type::TypeOfExpr:
4110  T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4111  break;
4112  case Type::Atomic:
4113  T = cast<AtomicType>(Ty)->getValueType();
4114  break;
4115  }
4116  } while (!T.isNull() && T->isVariablyModifiedType());
4117 }
4118 
4119 /// Build a sizeof or alignof expression given a type operand.
4120 ExprResult
4122  SourceLocation OpLoc,
4123  UnaryExprOrTypeTrait ExprKind,
4124  SourceRange R) {
4125  if (!TInfo)
4126  return ExprError();
4127 
4128  QualType T = TInfo->getType();
4129 
4130  if (!T->isDependentType() &&
4131  CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4132  return ExprError();
4133 
4134  if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4135  if (auto *TT = T->getAs<TypedefType>()) {
4136  for (auto I = FunctionScopes.rbegin(),
4137  E = std::prev(FunctionScopes.rend());
4138  I != E; ++I) {
4139  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4140  if (CSI == nullptr)
4141  break;
4142  DeclContext *DC = nullptr;
4143  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4144  DC = LSI->CallOperator;
4145  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4146  DC = CRSI->TheCapturedDecl;
4147  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4148  DC = BSI->TheDecl;
4149  if (DC) {
4150  if (DC->containsDecl(TT->getDecl()))
4151  break;
4152  captureVariablyModifiedType(Context, T, CSI);
4153  }
4154  }
4155  }
4156  }
4157 
4158  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4159  return new (Context) UnaryExprOrTypeTraitExpr(
4160  ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4161 }
4162 
4163 /// Build a sizeof or alignof expression given an expression
4164 /// operand.
4165 ExprResult
4167  UnaryExprOrTypeTrait ExprKind) {
4168  ExprResult PE = CheckPlaceholderExpr(E);
4169  if (PE.isInvalid())
4170  return ExprError();
4171 
4172  E = PE.get();
4173 
4174  // Verify that the operand is valid.
4175  bool isInvalid = false;
4176  if (E->isTypeDependent()) {
4177  // Delay type-checking for type-dependent expressions.
4178  } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4179  isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4180  } else if (ExprKind == UETT_VecStep) {
4181  isInvalid = CheckVecStepExpr(E);
4182  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4183  Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4184  isInvalid = true;
4185  } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4186  Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4187  isInvalid = true;
4188  } else {
4189  isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4190  }
4191 
4192  if (isInvalid)
4193  return ExprError();
4194 
4195  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4196  PE = TransformToPotentiallyEvaluated(E);
4197  if (PE.isInvalid()) return ExprError();
4198  E = PE.get();
4199  }
4200 
4201  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4202  return new (Context) UnaryExprOrTypeTraitExpr(
4203  ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4204 }
4205 
4206 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4207 /// expr and the same for @c alignof and @c __alignof
4208 /// Note that the ArgRange is invalid if isType is false.
4209 ExprResult
4211  UnaryExprOrTypeTrait ExprKind, bool IsType,
4212  void *TyOrEx, SourceRange ArgRange) {
4213  // If error parsing type, ignore.
4214  if (!TyOrEx) return ExprError();
4215 
4216  if (IsType) {
4217  TypeSourceInfo *TInfo;
4218  (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4219  return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4220  }
4221 
4222  Expr *ArgEx = (Expr *)TyOrEx;
4223  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4224  return Result;
4225 }
4226 
4228  bool IsReal) {
4229  if (V.get()->isTypeDependent())
4230  return S.Context.DependentTy;
4231 
4232  // _Real and _Imag are only l-values for normal l-values.
4233  if (V.get()->getObjectKind() != OK_Ordinary) {
4234  V = S.DefaultLvalueConversion(V.get());
4235  if (V.isInvalid())
4236  return QualType();
4237  }
4238 
4239  // These operators return the element type of a complex type.
4240  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4241  return CT->getElementType();
4242 
4243  // Otherwise they pass through real integer and floating point types here.
4244  if (V.get()->getType()->isArithmeticType())
4245  return V.get()->getType();
4246 
4247  // Test for placeholders.
4248  ExprResult PR = S.CheckPlaceholderExpr(V.get());
4249  if (PR.isInvalid()) return QualType();
4250  if (PR.get() != V.get()) {
4251  V = PR;
4252  return CheckRealImagOperand(S, V, Loc, IsReal);
4253  }
4254 
4255  // Reject anything else.
4256  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4257  << (IsReal ? "__real" : "__imag");
4258  return QualType();
4259 }
4260 
4261 
4262 
4263 ExprResult
4265  tok::TokenKind Kind, Expr *Input) {
4266  UnaryOperatorKind Opc;
4267  switch (Kind) {
4268  default: llvm_unreachable("Unknown unary op!");
4269  case tok::plusplus: Opc = UO_PostInc; break;
4270  case tok::minusminus: Opc = UO_PostDec; break;
4271  }
4272 
4273  // Since this might is a postfix expression, get rid of ParenListExprs.
4274  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4275  if (Result.isInvalid()) return ExprError();
4276  Input = Result.get();
4277 
4278  return BuildUnaryOp(S, OpLoc, Opc, Input);
4279 }
4280 
4281 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4282 ///
4283 /// \return true on error
4285  SourceLocation opLoc,
4286  Expr *op) {
4287  assert(op->getType()->isObjCObjectPointerType());
4289  !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4290  return false;
4291 
4292  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4293  << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4294  << op->getSourceRange();
4295  return true;
4296 }
4297 
4299  auto *BaseNoParens = Base->IgnoreParens();
4300  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4301  return MSProp->getPropertyDecl()->getType()->isArrayType();
4302  return isa<MSPropertySubscriptExpr>(BaseNoParens);
4303 }
4304 
4305 ExprResult
4307  Expr *idx, SourceLocation rbLoc) {
4308  if (base && !base->getType().isNull() &&
4309  base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4310  return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4311  /*Length=*/nullptr, rbLoc);
4312 
4313  // Since this might be a postfix expression, get rid of ParenListExprs.
4314  if (isa<ParenListExpr>(base)) {
4315  ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4316  if (result.isInvalid()) return ExprError();
4317  base = result.get();
4318  }
4319 
4320  // Handle any non-overload placeholder types in the base and index
4321  // expressions. We can't handle overloads here because the other
4322  // operand might be an overloadable type, in which case the overload
4323  // resolution for the operator overload should get the first crack
4324  // at the overload.
4325  bool IsMSPropertySubscript = false;
4326  if (base->getType()->isNonOverloadPlaceholderType()) {
4327  IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4328  if (!IsMSPropertySubscript) {
4329  ExprResult result = CheckPlaceholderExpr(base);
4330  if (result.isInvalid())
4331  return ExprError();
4332  base = result.get();
4333  }
4334  }
4335  if (idx->getType()->isNonOverloadPlaceholderType()) {
4336  ExprResult result = CheckPlaceholderExpr(idx);
4337  if (result.isInvalid()) return ExprError();
4338  idx = result.get();
4339  }
4340 
4341  // Build an unanalyzed expression if either operand is type-dependent.
4342  if (getLangOpts().CPlusPlus &&
4343  (base->isTypeDependent() || idx->isTypeDependent())) {
4344  return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4345  VK_LValue, OK_Ordinary, rbLoc);
4346  }
4347 
4348  // MSDN, property (C++)
4349  // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4350  // This attribute can also be used in the declaration of an empty array in a
4351  // class or structure definition. For example:
4352  // __declspec(property(get=GetX, put=PutX)) int x[];
4353  // The above statement indicates that x[] can be used with one or more array
4354  // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4355  // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4356  if (IsMSPropertySubscript) {
4357  // Build MS property subscript expression if base is MS property reference
4358  // or MS property subscript.
4359  return new (Context) MSPropertySubscriptExpr(
4360  base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4361  }
4362 
4363  // Use C++ overloaded-operator rules if either operand has record
4364  // type. The spec says to do this if either type is *overloadable*,
4365  // but enum types can't declare subscript operators or conversion
4366  // operators, so there's nothing interesting for overload resolution
4367  // to do if there aren't any record types involved.
4368  //
4369  // ObjC pointers have their own subscripting logic that is not tied
4370  // to overload resolution and so should not take this path.
4371  if (getLangOpts().CPlusPlus &&
4372  (base->getType()->isRecordType() ||
4373  (!base->getType()->isObjCObjectPointerType() &&
4374  idx->getType()->isRecordType()))) {
4375  return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4376  }
4377 
4378  ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4379 
4380  if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4381  CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4382 
4383  return Res;
4384 }
4385 
4386 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4387  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4388  const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4389 
4390  // For expressions like `&(*s).b`, the base is recorded and what should be
4391  // checked.
4392  const MemberExpr *Member = nullptr;
4393  while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4394  StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4395 
4396  LastRecord.PossibleDerefs.erase(StrippedExpr);
4397 }
4398 
4399 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4400  QualType ResultTy = E->getType();
4401  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4402 
4403  // Bail if the element is an array since it is not memory access.
4404  if (isa<ArrayType>(ResultTy))
4405  return;
4406 
4407  if (ResultTy->hasAttr(attr::NoDeref)) {
4408  LastRecord.PossibleDerefs.insert(E);
4409  return;
4410  }
4411 
4412  // Check if the base type is a pointer to a member access of a struct
4413  // marked with noderef.
4414  const Expr *Base = E->getBase();
4415  QualType BaseTy = Base->getType();
4416  if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4417  // Not a pointer access
4418  return;
4419 
4420  const MemberExpr *Member = nullptr;
4421  while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4422  Member->isArrow())
4423  Base = Member->getBase();
4424 
4425  if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4426  if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4427  LastRecord.PossibleDerefs.insert(E);
4428  }
4429 }
4430 
4432  Expr *LowerBound,
4433  SourceLocation ColonLoc, Expr *Length,
4434  SourceLocation RBLoc) {
4435  if (Base->getType()->isPlaceholderType() &&
4437  BuiltinType::OMPArraySection)) {
4438  ExprResult Result = CheckPlaceholderExpr(Base);
4439  if (Result.isInvalid())
4440  return ExprError();
4441  Base = Result.get();
4442  }
4443  if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4444  ExprResult Result = CheckPlaceholderExpr(LowerBound);
4445  if (Result.isInvalid())
4446  return ExprError();
4447  Result = DefaultLvalueConversion(Result.get());
4448  if (Result.isInvalid())
4449  return ExprError();
4450  LowerBound = Result.get();
4451  }
4452  if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4453  ExprResult Result = CheckPlaceholderExpr(Length);
4454  if (Result.isInvalid())
4455  return ExprError();
4456  Result = DefaultLvalueConversion(Result.get());
4457  if (Result.isInvalid())
4458  return ExprError();
4459  Length = Result.get();
4460  }
4461 
4462  // Build an unanalyzed expression if either operand is type-dependent.
4463  if (Base->isTypeDependent() ||
4464  (LowerBound &&
4465  (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4466  (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4467  return new (Context)
4468  OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4469  VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4470  }
4471 
4472  // Perform default conversions.
4474  QualType ResultTy;
4475  if (OriginalTy->isAnyPointerType()) {
4476  ResultTy = OriginalTy->getPointeeType();
4477  } else if (OriginalTy->isArrayType()) {
4478  ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4479  } else {
4480  return ExprError(
4481  Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4482  << Base->getSourceRange());
4483  }
4484  // C99 6.5.2.1p1
4485  if (LowerBound) {
4486  auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4487  LowerBound);
4488  if (Res.isInvalid())
4489  return ExprError(Diag(LowerBound->getExprLoc(),
4490  diag::err_omp_typecheck_section_not_integer)
4491  << 0 << LowerBound->getSourceRange());
4492  LowerBound = Res.get();
4493 
4494  if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4495  LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4496  Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4497  << 0 << LowerBound->getSourceRange();
4498  }
4499  if (Length) {
4500  auto Res =
4501  PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4502  if (Res.isInvalid())
4503  return ExprError(Diag(Length->getExprLoc(),
4504  diag::err_omp_typecheck_section_not_integer)
4505  << 1 << Length->getSourceRange());
4506  Length = Res.get();
4507 
4508  if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4509  Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4510  Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4511  << 1 << Length->getSourceRange();
4512  }
4513 
4514  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4515  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4516  // type. Note that functions are not objects, and that (in C99 parlance)
4517  // incomplete types are not object types.
4518  if (ResultTy->isFunctionType()) {
4519  Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4520  << ResultTy << Base->getSourceRange();
4521  return ExprError();
4522  }
4523 
4524  if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4525  diag::err_omp_section_incomplete_type, Base))
4526  return ExprError();
4527 
4528  if (LowerBound && !OriginalTy->isAnyPointerType()) {
4529  Expr::EvalResult Result;
4530  if (LowerBound->EvaluateAsInt(Result, Context)) {
4531  // OpenMP 4.5, [2.4 Array Sections]
4532  // The array section must be a subset of the original array.
4533  llvm::APSInt LowerBoundValue = Result.Val.getInt();
4534  if (LowerBoundValue.isNegative()) {
4535  Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4536  << LowerBound->getSourceRange();
4537  return ExprError();
4538  }
4539  }
4540  }
4541 
4542  if (Length) {
4543  Expr::EvalResult Result;
4544  if (Length->EvaluateAsInt(Result, Context)) {
4545  // OpenMP 4.5, [2.4 Array Sections]
4546  // The length must evaluate to non-negative integers.
4547  llvm::APSInt LengthValue = Result.Val.getInt();
4548  if (LengthValue.isNegative()) {
4549  Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4550  << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4551  << Length->getSourceRange();
4552  return ExprError();
4553  }
4554  }
4555  } else if (ColonLoc.isValid() &&
4556  (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4557  !OriginalTy->isVariableArrayType()))) {
4558  // OpenMP 4.5, [2.4 Array Sections]
4559  // When the size of the array dimension is not known, the length must be
4560  // specified explicitly.
4561  Diag(ColonLoc, diag::err_omp_section_length_undefined)
4562  << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4563  return ExprError();
4564  }
4565 
4566  if (!Base->getType()->isSpecificPlaceholderType(
4567  BuiltinType::OMPArraySection)) {
4568  ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4569  if (Result.isInvalid())
4570  return ExprError();
4571  Base = Result.get();
4572  }
4573  return new (Context)
4574  OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4575  VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4576 }
4577 
4578 ExprResult
4580  Expr *Idx, SourceLocation RLoc) {
4581  Expr *LHSExp = Base;
4582  Expr *RHSExp = Idx;
4583 
4584  ExprValueKind VK = VK_LValue;
4586 
4587  // Per C++ core issue 1213, the result is an xvalue if either operand is
4588  // a non-lvalue array, and an lvalue otherwise.
4589  if (getLangOpts().CPlusPlus11) {
4590  for (auto *Op : {LHSExp, RHSExp}) {
4591  Op = Op->IgnoreImplicit();
4592  if (Op->getType()->isArrayType() && !Op->isLValue())
4593  VK = VK_XValue;
4594  }
4595  }
4596 
4597  // Perform default conversions.
4598  if (!LHSExp->getType()->getAs<VectorType>()) {
4599  ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4600  if (Result.isInvalid())
4601  return ExprError();
4602  LHSExp = Result.get();
4603  }
4604  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4605  if (Result.isInvalid())
4606  return ExprError();
4607  RHSExp = Result.get();
4608 
4609  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4610 
4611  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4612  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4613  // in the subscript position. As a result, we need to derive the array base
4614  // and index from the expression types.
4615  Expr *BaseExpr, *IndexExpr;
4616  QualType ResultType;
4617  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4618  BaseExpr = LHSExp;
4619  IndexExpr = RHSExp;
4620  ResultType = Context.DependentTy;
4621  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4622  BaseExpr = LHSExp;
4623  IndexExpr = RHSExp;
4624  ResultType = PTy->getPointeeType();
4625  } else if (const ObjCObjectPointerType *PTy =
4626  LHSTy->getAs<ObjCObjectPointerType>()) {
4627  BaseExpr = LHSExp;
4628  IndexExpr = RHSExp;
4629 
4630  // Use custom logic if this should be the pseudo-object subscript
4631  // expression.
4632  if (!LangOpts.isSubscriptPointerArithmetic())
4633  return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4634  nullptr);
4635 
4636  ResultType = PTy->getPointeeType();
4637  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4638  // Handle the uncommon case of "123[Ptr]".
4639  BaseExpr = RHSExp;
4640  IndexExpr = LHSExp;
4641  ResultType = PTy->getPointeeType();
4642  } else if (const ObjCObjectPointerType *PTy =
4643  RHSTy->getAs<ObjCObjectPointerType>()) {
4644  // Handle the uncommon case of "123[Ptr]".
4645  BaseExpr = RHSExp;
4646  IndexExpr = LHSExp;
4647  ResultType = PTy->getPointeeType();
4648  if (!LangOpts.isSubscriptPointerArithmetic()) {
4649  Diag(LLoc, diag::err_subscript_nonfragile_interface)
4650  << ResultType << BaseExpr->getSourceRange();
4651  return ExprError();
4652  }
4653  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4654  BaseExpr = LHSExp; // vectors: V[123]
4655  IndexExpr = RHSExp;
4656  // We apply C++ DR1213 to vector subscripting too.
4657  if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4658  ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4659  if (Materialized.isInvalid())
4660  return ExprError();
4661  LHSExp = Materialized.get();
4662  }
4663  VK = LHSExp->getValueKind();
4664  if (VK != VK_RValue)
4665  OK = OK_VectorComponent;
4666 
4667  ResultType = VTy->getElementType();
4668  QualType BaseType = BaseExpr->getType();
4669  Qualifiers BaseQuals = BaseType.getQualifiers();
4670  Qualifiers MemberQuals = ResultType.getQualifiers();
4671  Qualifiers Combined = BaseQuals + MemberQuals;
4672  if (Combined != MemberQuals)
4673  ResultType = Context.getQualifiedType(ResultType, Combined);
4674  } else if (LHSTy->isArrayType()) {
4675  // If we see an array that wasn't promoted by
4676  // DefaultFunctionArrayLvalueConversion, it must be an array that
4677  // wasn't promoted because of the C90 rule that doesn't
4678  // allow promoting non-lvalue arrays. Warn, then
4679  // force the promotion here.
4680  Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4681  << LHSExp->getSourceRange();
4682  LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4683  CK_ArrayToPointerDecay).get();
4684  LHSTy = LHSExp->getType();
4685 
4686  BaseExpr = LHSExp;
4687  IndexExpr = RHSExp;
4688  ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4689  } else if (RHSTy->isArrayType()) {
4690  // Same as previous, except for 123[f().a] case
4691  Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4692  << RHSExp->getSourceRange();
4693  RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4694  CK_ArrayToPointerDecay).get();
4695  RHSTy = RHSExp->getType();
4696 
4697  BaseExpr = RHSExp;
4698  IndexExpr = LHSExp;
4699  ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4700  } else {
4701  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4702  << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4703  }
4704  // C99 6.5.2.1p1
4705  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4706  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4707  << IndexExpr->getSourceRange());
4708 
4709  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4710  IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4711  && !IndexExpr->isTypeDependent())
4712  Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4713 
4714  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4715  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4716  // type. Note that Functions are not objects, and that (in C99 parlance)
4717  // incomplete types are not object types.
4718  if (ResultType->isFunctionType()) {
4719  Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4720  << ResultType << BaseExpr->getSourceRange();
4721  return ExprError();
4722  }
4723 
4724  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4725  // GNU extension: subscripting on pointer to void
4726  Diag(LLoc, diag::ext_gnu_subscript_void_type)
4727  << BaseExpr->getSourceRange();
4728 
4729  // C forbids expressions of unqualified void type from being l-values.
4730  // See IsCForbiddenLValueType.
4731  if (!ResultType.hasQualifiers()) VK = VK_RValue;
4732  } else if (!ResultType->isDependentType() &&
4733  RequireCompleteType(LLoc, ResultType,
4734  diag::err_subscript_incomplete_type, BaseExpr))
4735  return ExprError();
4736 
4737  assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4738  !ResultType.isCForbiddenLValueType());
4739 
4740  if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4741  FunctionScopes.size() > 1) {
4742  if (auto *TT =
4743  LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4744  for (auto I = FunctionScopes.rbegin(),
4745  E = std::prev(FunctionScopes.rend());
4746  I != E; ++I) {
4747  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4748  if (CSI == nullptr)
4749  break;
4750  DeclContext *DC = nullptr;
4751  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4752  DC = LSI->CallOperator;
4753  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4754  DC = CRSI->TheCapturedDecl;
4755  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4756  DC = BSI->TheDecl;
4757  if (DC) {
4758  if (DC->containsDecl(TT->getDecl()))
4759  break;
4761  Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4762  }
4763  }
4764  }
4765  }
4766 
4767  return new (Context)
4768  ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4769 }
4770 
4772  ParmVarDecl *Param) {
4773  if (Param->hasUnparsedDefaultArg()) {
4774  Diag(CallLoc,
4775  diag::err_use_of_default_argument_to_function_declared_later) <<
4776  FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4777  Diag(UnparsedDefaultArgLocs[Param],
4778  diag::note_default_argument_declared_here);
4779  return true;
4780  }
4781 
4782  if (Param->hasUninstantiatedDefaultArg()) {
4783  Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4784 
4786  *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4787 
4788  // Instantiate the expression.
4789  //
4790  // FIXME: Pass in a correct Pattern argument, otherwise
4791  // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4792  //
4793  // template<typename T>
4794  // struct A {
4795  // static int FooImpl();
4796  //
4797  // template<typename Tp>
4798  // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4799  // // template argument list [[T], [Tp]], should be [[Tp]].
4800  // friend A<Tp> Foo(int a);
4801  // };
4802  //
4803  // template<typename T>
4804  // A<T> Foo(int a = A<T>::FooImpl());
4805  MultiLevelTemplateArgumentList MutiLevelArgList
4806  = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4807 
4808  InstantiatingTemplate Inst(*this, CallLoc, Param,
4809  MutiLevelArgList.getInnermost());
4810  if (Inst.isInvalid())
4811  return true;
4812  if (Inst.isAlreadyInstantiating()) {
4813  Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4814  Param->setInvalidDecl();
4815  return true;
4816  }
4817 
4818  ExprResult Result;
4819  {
4820  // C++ [dcl.fct.default]p5:
4821  // The names in the [default argument] expression are bound, and
4822  // the semantic constraints are checked, at the point where the
4823  // default argument expression appears.
4824  ContextRAII SavedContext(*this, FD);
4825  LocalInstantiationScope Local(*this);
4826  Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4827  /*DirectInit*/false);
4828  }
4829  if (Result.isInvalid())
4830  return true;
4831 
4832  // Check the expression as an initializer for the parameter.
4833  InitializedEntity Entity
4834  = InitializedEntity::InitializeParameter(Context, Param);
4836  Param->getLocation(),
4837  /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4838  Expr *ResultE = Result.getAs<Expr>();
4839 
4840  InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4841  Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4842  if (Result.isInvalid())
4843  return true;
4844 
4845  Result =
4846  ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4847  /*DiscardedValue*/ false);
4848  if (Result.isInvalid())
4849  return true;
4850 
4851  // Remember the instantiated default argument.
4852  Param->setDefaultArg(Result.getAs<Expr>());
4853  if (ASTMutationListener *L = getASTMutationListener()) {
4854  L->DefaultArgumentInstantiated(Param);
4855  }
4856  }
4857 
4858  // If the default argument expression is not set yet, we are building it now.
4859  if (!Param->hasInit()) {
4860  Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4861  Param->setInvalidDecl();
4862  return true;
4863  }
4864 
4865  // If the default expression creates temporaries, we need to
4866  // push them to the current stack of expression temporaries so they'll
4867  // be properly destroyed.
4868  // FIXME: We should really be rebuilding the default argument with new
4869  // bound temporaries; see the comment in PR5810.
4870  // We don't need to do that with block decls, though, because
4871  // blocks in default argument expression can never capture anything.
4872  if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4873  // Set the "needs cleanups" bit regardless of whether there are
4874  // any explicit objects.
4875  Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4876 
4877  // Append all the objects to the cleanup list. Right now, this
4878  // should always be a no-op, because blocks in default argument
4879  // expressions should never be able to capture anything.
4880  assert(!Init->getNumObjects() &&
4881  "default argument expression has capturing blocks?");
4882  }
4883 
4884  // We already type-checked the argument, so we know it works.
4885  // Just mark all of the declarations in this potentially-evaluated expression
4886  // as being "referenced".
4888  *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4889  MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4890  /*SkipLocalVariables=*/true);
4891  return false;
4892 }
4893 
4895  FunctionDecl *FD, ParmVarDecl *Param) {
4896  if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4897  return ExprError();
4898  return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
4899 }
4900 
4903  Expr *Fn) {
4904  if (Proto && Proto->isVariadic()) {
4905  if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4906  return VariadicConstructor;
4907  else if (Fn && Fn->getType()->isBlockPointerType())
4908  return VariadicBlock;
4909  else if (FDecl) {
4910  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4911  if (Method->isInstance())
4912  return VariadicMethod;
4913  } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4914  return VariadicMethod;
4915  return VariadicFunction;
4916  }
4917  return VariadicDoesNotApply;
4918 }
4919 
4920 namespace {
4921 class FunctionCallCCC final : public FunctionCallFilterCCC {
4922 public:
4923  FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4924  unsigned NumArgs, MemberExpr *ME)
4925  : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4926  FunctionName(FuncName) {}
4927 
4928  bool ValidateCandidate(const TypoCorrection &candidate) override {
4929  if (!candidate.getCorrectionSpecifier() ||
4930  candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4931  return false;
4932  }
4933 
4934  return FunctionCallFilterCCC::ValidateCandidate(candidate);
4935  }
4936 
4937  std::unique_ptr<CorrectionCandidateCallback> clone() override {
4938  return llvm::make_unique<FunctionCallCCC>(*this);
4939  }
4940 
4941 private:
4942  const IdentifierInfo *const FunctionName;
4943 };
4944 }
4945 
4947  FunctionDecl *FDecl,
4948  ArrayRef<Expr *> Args) {
4949  MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4950  DeclarationName FuncName = FDecl->getDeclName();
4951  SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4952 
4953  FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4954  if (TypoCorrection Corrected = S.CorrectTypo(
4955  DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4956  S.getScopeForContext(S.CurContext), nullptr, CCC,
4958  if (NamedDecl *ND = Corrected.getFoundDecl()) {
4959  if (Corrected.isOverloaded()) {
4962  for (NamedDecl *CD : Corrected) {
4963  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4965  OCS);
4966  }
4967  switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4968  case OR_Success:
4969  ND = Best->FoundDecl;
4970  Corrected.setCorrectionDecl(ND);
4971  break;
4972  default:
4973  break;
4974  }
4975  }
4976  ND = ND->getUnderlyingDecl();
4977  if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4978  return Corrected;
4979  }
4980  }
4981  return TypoCorrection();
4982 }
4983 
4984 /// ConvertArgumentsForCall - Converts the arguments specified in
4985 /// Args/NumArgs to the parameter types of the function FDecl with
4986 /// function prototype Proto. Call is the call expression itself, and
4987 /// Fn is the function expression. For a C++ member function, this
4988 /// routine does not attempt to convert the object argument. Returns
4989 /// true if the call is ill-formed.
4990 bool
4992  FunctionDecl *FDecl,
4993  const FunctionProtoType *Proto,
4994  ArrayRef<Expr *> Args,
4995  SourceLocation RParenLoc,
4996  bool IsExecConfig) {
4997  // Bail out early if calling a builtin with custom typechecking.
4998  if (FDecl)
4999  if (unsigned ID = FDecl->getBuiltinID())
5000  if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5001  return false;
5002 
5003  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5004  // assignment, to the types of the corresponding parameter, ...
5005  unsigned NumParams = Proto->getNumParams();
5006  bool Invalid = false;
5007  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5008  unsigned FnKind = Fn->getType()->isBlockPointerType()
5009  ? 1 /* block */
5010  : (IsExecConfig ? 3 /* kernel function (exec config) */
5011  : 0 /* function */);
5012 
5013  // If too few arguments are available (and we don't have default
5014  // arguments for the remaining parameters), don't make the call.
5015  if (Args.size() < NumParams) {
5016  if (Args.size() < MinArgs) {
5017  TypoCorrection TC;
5018  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5019  unsigned diag_id =
5020  MinArgs == NumParams && !Proto->isVariadic()
5021  ? diag::err_typecheck_call_too_few_args_suggest
5022  : diag::err_typecheck_call_too_few_args_at_least_suggest;
5023  diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5024  << static_cast<unsigned>(Args.size())
5025  << TC.getCorrectionRange());
5026  } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5027  Diag(RParenLoc,
5028  MinArgs == NumParams && !Proto->isVariadic()
5029  ? diag::err_typecheck_call_too_few_args_one
5030  : diag::err_typecheck_call_too_few_args_at_least_one)
5031  << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5032  else
5033  Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5034  ? diag::err_typecheck_call_too_few_args
5035  : diag::err_typecheck_call_too_few_args_at_least)
5036  << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5037  << Fn->getSourceRange();
5038 
5039  // Emit the location of the prototype.
5040  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5041  Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5042 
5043  return true;
5044  }
5045  // We reserve space for the default arguments when we create
5046  // the call expression, before calling ConvertArgumentsForCall.
5047  assert((Call->getNumArgs() == NumParams) &&
5048  "We should have reserved space for the default arguments before!");
5049  }
5050 
5051  // If too many are passed and not variadic, error on the extras and drop
5052  // them.
5053  if (Args.size() > NumParams) {
5054  if (!Proto->isVariadic()) {
5055  TypoCorrection TC;
5056  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5057  unsigned diag_id =
5058  MinArgs == NumParams && !Proto->isVariadic()
5059  ? diag::err_typecheck_call_too_many_args_suggest
5060  : diag::err_typecheck_call_too_many_args_at_most_suggest;
5061  diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5062  << static_cast<unsigned>(Args.size())
5063  << TC.getCorrectionRange());
5064  } else if (NumParams == 1 && FDecl &&
5065  FDecl->getParamDecl(0)->getDeclName())
5066  Diag(Args[NumParams]->getBeginLoc(),
5067  MinArgs == NumParams
5068  ? diag::err_typecheck_call_too_many_args_one
5069  : diag::err_typecheck_call_too_many_args_at_most_one)
5070  << FnKind << FDecl->getParamDecl(0)
5071  << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5072  << SourceRange(Args[NumParams]->getBeginLoc(),
5073  Args.back()->getEndLoc());
5074  else
5075  Diag(Args[NumParams]->getBeginLoc(),
5076  MinArgs == NumParams
5077  ? diag::err_typecheck_call_too_many_args
5078  : diag::err_typecheck_call_too_many_args_at_most)
5079  << FnKind << NumParams << static_cast<unsigned>(Args.size())
5080  << Fn->getSourceRange()
5081  << SourceRange(Args[NumParams]->getBeginLoc(),
5082  Args.back()->getEndLoc());
5083 
5084  // Emit the location of the prototype.
5085  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5086  Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5087 
5088  // This deletes the extra arguments.
5089  Call->shrinkNumArgs(NumParams);
5090  return true;
5091  }
5092  }
5093  SmallVector<Expr *, 8> AllArgs;
5094  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5095 
5096  Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5097  AllArgs, CallType);
5098  if (Invalid)
5099  return true;
5100  unsigned TotalNumArgs = AllArgs.size();
5101  for (unsigned i = 0; i < TotalNumArgs; ++i)
5102  Call->setArg(i, AllArgs[i]);
5103 
5104  return false;
5105 }
5106 
5108  const FunctionProtoType *Proto,
5109  unsigned FirstParam, ArrayRef<Expr *> Args,
5110  SmallVectorImpl<Expr *> &AllArgs,
5111  VariadicCallType CallType, bool AllowExplicit,
5112  bool IsListInitialization) {
5113  unsigned NumParams = Proto->getNumParams();
5114  bool Invalid = false;
5115  size_t ArgIx = 0;
5116  // Continue to check argument types (even if we have too few/many args).
5117  for (unsigned i = FirstParam; i < NumParams; i++) {
5118  QualType ProtoArgType = Proto->getParamType(i);
5119 
5120  Expr *Arg;
5121  ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5122  if (ArgIx < Args.size()) {
5123  Arg = Args[ArgIx++];
5124 
5125  if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5126  diag::err_call_incomplete_argument, Arg))
5127  return true;
5128 
5129  // Strip the unbridged-cast placeholder expression off, if applicable.
5130  bool CFAudited = false;
5131  if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5132  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5133  (!Param || !Param->hasAttr<CFConsumedAttr>()))
5134  Arg = stripARCUnbridgedCast(Arg);
5135  else if (getLangOpts().ObjCAutoRefCount &&
5136  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5137  (!Param || !Param->hasAttr<CFConsumedAttr>()))
5138  CFAudited = true;
5139 
5140  if (Proto->getExtParameterInfo(i).isNoEscape())
5141  if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5142  BE->getBlockDecl()->setDoesNotEscape();
5143 
5144  InitializedEntity Entity =
5145  Param ? InitializedEntity::InitializeParameter(Context, Param,
5146  ProtoArgType)
5148  Context, ProtoArgType, Proto->isParamConsumed(i));
5149 
5150  // Remember that parameter belongs to a CF audited API.
5151  if (CFAudited)
5152  Entity.setParameterCFAudited();
5153 
5154  ExprResult ArgE = PerformCopyInitialization(
5155  Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5156  if (ArgE.isInvalid())
5157  return true;
5158 
5159  Arg = ArgE.getAs<Expr>();
5160  } else {
5161  assert(Param && "can't use default arguments without a known callee");
5162 
5163  ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5164  if (ArgExpr.isInvalid())
5165  return true;
5166 
5167  Arg = ArgExpr.getAs<Expr>();
5168  }
5169 
5170  // Check for array bounds violations for each argument to the call. This
5171  // check only triggers warnings when the argument isn't a more complex Expr
5172  // with its own checking, such as a BinaryOperator.
5173  CheckArrayAccess(Arg);
5174 
5175  // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5176  CheckStaticArrayArgument(CallLoc, Param, Arg);
5177 
5178  AllArgs.push_back(Arg);
5179  }
5180 
5181  // If this is a variadic call, handle args passed through "...".
5182  if (CallType != VariadicDoesNotApply) {
5183  // Assume that extern "C" functions with variadic arguments that
5184  // return __unknown_anytype aren't *really* variadic.
5185  if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5186  FDecl->isExternC()) {
5187  for (Expr *A : Args.slice(ArgIx)) {
5188  QualType paramType; // ignored
5189  ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5190  Invalid |= arg.isInvalid();
5191  AllArgs.push_back(arg.get());
5192  }
5193 
5194  // Otherwise do argument promotion, (C99 6.5.2.2p7).
5195  } else {
5196  for (Expr *A : Args.slice(ArgIx)) {
5197  ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5198  Invalid |= Arg.isInvalid();
5199  AllArgs.push_back(Arg.get());
5200  }
5201  }
5202 
5203  // Check for array bounds violations.
5204  for (Expr *A : Args.slice(ArgIx))
5205  CheckArrayAccess(A);
5206  }
5207  return Invalid;
5208 }
5209 
5211  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5212  if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5213  TL = DTL.getOriginalLoc();
5214  if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5215  S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5216  << ATL.getLocalSourceRange();
5217 }
5218 
5219 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5220 /// array parameter, check that it is non-null, and that if it is formed by
5221 /// array-to-pointer decay, the underlying array is sufficiently large.
5222 ///
5223 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5224 /// array type derivation, then for each call to the function, the value of the
5225 /// corresponding actual argument shall provide access to the first element of
5226 /// an array with at least as many elements as specified by the size expression.
5227 void
5229  ParmVarDecl *Param,
5230  const Expr *ArgExpr) {
5231  // Static array parameters are not supported in C++.
5232  if (!Param || getLangOpts().CPlusPlus)
5233  return;
5234 
5235  QualType OrigTy = Param->getOriginalType();
5236 
5237  const ArrayType *AT = Context.getAsArrayType(OrigTy);
5238  if (!AT || AT->getSizeModifier() != ArrayType::Static)
5239  return;
5240 
5241  if (ArgExpr->isNullPointerConstant(Context,
5243  Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5244  DiagnoseCalleeStaticArrayParam(*this, Param);
5245  return;
5246  }
5247 
5248  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5249  if (!CAT)
5250  return;
5251 
5252  const ConstantArrayType *ArgCAT =
5253  Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5254  if (!ArgCAT)
5255  return;
5256 
5257  if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5258  ArgCAT->getElementType())) {
5259  if (ArgCAT->getSize().ult(CAT->getSize())) {
5260  Diag(CallLoc, diag::warn_static_array_too_small)
5261  << ArgExpr->getSourceRange()
5262  << (unsigned)ArgCAT->getSize().getZExtValue()
5263  << (unsigned)CAT->getSize().getZExtValue() << 0;
5264  DiagnoseCalleeStaticArrayParam(*this, Param);
5265  }
5266  return;
5267  }
5268 
5269  Optional<CharUnits> ArgSize =
5270  getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5271  Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5272  if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5273  Diag(CallLoc, diag::warn_static_array_too_small)
5274  << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5275  << (unsigned)ParmSize->getQuantity() << 1;
5276  DiagnoseCalleeStaticArrayParam(*this, Param);
5277  }
5278 }
5279 
5280 /// Given a function expression of unknown-any type, try to rebuild it
5281 /// to have a function type.
5283 
5284 /// Is the given type a placeholder that we need to lower out
5285 /// immediately during argument processing?
5287  // Placeholders are never sugared.
5288  const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5289  if (!placeholder) return false;
5290 
5291  switch (placeholder->getKind()) {
5292  // Ignore all the non-placeholder types.
5293 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5294  case BuiltinType::Id:
5295 #include "clang/Basic/OpenCLImageTypes.def"
5296 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5297  case BuiltinType::Id:
5298 #include "clang/Basic/OpenCLExtensionTypes.def"
5299 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5300 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5301 #include "clang/AST/BuiltinTypes.def"
5302  return false;
5303 
5304  // We cannot lower out overload sets; they might validly be resolved
5305  // by the call machinery.
5306  case BuiltinType::Overload:
5307  return false;
5308 
5309  // Unbridged casts in ARC can be handled in some call positions and
5310  // should be left in place.
5311  case BuiltinType::ARCUnbridgedCast:
5312  return false;
5313 
5314  // Pseudo-objects should be converted as soon as possible.
5315  case BuiltinType::PseudoObject:
5316  return true;
5317 
5318  // The debugger mode could theoretically but currently does not try
5319  // to resolve unknown-typed arguments based on known parameter types.
5320  case BuiltinType::UnknownAny:
5321  return true;
5322 
5323  // These are always invalid as call arguments and should be reported.
5324  case BuiltinType::BoundMember:
5325  case BuiltinType::BuiltinFn:
5326  case BuiltinType::OMPArraySection:
5327  return true;
5328 
5329  }
5330  llvm_unreachable("bad builtin type kind");
5331 }
5332 
5333 /// Check an argument list for placeholders that we won't try to
5334 /// handle later.
5336  // Apply this processing to all the arguments at once instead of
5337  // dying at the first failure.
5338  bool hasInvalid = false;
5339  for (size_t i = 0, e = args.size(); i != e; i++) {
5340  if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5342  if (result.isInvalid()) hasInvalid = true;
5343  else args[i] = result.get();
5344  } else if (hasInvalid) {
5345  (void)S.CorrectDelayedTyposInExpr(args[i]);
5346  }
5347  }
5348  return hasInvalid;
5349 }
5350 
5351 /// If a builtin function has a pointer argument with no explicit address
5352 /// space, then it should be able to accept a pointer to any address
5353 /// space as input. In order to do this, we need to replace the
5354 /// standard builtin declaration with one that uses the same address space
5355 /// as the call.
5356 ///
5357 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5358 /// it does not contain any pointer arguments without
5359 /// an address space qualifer. Otherwise the rewritten
5360 /// FunctionDecl is returned.
5361 /// TODO: Handle pointer return types.
5363  FunctionDecl *FDecl,
5364  MultiExprArg ArgExprs) {
5365 
5366  QualType DeclType = FDecl->getType();
5367  const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5368 
5369  if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5370  !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5371  return nullptr;
5372 
5373  bool NeedsNewDecl = false;
5374  unsigned i = 0;
5375  SmallVector<QualType, 8> OverloadParams;
5376 
5377  for (QualType ParamType : FT->param_types()) {
5378 
5379  // Convert array arguments to pointer to simplify type lookup.
5380  ExprResult ArgRes =
5381  Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5382  if (ArgRes.isInvalid())
5383  return nullptr;
5384  Expr *Arg = ArgRes.get();
5385  QualType ArgType = Arg->getType();
5386  if (!ParamType->isPointerType() ||
5387  ParamType.getQualifiers().hasAddressSpace() ||
5388  !ArgType->isPointerType() ||
5389  !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5390  OverloadParams.push_back(ParamType);
5391  continue;
5392  }
5393 
5394  QualType PointeeType = ParamType->getPointeeType();
5395  if (PointeeType.getQualifiers().hasAddressSpace())
5396  continue;
5397 
5398  NeedsNewDecl = true;
5399  LangAS AS = ArgType->getPointeeType().getAddressSpace();
5400 
5401  PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5402  OverloadParams.push_back(Context.getPointerType(PointeeType));
5403  }
5404 
5405  if (!NeedsNewDecl)
5406  return nullptr;
5407 
5409  QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5410  OverloadParams, EPI);
5411  DeclContext *Parent = FDecl->getParent();
5412  FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5413  FDecl->getLocation(),
5414  FDecl->getLocation(),
5415  FDecl->getIdentifier(),
5416  OverloadTy,
5417  /*TInfo=*/nullptr,
5418  SC_Extern, false,
5419  /*hasPrototype=*/true);
5421  FT = cast<FunctionProtoType>(OverloadTy);
5422  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5423  QualType ParamType = FT->getParamType(i);
5424  ParmVarDecl *Parm =
5425  ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5426  SourceLocation(), nullptr, ParamType,
5427  /*TInfo=*/nullptr, SC_None, nullptr);
5428  Parm->setScopeInfo(0, i);
5429  Params.push_back(Parm);
5430  }
5431  OverloadDecl->setParams(Params);
5432  return OverloadDecl;
5433 }
5434 
5435 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5436  FunctionDecl *Callee,
5437  MultiExprArg ArgExprs) {
5438  // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5439  // similar attributes) really don't like it when functions are called with an
5440  // invalid number of args.
5441  if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5442  /*PartialOverloading=*/false) &&
5443  !Callee->isVariadic())
5444  return;
5445  if (Callee->getMinRequiredArguments() > ArgExprs.size())
5446  return;
5447 
5448  if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5449  S.Diag(Fn->getBeginLoc(),
5450  isa<CXXMethodDecl>(Callee)
5451  ? diag::err_ovl_no_viable_member_function_in_call
5452  : diag::err_ovl_no_viable_function_in_call)
5453  << Callee << Callee->getSourceRange();
5454  S.Diag(Callee->getLocation(),
5455  diag::note_ovl_candidate_disabled_by_function_cond_attr)
5456  << Attr->getCond()->getSourceRange() << Attr->getMessage();
5457  return;
5458  }
5459 }
5460 
5462  const UnresolvedMemberExpr *const UME, Sema &S) {
5463 
5464  const auto GetFunctionLevelDCIfCXXClass =
5465  [](Sema &S) -> const CXXRecordDecl * {
5466  const DeclContext *const DC = S.getFunctionLevelDeclContext();
5467  if (!DC || !DC->getParent())
5468  return nullptr;
5469 
5470  // If the call to some member function was made from within a member
5471  // function body 'M' return return 'M's parent.
5472  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5473  return MD->getParent()->getCanonicalDecl();
5474  // else the call was made from within a default member initializer of a
5475  // class, so return the class.
5476  if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5477  return RD->getCanonicalDecl();
5478  return nullptr;
5479  };
5480  // If our DeclContext is neither a member function nor a class (in the
5481  // case of a lambda in a default member initializer), we can't have an
5482  // enclosing 'this'.
5483 
5484  const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5485  if (!CurParentClass)
5486  return false;
5487 
5488  // The naming class for implicit member functions call is the class in which
5489  // name lookup starts.
5490  const CXXRecordDecl *const NamingClass =
5491  UME->getNamingClass()->getCanonicalDecl();
5492  assert(NamingClass && "Must have naming class even for implicit access");
5493 
5494  // If the unresolved member functions were found in a 'naming class' that is
5495  // related (either the same or derived from) to the class that contains the
5496  // member function that itself contained the implicit member access.
5497 
5498  return CurParentClass == NamingClass ||
5499  CurParentClass->isDerivedFrom(NamingClass);
5500 }
5501 
5502 static void
5504  Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5505 
5506  if (!UME)
5507  return;
5508 
5509  LambdaScopeInfo *const CurLSI = S.getCurLambda();
5510  // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5511  // already been captured, or if this is an implicit member function call (if
5512  // it isn't, an attempt to capture 'this' should already have been made).
5513  if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5514  !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5515  return;
5516 
5517  // Check if the naming class in which the unresolved members were found is
5518  // related (same as or is a base of) to the enclosing class.
5519 
5521  return;
5522 
5523 
5524  DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5525  // If the enclosing function is not dependent, then this lambda is
5526  // capture ready, so if we can capture this, do so.
5527  if (!EnclosingFunctionCtx->isDependentContext()) {
5528  // If the current lambda and all enclosing lambdas can capture 'this' -
5529  // then go ahead and capture 'this' (since our unresolved overload set
5530  // contains at least one non-static member function).
5531  if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5532  S.CheckCXXThisCapture(CallLoc);
5533  } else if (S.CurContext->isDependentContext()) {
5534  // ... since this is an implicit member reference, that might potentially
5535  // involve a 'this' capture, mark '