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