clang  8.0.0
SemaExpr.cpp
Go to the documentation of this file.
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/FixedPoint.h"
32 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/Support/ConvertUTF.h"
49 using namespace clang;
50 using namespace sema;
51 
52 /// Determine whether the use of this declaration is valid, without
53 /// emitting diagnostics.
54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
55  // See if this is an auto-typed variable whose initializer we are parsing.
56  if (ParsingInitForAutoVars.count(D))
57  return false;
58 
59  // See if this is a deleted function.
60  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
61  if (FD->isDeleted())
62  return false;
63 
64  // If the function has a deduced return type, and we can't deduce it,
65  // then we can't use it either.
66  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
67  DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
68  return false;
69 
70  // See if this is an aligned allocation/deallocation function that is
71  // unavailable.
72  if (TreatUnavailableAsInvalid &&
73  isUnavailableAlignedAllocationFunction(*FD))
74  return false;
75  }
76 
77  // See if this function is unavailable.
78  if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
79  cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
80  return false;
81 
82  return true;
83 }
84 
86  // Warn if this is used but marked unused.
87  if (const auto *A = D->getAttr<UnusedAttr>()) {
88  // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
89  // should diagnose them.
90  if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
91  A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
92  const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
93  if (DC && !DC->hasAttr<UnusedAttr>())
94  S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
95  }
96  }
97 }
98 
99 /// Emit a note explaining that this function is deleted.
101  assert(Decl->isDeleted());
102 
103  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
104 
105  if (Method && Method->isDeleted() && Method->isDefaulted()) {
106  // If the method was explicitly defaulted, point at that declaration.
107  if (!Method->isImplicit())
108  Diag(Decl->getLocation(), diag::note_implicitly_deleted);
109 
110  // Try to diagnose why this special member function was implicitly
111  // deleted. This might fail, if that reason no longer applies.
112  CXXSpecialMember CSM = getSpecialMember(Method);
113  if (CSM != CXXInvalid)
114  ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
115 
116  return;
117  }
118 
119  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
120  if (Ctor && Ctor->isInheritingConstructor())
121  return NoteDeletedInheritingConstructor(Ctor);
122 
123  Diag(Decl->getLocation(), diag::note_availability_specified_here)
124  << Decl << 1;
125 }
126 
127 /// Determine whether a FunctionDecl was ever declared with an
128 /// explicit storage class.
130  for (auto I : D->redecls()) {
131  if (I->getStorageClass() != SC_None)
132  return true;
133  }
134  return false;
135 }
136 
137 /// Check whether we're in an extern inline function and referring to a
138 /// variable or function with internal linkage (C11 6.7.4p3).
139 ///
140 /// This is only a warning because we used to silently accept this code, but
141 /// in many cases it will not behave correctly. This is not enabled in C++ mode
142 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
143 /// and so while there may still be user mistakes, most of the time we can't
144 /// prove that there are errors.
146  const NamedDecl *D,
147  SourceLocation Loc) {
148  // This is disabled under C++; there are too many ways for this to fire in
149  // contexts where the warning is a false positive, or where it is technically
150  // correct but benign.
151  if (S.getLangOpts().CPlusPlus)
152  return;
153 
154  // Check if this is an inlined function or method.
155  FunctionDecl *Current = S.getCurFunctionDecl();
156  if (!Current)
157  return;
158  if (!Current->isInlined())
159  return;
160  if (!Current->isExternallyVisible())
161  return;
162 
163  // Check if the decl has internal linkage.
164  if (D->getFormalLinkage() != InternalLinkage)
165  return;
166 
167  // Downgrade from ExtWarn to Extension if
168  // (1) the supposedly external inline function is in the main file,
169  // and probably won't be included anywhere else.
170  // (2) the thing we're referencing is a pure function.
171  // (3) the thing we're referencing is another inline function.
172  // This last can give us false negatives, but it's better than warning on
173  // wrappers for simple C library functions.
174  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
175  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
176  if (!DowngradeWarning && UsedFn)
177  DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
178 
179  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
180  : diag::ext_internal_in_extern_inline)
181  << /*IsVar=*/!UsedFn << D;
182 
184 
185  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
186  << D;
187 }
188 
190  const FunctionDecl *First = Cur->getFirstDecl();
191 
192  // Suggest "static" on the function, if possible.
193  if (!hasAnyExplicitStorageClass(First)) {
194  SourceLocation DeclBegin = First->getSourceRange().getBegin();
195  Diag(DeclBegin, diag::note_convert_inline_to_static)
196  << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
197  }
198 }
199 
200 /// Determine whether the use of this declaration is valid, and
201 /// emit any corresponding diagnostics.
202 ///
203 /// This routine diagnoses various problems with referencing
204 /// declarations that can occur when using a declaration. For example,
205 /// it might warn if a deprecated or unavailable declaration is being
206 /// used, or produce an error (and return true) if a C++0x deleted
207 /// function is being used.
208 ///
209 /// \returns true if there was an error (this declaration cannot be
210 /// referenced), false otherwise.
211 ///
213  const ObjCInterfaceDecl *UnknownObjCClass,
214  bool ObjCPropertyAccess,
215  bool AvoidPartialAvailabilityChecks,
216  ObjCInterfaceDecl *ClassReceiver) {
217  SourceLocation Loc = Locs.front();
218  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
219  // If there were any diagnostics suppressed by template argument deduction,
220  // emit them now.
221  auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
222  if (Pos != SuppressedDiagnostics.end()) {
223  for (const PartialDiagnosticAt &Suppressed : Pos->second)
224  Diag(Suppressed.first, Suppressed.second);
225 
226  // Clear out the list of suppressed diagnostics, so that we don't emit
227  // them again for this specialization. However, we don't obsolete this
228  // entry from the table, because we want to avoid ever emitting these
229  // diagnostics again.
230  Pos->second.clear();
231  }
232 
233  // C++ [basic.start.main]p3:
234  // The function 'main' shall not be used within a program.
235  if (cast<FunctionDecl>(D)->isMain())
236  Diag(Loc, diag::ext_main_used);
237 
238  diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
239  }
240 
241  // See if this is an auto-typed variable whose initializer we are parsing.
242  if (ParsingInitForAutoVars.count(D)) {
243  if (isa<BindingDecl>(D)) {
244  Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
245  << D->getDeclName();
246  } else {
247  Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
248  << D->getDeclName() << cast<VarDecl>(D)->getType();
249  }
250  return true;
251  }
252 
253  // See if this is a deleted function.
254  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
255  if (FD->isDeleted()) {
256  auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
257  if (Ctor && Ctor->isInheritingConstructor())
258  Diag(Loc, diag::err_deleted_inherited_ctor_use)
259  << Ctor->getParent()
260  << Ctor->getInheritedConstructor().getConstructor()->getParent();
261  else
262  Diag(Loc, diag::err_deleted_function_use);
263  NoteDeletedFunction(FD);
264  return true;
265  }
266 
267  // If the function has a deduced return type, and we can't deduce it,
268  // then we can't use it either.
269  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
270  DeduceReturnType(FD, Loc))
271  return true;
272 
273  if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
274  return true;
275  }
276 
277  if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
278  // Lambdas are only default-constructible or assignable in C++2a onwards.
279  if (MD->getParent()->isLambda() &&
280  ((isa<CXXConstructorDecl>(MD) &&
281  cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
282  MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
283  Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
284  << !isa<CXXConstructorDecl>(MD);
285  }
286  }
287 
288  auto getReferencedObjCProp = [](const NamedDecl *D) ->
289  const ObjCPropertyDecl * {
290  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
291  return MD->findPropertyDecl();
292  return nullptr;
293  };
294  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
295  if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
296  return true;
297  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
298  return true;
299  }
300 
301  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
302  // Only the variables omp_in and omp_out are allowed in the combiner.
303  // Only the variables omp_priv and omp_orig are allowed in the
304  // initializer-clause.
305  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
306  if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
307  isa<VarDecl>(D)) {
308  Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
309  << getCurFunction()->HasOMPDeclareReductionCombiner;
310  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
311  return true;
312  }
313 
314  DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
315  AvoidPartialAvailabilityChecks, ClassReceiver);
316 
317  DiagnoseUnusedOfDecl(*this, D, Loc);
318 
320 
321  return false;
322 }
323 
324 /// Retrieve the message suffix that should be added to a
325 /// diagnostic complaining about the given function being deleted or
326 /// unavailable.
328  std::string Message;
329  if (FD->getAvailability(&Message))
330  return ": " + Message;
331 
332  return std::string();
333 }
334 
335 /// DiagnoseSentinelCalls - This routine checks whether a call or
336 /// message-send is to a declaration with the sentinel attribute, and
337 /// if so, it checks that the requirements of the sentinel are
338 /// satisfied.
340  ArrayRef<Expr *> Args) {
341  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
342  if (!attr)
343  return;
344 
345  // The number of formal parameters of the declaration.
346  unsigned numFormalParams;
347 
348  // The kind of declaration. This is also an index into a %select in
349  // the diagnostic.
350  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
351 
352  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
353  numFormalParams = MD->param_size();
354  calleeType = CT_Method;
355  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
356  numFormalParams = FD->param_size();
357  calleeType = CT_Function;
358  } else if (isa<VarDecl>(D)) {
359  QualType type = cast<ValueDecl>(D)->getType();
360  const FunctionType *fn = nullptr;
361  if (const PointerType *ptr = type->getAs<PointerType>()) {
362  fn = ptr->getPointeeType()->getAs<FunctionType>();
363  if (!fn) return;
364  calleeType = CT_Function;
365  } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
366  fn = ptr->getPointeeType()->castAs<FunctionType>();
367  calleeType = CT_Block;
368  } else {
369  return;
370  }
371 
372  if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
373  numFormalParams = proto->getNumParams();
374  } else {
375  numFormalParams = 0;
376  }
377  } else {
378  return;
379  }
380 
381  // "nullPos" is the number of formal parameters at the end which
382  // effectively count as part of the variadic arguments. This is
383  // useful if you would prefer to not have *any* formal parameters,
384  // but the language forces you to have at least one.
385  unsigned nullPos = attr->getNullPos();
386  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
387  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
388 
389  // The number of arguments which should follow the sentinel.
390  unsigned numArgsAfterSentinel = attr->getSentinel();
391 
392  // If there aren't enough arguments for all the formal parameters,
393  // the sentinel, and the args after the sentinel, complain.
394  if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
395  Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
396  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
397  return;
398  }
399 
400  // Otherwise, find the sentinel expression.
401  Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
402  if (!sentinelExpr) return;
403  if (sentinelExpr->isValueDependent()) return;
404  if (Context.isSentinelNullExpr(sentinelExpr)) return;
405 
406  // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
407  // or 'NULL' if those are actually defined in the context. Only use
408  // 'nil' for ObjC methods, where it's much more likely that the
409  // variadic arguments form a list of object pointers.
410  SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
411  std::string NullValue;
412  if (calleeType == CT_Method && PP.isMacroDefined("nil"))
413  NullValue = "nil";
414  else if (getLangOpts().CPlusPlus11)
415  NullValue = "nullptr";
416  else if (PP.isMacroDefined("NULL"))
417  NullValue = "NULL";
418  else
419  NullValue = "(void*) 0";
420 
421  if (MissingNilLoc.isInvalid())
422  Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
423  else
424  Diag(MissingNilLoc, diag::warn_missing_sentinel)
425  << int(calleeType)
426  << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
427  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
428 }
429 
431  return E ? E->getSourceRange() : SourceRange();
432 }
433 
434 //===----------------------------------------------------------------------===//
435 // Standard Promotions and Conversions
436 //===----------------------------------------------------------------------===//
437 
438 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
440  // Handle any placeholder expressions which made it here.
441  if (E->getType()->isPlaceholderType()) {
442  ExprResult result = CheckPlaceholderExpr(E);
443  if (result.isInvalid()) return ExprError();
444  E = result.get();
445  }
446 
447  QualType Ty = E->getType();
448  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
449 
450  if (Ty->isFunctionType()) {
451  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
452  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
453  if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
454  return ExprError();
455 
456  E = ImpCastExprToType(E, Context.getPointerType(Ty),
457  CK_FunctionToPointerDecay).get();
458  } else if (Ty->isArrayType()) {
459  // In C90 mode, arrays only promote to pointers if the array expression is
460  // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
461  // type 'array of type' is converted to an expression that has type 'pointer
462  // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
463  // that has type 'array of type' ...". The relevant change is "an lvalue"
464  // (C90) to "an expression" (C99).
465  //
466  // C++ 4.2p1:
467  // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
468  // T" can be converted to an rvalue of type "pointer to T".
469  //
470  if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
471  E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
472  CK_ArrayToPointerDecay).get();
473  }
474  return E;
475 }
476 
478  // Check to see if we are dereferencing a null pointer. If so,
479  // and if not volatile-qualified, this is undefined behavior that the
480  // optimizer will delete, so warn about it. People sometimes try to use this
481  // to get a deterministic trap and are surprised by clang's behavior. This
482  // only handles the pattern "*null", which is a very syntactic check.
483  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
484  if (UO->getOpcode() == UO_Deref &&
485  UO->getSubExpr()->IgnoreParenCasts()->
486  isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
487  !UO->getType().isVolatileQualified()) {
488  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
489  S.PDiag(diag::warn_indirection_through_null)
490  << UO->getSubExpr()->getSourceRange());
491  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
492  S.PDiag(diag::note_indirection_through_null));
493  }
494 }
495 
496 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
497  SourceLocation AssignLoc,
498  const Expr* RHS) {
499  const ObjCIvarDecl *IV = OIRE->getDecl();
500  if (!IV)
501  return;
502 
503  DeclarationName MemberName = IV->getDeclName();
504  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
505  if (!Member || !Member->isStr("isa"))
506  return;
507 
508  const Expr *Base = OIRE->getBase();
509  QualType BaseType = Base->getType();
510  if (OIRE->isArrow())
511  BaseType = BaseType->getPointeeType();
512  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
513  if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
514  ObjCInterfaceDecl *ClassDeclared = nullptr;
515  ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
516  if (!ClassDeclared->getSuperClass()
517  && (*ClassDeclared->ivar_begin()) == IV) {
518  if (RHS) {
519  NamedDecl *ObjectSetClass =
521  &S.Context.Idents.get("object_setClass"),
523  if (ObjectSetClass) {
524  SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
525  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
527  "object_setClass(")
529  SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
530  << FixItHint::CreateInsertion(RHSLocEnd, ")");
531  }
532  else
533  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
534  } else {
535  NamedDecl *ObjectGetClass =
537  &S.Context.Idents.get("object_getClass"),
539  if (ObjectGetClass)
540  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
542  "object_getClass(")
544  SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
545  else
546  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
547  }
548  S.Diag(IV->getLocation(), diag::note_ivar_decl);
549  }
550  }
551 }
552 
554  // Handle any placeholder expressions which made it here.
555  if (E->getType()->isPlaceholderType()) {
556  ExprResult result = CheckPlaceholderExpr(E);
557  if (result.isInvalid()) return ExprError();
558  E = result.get();
559  }
560 
561  // C++ [conv.lval]p1:
562  // A glvalue of a non-function, non-array type T can be
563  // converted to a prvalue.
564  if (!E->isGLValue()) return E;
565 
566  QualType T = E->getType();
567  assert(!T.isNull() && "r-value conversion on typeless expression?");
568 
569  // We don't want to throw lvalue-to-rvalue casts on top of
570  // expressions of certain types in C++.
571  if (getLangOpts().CPlusPlus &&
572  (E->getType() == Context.OverloadTy ||
573  T->isDependentType() ||
574  T->isRecordType()))
575  return E;
576 
577  // The C standard is actually really unclear on this point, and
578  // DR106 tells us what the result should be but not why. It's
579  // generally best to say that void types just doesn't undergo
580  // lvalue-to-rvalue at all. Note that expressions of unqualified
581  // 'void' type are never l-values, but qualified void can be.
582  if (T->isVoidType())
583  return E;
584 
585  // OpenCL usually rejects direct accesses to values of 'half' type.
586  if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
587  T->isHalfType()) {
588  Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
589  << 0 << T;
590  return ExprError();
591  }
592 
594  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
595  NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
596  &Context.Idents.get("object_getClass"),
597  SourceLocation(), LookupOrdinaryName);
598  if (ObjectGetClass)
599  Diag(E->getExprLoc(), diag::warn_objc_isa_use)
600  << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
602  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
603  else
604  Diag(E->getExprLoc(), diag::warn_objc_isa_use);
605  }
606  else if (const ObjCIvarRefExpr *OIRE =
607  dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
608  DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
609 
610  // C++ [conv.lval]p1:
611  // [...] If T is a non-class type, the type of the prvalue is the
612  // cv-unqualified version of T. Otherwise, the type of the
613  // rvalue is T.
614  //
615  // C99 6.3.2.1p2:
616  // If the lvalue has qualified type, the value has the unqualified
617  // version of the type of the lvalue; otherwise, the value has the
618  // type of the lvalue.
619  if (T.hasQualifiers())
620  T = T.getUnqualifiedType();
621 
622  // Under the MS ABI, lock down the inheritance model now.
623  if (T->isMemberPointerType() &&
624  Context.getTargetInfo().getCXXABI().isMicrosoft())
625  (void)isCompleteType(E->getExprLoc(), T);
626 
627  UpdateMarkingForLValueToRValue(E);
628 
629  // Loading a __weak object implicitly retains the value, so we need a cleanup to
630  // balance that.
632  Cleanup.setExprNeedsCleanups(true);
633 
634  ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
635  nullptr, VK_RValue);
636 
637  // C11 6.3.2.1p2:
638  // ... if the lvalue has atomic type, the value has the non-atomic version
639  // of the type of the lvalue ...
640  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
641  T = Atomic->getValueType().getUnqualifiedType();
642  Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
643  nullptr, VK_RValue);
644  }
645 
646  return Res;
647 }
648 
650  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
651  if (Res.isInvalid())
652  return ExprError();
653  Res = DefaultLvalueConversion(Res.get());
654  if (Res.isInvalid())
655  return ExprError();
656  return Res;
657 }
658 
659 /// CallExprUnaryConversions - a special case of an unary conversion
660 /// performed on a function designator of a call expression.
662  QualType Ty = E->getType();
663  ExprResult Res = E;
664  // Only do implicit cast for a function type, but not for a pointer
665  // to function type.
666  if (Ty->isFunctionType()) {
667  Res = ImpCastExprToType(E, Context.getPointerType(Ty),
668  CK_FunctionToPointerDecay).get();
669  if (Res.isInvalid())
670  return ExprError();
671  }
672  Res = DefaultLvalueConversion(Res.get());
673  if (Res.isInvalid())
674  return ExprError();
675  return Res.get();
676 }
677 
678 /// UsualUnaryConversions - Performs various conversions that are common to most
679 /// operators (C99 6.3). The conversions of array and function types are
680 /// sometimes suppressed. For example, the array->pointer conversion doesn't
681 /// apply if the array is an argument to the sizeof or address (&) operators.
682 /// In these instances, this routine should *not* be called.
684  // First, convert to an r-value.
685  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
686  if (Res.isInvalid())
687  return ExprError();
688  E = Res.get();
689 
690  QualType Ty = E->getType();
691  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
692 
693  // Half FP have to be promoted to float unless it is natively supported
694  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
695  return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
696 
697  // Try to perform integral promotions if the object has a theoretically
698  // promotable type.
700  // C99 6.3.1.1p2:
701  //
702  // The following may be used in an expression wherever an int or
703  // unsigned int may be used:
704  // - an object or expression with an integer type whose integer
705  // conversion rank is less than or equal to the rank of int
706  // and unsigned int.
707  // - A bit-field of type _Bool, int, signed int, or unsigned int.
708  //
709  // If an int can represent all values of the original type, the
710  // value is converted to an int; otherwise, it is converted to an
711  // unsigned int. These are called the integer promotions. All
712  // other types are unchanged by the integer promotions.
713 
714  QualType PTy = Context.isPromotableBitField(E);
715  if (!PTy.isNull()) {
716  E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
717  return E;
718  }
719  if (Ty->isPromotableIntegerType()) {
720  QualType PT = Context.getPromotedIntegerType(Ty);
721  E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
722  return E;
723  }
724  }
725  return E;
726 }
727 
728 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
729 /// do not have a prototype. Arguments that have type float or __fp16
730 /// are promoted to double. All other argument types are converted by
731 /// UsualUnaryConversions().
733  QualType Ty = E->getType();
734  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
735 
736  ExprResult Res = UsualUnaryConversions(E);
737  if (Res.isInvalid())
738  return ExprError();
739  E = Res.get();
740 
741  QualType ScalarTy = Ty;
742  unsigned NumElts = 0;
743  if (const ExtVectorType *VecTy = Ty->getAs<ExtVectorType>()) {
744  NumElts = VecTy->getNumElements();
745  ScalarTy = VecTy->getElementType();
746  }
747 
748  // If this is a 'float' or '__fp16' (CVR qualified or typedef)
749  // promote to double.
750  // Note that default argument promotion applies only to float (and
751  // half/fp16); it does not apply to _Float16.
752  const BuiltinType *BTy = ScalarTy->getAs<BuiltinType>();
753  if (BTy && (BTy->getKind() == BuiltinType::Half ||
754  BTy->getKind() == BuiltinType::Float)) {
755  if (getLangOpts().OpenCL &&
756  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
757  if (BTy->getKind() == BuiltinType::Half) {
758  QualType Ty = Context.FloatTy;
759  if (NumElts != 0)
760  Ty = Context.getExtVectorType(Ty, NumElts);
761  E = ImpCastExprToType(E, Ty, CK_FloatingCast).get();
762  }
763  } else {
764  QualType Ty = Context.DoubleTy;
765  if (NumElts != 0)
766  Ty = Context.getExtVectorType(Ty, NumElts);
767  E = ImpCastExprToType(E, Ty, CK_FloatingCast).get();
768  }
769  }
770 
771  // C++ performs lvalue-to-rvalue conversion as a default argument
772  // promotion, even on class types, but note:
773  // C++11 [conv.lval]p2:
774  // When an lvalue-to-rvalue conversion occurs in an unevaluated
775  // operand or a subexpression thereof the value contained in the
776  // referenced object is not accessed. Otherwise, if the glvalue
777  // has a class type, the conversion copy-initializes a temporary
778  // of type T from the glvalue and the result of the conversion
779  // is a prvalue for the temporary.
780  // FIXME: add some way to gate this entire thing for correctness in
781  // potentially potentially evaluated contexts.
782  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
783  ExprResult Temp = PerformCopyInitialization(
785  E->getExprLoc(), E);
786  if (Temp.isInvalid())
787  return ExprError();
788  E = Temp.get();
789  }
790 
791  return E;
792 }
793 
794 /// Determine the degree of POD-ness for an expression.
795 /// Incomplete types are considered POD, since this check can be performed
796 /// when we're in an unevaluated context.
798  if (Ty->isIncompleteType()) {
799  // C++11 [expr.call]p7:
800  // After these conversions, if the argument does not have arithmetic,
801  // enumeration, pointer, pointer to member, or class type, the program
802  // is ill-formed.
803  //
804  // Since we've already performed array-to-pointer and function-to-pointer
805  // decay, the only such type in C++ is cv void. This also handles
806  // initializer lists as variadic arguments.
807  if (Ty->isVoidType())
808  return VAK_Invalid;
809 
810  if (Ty->isObjCObjectType())
811  return VAK_Invalid;
812  return VAK_Valid;
813  }
814 
816  return VAK_Invalid;
817 
818  if (Ty.isCXX98PODType(Context))
819  return VAK_Valid;
820 
821  // C++11 [expr.call]p7:
822  // Passing a potentially-evaluated argument of class type (Clause 9)
823  // having a non-trivial copy constructor, a non-trivial move constructor,
824  // or a non-trivial destructor, with no corresponding parameter,
825  // is conditionally-supported with implementation-defined semantics.
826  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
827  if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
828  if (!Record->hasNonTrivialCopyConstructor() &&
829  !Record->hasNonTrivialMoveConstructor() &&
830  !Record->hasNonTrivialDestructor())
831  return VAK_ValidInCXX11;
832 
833  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
834  return VAK_Valid;
835 
836  if (Ty->isObjCObjectType())
837  return VAK_Invalid;
838 
839  if (getLangOpts().MSVCCompat)
840  return VAK_MSVCUndefined;
841 
842  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
843  // permitted to reject them. We should consider doing so.
844  return VAK_Undefined;
845 }
846 
848  // Don't allow one to pass an Objective-C interface to a vararg.
849  const QualType &Ty = E->getType();
850  VarArgKind VAK = isValidVarArgType(Ty);
851 
852  // Complain about passing non-POD types through varargs.
853  switch (VAK) {
854  case VAK_ValidInCXX11:
855  DiagRuntimeBehavior(
856  E->getBeginLoc(), nullptr,
857  PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
858  LLVM_FALLTHROUGH;
859  case VAK_Valid:
860  if (Ty->isRecordType()) {
861  // This is unlikely to be what the user intended. If the class has a
862  // 'c_str' member function, the user probably meant to call that.
863  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
864  PDiag(diag::warn_pass_class_arg_to_vararg)
865  << Ty << CT << hasCStrMethod(E) << ".c_str()");
866  }
867  break;
868 
869  case VAK_Undefined:
870  case VAK_MSVCUndefined:
871  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
872  PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
873  << getLangOpts().CPlusPlus11 << Ty << CT);
874  break;
875 
876  case VAK_Invalid:
878  Diag(E->getBeginLoc(),
879  diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
880  << Ty << CT;
881  else if (Ty->isObjCObjectType())
882  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
883  PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
884  << Ty << CT);
885  else
886  Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
887  << isa<InitListExpr>(E) << Ty << CT;
888  break;
889  }
890 }
891 
892 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
893 /// will create a trap if the resulting type is not a POD type.
895  FunctionDecl *FDecl) {
896  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
897  // Strip the unbridged-cast placeholder expression off, if applicable.
898  if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
899  (CT == VariadicMethod ||
900  (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
901  E = stripARCUnbridgedCast(E);
902 
903  // Otherwise, do normal placeholder checking.
904  } else {
905  ExprResult ExprRes = CheckPlaceholderExpr(E);
906  if (ExprRes.isInvalid())
907  return ExprError();
908  E = ExprRes.get();
909  }
910  }
911 
912  ExprResult ExprRes = DefaultArgumentPromotion(E);
913  if (ExprRes.isInvalid())
914  return ExprError();
915  E = ExprRes.get();
916 
917  // Diagnostics regarding non-POD argument types are
918  // emitted along with format string checking in Sema::CheckFunctionCall().
919  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
920  // Turn this into a trap.
921  CXXScopeSpec SS;
922  SourceLocation TemplateKWLoc;
923  UnqualifiedId Name;
924  Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
925  E->getBeginLoc());
926  ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
927  Name, true, false);
928  if (TrapFn.isInvalid())
929  return ExprError();
930 
931  ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
932  None, E->getEndLoc());
933  if (Call.isInvalid())
934  return ExprError();
935 
936  ExprResult Comma =
937  ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
938  if (Comma.isInvalid())
939  return ExprError();
940  return Comma.get();
941  }
942 
943  if (!getLangOpts().CPlusPlus &&
944  RequireCompleteType(E->getExprLoc(), E->getType(),
945  diag::err_call_incomplete_argument))
946  return ExprError();
947 
948  return E;
949 }
950 
951 /// Converts an integer to complex float type. Helper function of
952 /// UsualArithmeticConversions()
953 ///
954 /// \return false if the integer expression is an integer type and is
955 /// successfully converted to the complex type.
957  ExprResult &ComplexExpr,
958  QualType IntTy,
959  QualType ComplexTy,
960  bool SkipCast) {
961  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
962  if (SkipCast) return false;
963  if (IntTy->isIntegerType()) {
964  QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
965  IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
966  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
967  CK_FloatingRealToComplex);
968  } else {
969  assert(IntTy->isComplexIntegerType());
970  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
971  CK_IntegralComplexToFloatingComplex);
972  }
973  return false;
974 }
975 
976 /// Handle arithmetic conversion with complex types. Helper function of
977 /// UsualArithmeticConversions()
979  ExprResult &RHS, QualType LHSType,
980  QualType RHSType,
981  bool IsCompAssign) {
982  // if we have an integer operand, the result is the complex type.
983  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
984  /*skipCast*/false))
985  return LHSType;
986  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
987  /*skipCast*/IsCompAssign))
988  return RHSType;
989 
990  // This handles complex/complex, complex/float, or float/complex.
991  // When both operands are complex, the shorter operand is converted to the
992  // type of the longer, and that is the type of the result. This corresponds
993  // to what is done when combining two real floating-point operands.
994  // The fun begins when size promotion occur across type domains.
995  // From H&S 6.3.4: When one operand is complex and the other is a real
996  // floating-point type, the less precise type is converted, within it's
997  // real or complex domain, to the precision of the other type. For example,
998  // when combining a "long double" with a "double _Complex", the
999  // "double _Complex" is promoted to "long double _Complex".
1000 
1001  // Compute the rank of the two types, regardless of whether they are complex.
1002  int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1003 
1004  auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1005  auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1006  QualType LHSElementType =
1007  LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1008  QualType RHSElementType =
1009  RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1010 
1011  QualType ResultType = S.Context.getComplexType(LHSElementType);
1012  if (Order < 0) {
1013  // Promote the precision of the LHS if not an assignment.
1014  ResultType = S.Context.getComplexType(RHSElementType);
1015  if (!IsCompAssign) {
1016  if (LHSComplexType)
1017  LHS =
1018  S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1019  else
1020  LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1021  }
1022  } else if (Order > 0) {
1023  // Promote the precision of the RHS.
1024  if (RHSComplexType)
1025  RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1026  else
1027  RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1028  }
1029  return ResultType;
1030 }
1031 
1032 /// Handle arithmetic conversion from integer to float. Helper function
1033 /// of UsualArithmeticConversions()
1035  ExprResult &IntExpr,
1036  QualType FloatTy, QualType IntTy,
1037  bool ConvertFloat, bool ConvertInt) {
1038  if (IntTy->isIntegerType()) {
1039  if (ConvertInt)
1040  // Convert intExpr to the lhs floating point type.
1041  IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1042  CK_IntegralToFloating);
1043  return FloatTy;
1044  }
1045 
1046  // Convert both sides to the appropriate complex float.
1047  assert(IntTy->isComplexIntegerType());
1048  QualType result = S.Context.getComplexType(FloatTy);
1049 
1050  // _Complex int -> _Complex float
1051  if (ConvertInt)
1052  IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1053  CK_IntegralComplexToFloatingComplex);
1054 
1055  // float -> _Complex float
1056  if (ConvertFloat)
1057  FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1058  CK_FloatingRealToComplex);
1059 
1060  return result;
1061 }
1062 
1063 /// Handle arithmethic conversion with floating point types. Helper
1064 /// function of UsualArithmeticConversions()
1066  ExprResult &RHS, QualType LHSType,
1067  QualType RHSType, bool IsCompAssign) {
1068  bool LHSFloat = LHSType->isRealFloatingType();
1069  bool RHSFloat = RHSType->isRealFloatingType();
1070 
1071  // If we have two real floating types, convert the smaller operand
1072  // to the bigger result.
1073  if (LHSFloat && RHSFloat) {
1074  int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1075  if (order > 0) {
1076  RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1077  return LHSType;
1078  }
1079 
1080  assert(order < 0 && "illegal float comparison");
1081  if (!IsCompAssign)
1082  LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1083  return RHSType;
1084  }
1085 
1086  if (LHSFloat) {
1087  // Half FP has to be promoted to float unless it is natively supported
1088  if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1089  LHSType = S.Context.FloatTy;
1090 
1091  return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1092  /*convertFloat=*/!IsCompAssign,
1093  /*convertInt=*/ true);
1094  }
1095  assert(RHSFloat);
1096  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1097  /*convertInt=*/ true,
1098  /*convertFloat=*/!IsCompAssign);
1099 }
1100 
1101 /// Diagnose attempts to convert between __float128 and long double if
1102 /// there is no support for such conversion. Helper function of
1103 /// UsualArithmeticConversions().
1104 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1105  QualType RHSType) {
1106  /* No issue converting if at least one of the types is not a floating point
1107  type or the two types have the same rank.
1108  */
1109  if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1110  S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1111  return false;
1112 
1113  assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1114  "The remaining types must be floating point types.");
1115 
1116  auto *LHSComplex = LHSType->getAs<ComplexType>();
1117  auto *RHSComplex = RHSType->getAs<ComplexType>();
1118 
1119  QualType LHSElemType = LHSComplex ?
1120  LHSComplex->getElementType() : LHSType;
1121  QualType RHSElemType = RHSComplex ?
1122  RHSComplex->getElementType() : RHSType;
1123 
1124  // No issue if the two types have the same representation
1125  if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1126  &S.Context.getFloatTypeSemantics(RHSElemType))
1127  return false;
1128 
1129  bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1130  RHSElemType == S.Context.LongDoubleTy);
1131  Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1132  RHSElemType == S.Context.Float128Ty);
1133 
1134  // We've handled the situation where __float128 and long double have the same
1135  // representation. We allow all conversions for all possible long double types
1136  // except PPC's double double.
1137  return Float128AndLongDouble &&
1139  &llvm::APFloat::PPCDoubleDouble());
1140 }
1141 
1142 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1143 
1144 namespace {
1145 /// These helper callbacks are placed in an anonymous namespace to
1146 /// permit their use as function template parameters.
1147 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1148  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1149 }
1150 
1151 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1152  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1153  CK_IntegralComplexCast);
1154 }
1155 }
1156 
1157 /// Handle integer arithmetic conversions. Helper function of
1158 /// UsualArithmeticConversions()
1159 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1161  ExprResult &RHS, QualType LHSType,
1162  QualType RHSType, bool IsCompAssign) {
1163  // The rules for this case are in C99 6.3.1.8
1164  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1165  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1166  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1167  if (LHSSigned == RHSSigned) {
1168  // Same signedness; use the higher-ranked type
1169  if (order >= 0) {
1170  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1171  return LHSType;
1172  } else if (!IsCompAssign)
1173  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1174  return RHSType;
1175  } else if (order != (LHSSigned ? 1 : -1)) {
1176  // The unsigned type has greater than or equal rank to the
1177  // signed type, so use the unsigned type
1178  if (RHSSigned) {
1179  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1180  return LHSType;
1181  } else if (!IsCompAssign)
1182  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1183  return RHSType;
1184  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1185  // The two types are different widths; if we are here, that
1186  // means the signed type is larger than the unsigned type, so
1187  // use the signed type.
1188  if (LHSSigned) {
1189  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1190  return LHSType;
1191  } else if (!IsCompAssign)
1192  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1193  return RHSType;
1194  } else {
1195  // The signed type is higher-ranked than the unsigned type,
1196  // but isn't actually any bigger (like unsigned int and long
1197  // on most 32-bit systems). Use the unsigned type corresponding
1198  // to the signed type.
1199  QualType result =
1200  S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1201  RHS = (*doRHSCast)(S, RHS.get(), result);
1202  if (!IsCompAssign)
1203  LHS = (*doLHSCast)(S, LHS.get(), result);
1204  return result;
1205  }
1206 }
1207 
1208 /// Handle conversions with GCC complex int extension. Helper function
1209 /// of UsualArithmeticConversions()
1211  ExprResult &RHS, QualType LHSType,
1212  QualType RHSType,
1213  bool IsCompAssign) {
1214  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1215  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1216 
1217  if (LHSComplexInt && RHSComplexInt) {
1218  QualType LHSEltType = LHSComplexInt->getElementType();
1219  QualType RHSEltType = RHSComplexInt->getElementType();
1220  QualType ScalarType =
1221  handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1222  (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1223 
1224  return S.Context.getComplexType(ScalarType);
1225  }
1226 
1227  if (LHSComplexInt) {
1228  QualType LHSEltType = LHSComplexInt->getElementType();
1229  QualType ScalarType =
1230  handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1231  (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1232  QualType ComplexType = S.Context.getComplexType(ScalarType);
1233  RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1234  CK_IntegralRealToComplex);
1235 
1236  return ComplexType;
1237  }
1238 
1239  assert(RHSComplexInt);
1240 
1241  QualType RHSEltType = RHSComplexInt->getElementType();
1242  QualType ScalarType =
1243  handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1244  (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1245  QualType ComplexType = S.Context.getComplexType(ScalarType);
1246 
1247  if (!IsCompAssign)
1248  LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1249  CK_IntegralRealToComplex);
1250  return ComplexType;
1251 }
1252 
1253 /// UsualArithmeticConversions - Performs various conversions that are common to
1254 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1255 /// routine returns the first non-arithmetic type found. The client is
1256 /// responsible for emitting appropriate error diagnostics.
1258  bool IsCompAssign) {
1259  if (!IsCompAssign) {
1260  LHS = UsualUnaryConversions(LHS.get());
1261  if (LHS.isInvalid())
1262  return QualType();
1263  }
1264 
1265  RHS = UsualUnaryConversions(RHS.get());
1266  if (RHS.isInvalid())
1267  return QualType();
1268 
1269  // For conversion purposes, we ignore any qualifiers.
1270  // For example, "const float" and "float" are equivalent.
1271  QualType LHSType =
1272  Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1273  QualType RHSType =
1274  Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1275 
1276  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1277  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1278  LHSType = AtomicLHS->getValueType();
1279 
1280  // If both types are identical, no conversion is needed.
1281  if (LHSType == RHSType)
1282  return LHSType;
1283 
1284  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1285  // The caller can deal with this (e.g. pointer + int).
1286  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1287  return QualType();
1288 
1289  // Apply unary and bitfield promotions to the LHS's type.
1290  QualType LHSUnpromotedType = LHSType;
1291  if (LHSType->isPromotableIntegerType())
1292  LHSType = Context.getPromotedIntegerType(LHSType);
1293  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1294  if (!LHSBitfieldPromoteTy.isNull())
1295  LHSType = LHSBitfieldPromoteTy;
1296  if (LHSType != LHSUnpromotedType && !IsCompAssign)
1297  LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1298 
1299  // If both types are identical, no conversion is needed.
1300  if (LHSType == RHSType)
1301  return LHSType;
1302 
1303  // At this point, we have two different arithmetic types.
1304 
1305  // Diagnose attempts to convert between __float128 and long double where
1306  // such conversions currently can't be handled.
1307  if (unsupportedTypeConversion(*this, LHSType, RHSType))
1308  return QualType();
1309 
1310  // Handle complex types first (C99 6.3.1.8p1).
1311  if (LHSType->isComplexType() || RHSType->isComplexType())
1312  return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1313  IsCompAssign);
1314 
1315  // Now handle "real" floating types (i.e. float, double, long double).
1316  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1317  return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1318  IsCompAssign);
1319 
1320  // Handle GCC complex int extension.
1321  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1322  return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1323  IsCompAssign);
1324 
1325  // Finally, we have two differing integer types.
1326  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1327  (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1328 }
1329 
1330 
1331 //===----------------------------------------------------------------------===//
1332 // Semantic Analysis for various Expression Types
1333 //===----------------------------------------------------------------------===//
1334 
1335 
1336 ExprResult
1338  SourceLocation DefaultLoc,
1339  SourceLocation RParenLoc,
1340  Expr *ControllingExpr,
1341  ArrayRef<ParsedType> ArgTypes,
1342  ArrayRef<Expr *> ArgExprs) {
1343  unsigned NumAssocs = ArgTypes.size();
1344  assert(NumAssocs == ArgExprs.size());
1345 
1346  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1347  for (unsigned i = 0; i < NumAssocs; ++i) {
1348  if (ArgTypes[i])
1349  (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1350  else
1351  Types[i] = nullptr;
1352  }
1353 
1354  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1355  ControllingExpr,
1356  llvm::makeArrayRef(Types, NumAssocs),
1357  ArgExprs);
1358  delete [] Types;
1359  return ER;
1360 }
1361 
1362 ExprResult
1364  SourceLocation DefaultLoc,
1365  SourceLocation RParenLoc,
1366  Expr *ControllingExpr,
1368  ArrayRef<Expr *> Exprs) {
1369  unsigned NumAssocs = Types.size();
1370  assert(NumAssocs == Exprs.size());
1371 
1372  // Decay and strip qualifiers for the controlling expression type, and handle
1373  // placeholder type replacement. See committee discussion from WG14 DR423.
1374  {
1377  ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1378  if (R.isInvalid())
1379  return ExprError();
1380  ControllingExpr = R.get();
1381  }
1382 
1383  // The controlling expression is an unevaluated operand, so side effects are
1384  // likely unintended.
1385  if (!inTemplateInstantiation() &&
1386  ControllingExpr->HasSideEffects(Context, false))
1387  Diag(ControllingExpr->getExprLoc(),
1388  diag::warn_side_effects_unevaluated_context);
1389 
1390  bool TypeErrorFound = false,
1391  IsResultDependent = ControllingExpr->isTypeDependent(),
1392  ContainsUnexpandedParameterPack
1393  = ControllingExpr->containsUnexpandedParameterPack();
1394 
1395  for (unsigned i = 0; i < NumAssocs; ++i) {
1396  if (Exprs[i]->containsUnexpandedParameterPack())
1397  ContainsUnexpandedParameterPack = true;
1398 
1399  if (Types[i]) {
1400  if (Types[i]->getType()->containsUnexpandedParameterPack())
1401  ContainsUnexpandedParameterPack = true;
1402 
1403  if (Types[i]->getType()->isDependentType()) {
1404  IsResultDependent = true;
1405  } else {
1406  // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1407  // complete object type other than a variably modified type."
1408  unsigned D = 0;
1409  if (Types[i]->getType()->isIncompleteType())
1410  D = diag::err_assoc_type_incomplete;
1411  else if (!Types[i]->getType()->isObjectType())
1412  D = diag::err_assoc_type_nonobject;
1413  else if (Types[i]->getType()->isVariablyModifiedType())
1414  D = diag::err_assoc_type_variably_modified;
1415 
1416  if (D != 0) {
1417  Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1418  << Types[i]->getTypeLoc().getSourceRange()
1419  << Types[i]->getType();
1420  TypeErrorFound = true;
1421  }
1422 
1423  // C11 6.5.1.1p2 "No two generic associations in the same generic
1424  // selection shall specify compatible types."
1425  for (unsigned j = i+1; j < NumAssocs; ++j)
1426  if (Types[j] && !Types[j]->getType()->isDependentType() &&
1427  Context.typesAreCompatible(Types[i]->getType(),
1428  Types[j]->getType())) {
1429  Diag(Types[j]->getTypeLoc().getBeginLoc(),
1430  diag::err_assoc_compatible_types)
1431  << Types[j]->getTypeLoc().getSourceRange()
1432  << Types[j]->getType()
1433  << Types[i]->getType();
1434  Diag(Types[i]->getTypeLoc().getBeginLoc(),
1435  diag::note_compat_assoc)
1436  << Types[i]->getTypeLoc().getSourceRange()
1437  << Types[i]->getType();
1438  TypeErrorFound = true;
1439  }
1440  }
1441  }
1442  }
1443  if (TypeErrorFound)
1444  return ExprError();
1445 
1446  // If we determined that the generic selection is result-dependent, don't
1447  // try to compute the result expression.
1448  if (IsResultDependent)
1449  return new (Context) GenericSelectionExpr(
1450  Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1451  ContainsUnexpandedParameterPack);
1452 
1453  SmallVector<unsigned, 1> CompatIndices;
1454  unsigned DefaultIndex = -1U;
1455  for (unsigned i = 0; i < NumAssocs; ++i) {
1456  if (!Types[i])
1457  DefaultIndex = i;
1458  else if (Context.typesAreCompatible(ControllingExpr->getType(),
1459  Types[i]->getType()))
1460  CompatIndices.push_back(i);
1461  }
1462 
1463  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1464  // type compatible with at most one of the types named in its generic
1465  // association list."
1466  if (CompatIndices.size() > 1) {
1467  // We strip parens here because the controlling expression is typically
1468  // parenthesized in macro definitions.
1469  ControllingExpr = ControllingExpr->IgnoreParens();
1470  Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1471  << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1472  << (unsigned)CompatIndices.size();
1473  for (unsigned I : CompatIndices) {
1474  Diag(Types[I]->getTypeLoc().getBeginLoc(),
1475  diag::note_compat_assoc)
1476  << Types[I]->getTypeLoc().getSourceRange()
1477  << Types[I]->getType();
1478  }
1479  return ExprError();
1480  }
1481 
1482  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1483  // its controlling expression shall have type compatible with exactly one of
1484  // the types named in its generic association list."
1485  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1486  // We strip parens here because the controlling expression is typically
1487  // parenthesized in macro definitions.
1488  ControllingExpr = ControllingExpr->IgnoreParens();
1489  Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1490  << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1491  return ExprError();
1492  }
1493 
1494  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1495  // type name that is compatible with the type of the controlling expression,
1496  // then the result expression of the generic selection is the expression
1497  // in that generic association. Otherwise, the result expression of the
1498  // generic selection is the expression in the default generic association."
1499  unsigned ResultIndex =
1500  CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1501 
1502  return new (Context) GenericSelectionExpr(
1503  Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1504  ContainsUnexpandedParameterPack, ResultIndex);
1505 }
1506 
1507 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1508 /// location of the token and the offset of the ud-suffix within it.
1510  unsigned Offset) {
1511  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1512  S.getLangOpts());
1513 }
1514 
1515 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1516 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1518  IdentifierInfo *UDSuffix,
1519  SourceLocation UDSuffixLoc,
1520  ArrayRef<Expr*> Args,
1521  SourceLocation LitEndLoc) {
1522  assert(Args.size() <= 2 && "too many arguments for literal operator");
1523 
1524  QualType ArgTy[2];
1525  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1526  ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1527  if (ArgTy[ArgIdx]->isArrayType())
1528  ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1529  }
1530 
1531  DeclarationName OpName =
1533  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1534  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1535 
1536  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1537  if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1538  /*AllowRaw*/ false, /*AllowTemplate*/ false,
1539  /*AllowStringTemplate*/ false,
1540  /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1541  return ExprError();
1542 
1543  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1544 }
1545 
1546 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1547 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1548 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1549 /// multiple tokens. However, the common case is that StringToks points to one
1550 /// string.
1551 ///
1552 ExprResult
1554  assert(!StringToks.empty() && "Must have at least one string!");
1555 
1556  StringLiteralParser Literal(StringToks, PP);
1557  if (Literal.hadError)
1558  return ExprError();
1559 
1560  SmallVector<SourceLocation, 4> StringTokLocs;
1561  for (const Token &Tok : StringToks)
1562  StringTokLocs.push_back(Tok.getLocation());
1563 
1564  QualType CharTy = Context.CharTy;
1566  if (Literal.isWide()) {
1567  CharTy = Context.getWideCharType();
1568  Kind = StringLiteral::Wide;
1569  } else if (Literal.isUTF8()) {
1570  if (getLangOpts().Char8)
1571  CharTy = Context.Char8Ty;
1572  Kind = StringLiteral::UTF8;
1573  } else if (Literal.isUTF16()) {
1574  CharTy = Context.Char16Ty;
1575  Kind = StringLiteral::UTF16;
1576  } else if (Literal.isUTF32()) {
1577  CharTy = Context.Char32Ty;
1578  Kind = StringLiteral::UTF32;
1579  } else if (Literal.isPascal()) {
1580  CharTy = Context.UnsignedCharTy;
1581  }
1582 
1583  // Warn on initializing an array of char from a u8 string literal; this
1584  // becomes ill-formed in C++2a.
1585  if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1586  !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1587  Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1588 
1589  // Create removals for all 'u8' prefixes in the string literal(s). This
1590  // ensures C++2a compatibility (but may change the program behavior when
1591  // built by non-Clang compilers for which the execution character set is
1592  // not always UTF-8).
1593  auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1594  SourceLocation RemovalDiagLoc;
1595  for (const Token &Tok : StringToks) {
1596  if (Tok.getKind() == tok::utf8_string_literal) {
1597  if (RemovalDiagLoc.isInvalid())
1598  RemovalDiagLoc = Tok.getLocation();
1600  Tok.getLocation(),
1601  Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1602  getSourceManager(), getLangOpts())));
1603  }
1604  }
1605  Diag(RemovalDiagLoc, RemovalDiag);
1606  }
1607 
1608 
1609  QualType CharTyConst = CharTy;
1610  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1611  if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1612  CharTyConst.addConst();
1613 
1614  CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1615 
1616  // Get an array type for the string, according to C99 6.4.5. This includes
1617  // the nul terminator character as well as the string length for pascal
1618  // strings.
1619  QualType StrTy = Context.getConstantArrayType(
1620  CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1621  ArrayType::Normal, 0);
1622 
1623  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1624  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1625  Kind, Literal.Pascal, StrTy,
1626  &StringTokLocs[0],
1627  StringTokLocs.size());
1628  if (Literal.getUDSuffix().empty())
1629  return Lit;
1630 
1631  // We're building a user-defined literal.
1632  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1633  SourceLocation UDSuffixLoc =
1634  getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1635  Literal.getUDSuffixOffset());
1636 
1637  // Make sure we're allowed user-defined literals here.
1638  if (!UDLScope)
1639  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1640 
1641  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1642  // operator "" X (str, len)
1643  QualType SizeType = Context.getSizeType();
1644 
1645  DeclarationName OpName =
1646  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1647  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1648  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1649 
1650  QualType ArgTy[] = {
1651  Context.getArrayDecayedType(StrTy), SizeType
1652  };
1653 
1654  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1655  switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1656  /*AllowRaw*/ false, /*AllowTemplate*/ false,
1657  /*AllowStringTemplate*/ true,
1658  /*DiagnoseMissing*/ true)) {
1659 
1660  case LOLR_Cooked: {
1661  llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1662  IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1663  StringTokLocs[0]);
1664  Expr *Args[] = { Lit, LenArg };
1665 
1666  return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1667  }
1668 
1669  case LOLR_StringTemplate: {
1670  TemplateArgumentListInfo ExplicitArgs;
1671 
1672  unsigned CharBits = Context.getIntWidth(CharTy);
1673  bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1674  llvm::APSInt Value(CharBits, CharIsUnsigned);
1675 
1676  TemplateArgument TypeArg(CharTy);
1677  TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1678  ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1679 
1680  for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1681  Value = Lit->getCodeUnit(I);
1682  TemplateArgument Arg(Context, Value, CharTy);
1683  TemplateArgumentLocInfo ArgInfo;
1684  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1685  }
1686  return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1687  &ExplicitArgs);
1688  }
1689  case LOLR_Raw:
1690  case LOLR_Template:
1691  case LOLR_ErrorNoDiagnostic:
1692  llvm_unreachable("unexpected literal operator lookup result");
1693  case LOLR_Error:
1694  return ExprError();
1695  }
1696  llvm_unreachable("unexpected literal operator lookup result");
1697 }
1698 
1699 ExprResult
1701  SourceLocation Loc,
1702  const CXXScopeSpec *SS) {
1703  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1704  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1705 }
1706 
1707 /// BuildDeclRefExpr - Build an expression that references a
1708 /// declaration that does not require a closure capture.
1709 ExprResult
1711  const DeclarationNameInfo &NameInfo,
1712  const CXXScopeSpec *SS, NamedDecl *FoundD,
1713  const TemplateArgumentListInfo *TemplateArgs) {
1714  bool RefersToCapturedVariable =
1715  isa<VarDecl>(D) &&
1716  NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1717 
1718  DeclRefExpr *E;
1719  if (isa<VarTemplateSpecializationDecl>(D)) {
1721  cast<VarTemplateSpecializationDecl>(D);
1722 
1723  E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1725  VarSpec->getTemplateKeywordLoc(), D,
1726  RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1727  FoundD, TemplateArgs);
1728  } else {
1729  assert(!TemplateArgs && "No template arguments for non-variable"
1730  " template specialization references");
1731  E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1733  SourceLocation(), D, RefersToCapturedVariable,
1734  NameInfo, Ty, VK, FoundD);
1735  }
1736 
1737  MarkDeclRefReferenced(E);
1738 
1739  if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1740  Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1741  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1742  getCurFunction()->recordUseOfWeak(E);
1743 
1744  FieldDecl *FD = dyn_cast<FieldDecl>(D);
1745  if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1746  FD = IFD->getAnonField();
1747  if (FD) {
1748  UnusedPrivateFields.remove(FD);
1749  // Just in case we're building an illegal pointer-to-member.
1750  if (FD->isBitField())
1751  E->setObjectKind(OK_BitField);
1752  }
1753 
1754  // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1755  // designates a bit-field.
1756  if (auto *BD = dyn_cast<BindingDecl>(D))
1757  if (auto *BE = BD->getBinding())
1758  E->setObjectKind(BE->getObjectKind());
1759 
1760  return E;
1761 }
1762 
1763 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1764 /// possibly a list of template arguments.
1765 ///
1766 /// If this produces template arguments, it is permitted to call
1767 /// DecomposeTemplateName.
1768 ///
1769 /// This actually loses a lot of source location information for
1770 /// non-standard name kinds; we should consider preserving that in
1771 /// some way.
1772 void
1774  TemplateArgumentListInfo &Buffer,
1775  DeclarationNameInfo &NameInfo,
1776  const TemplateArgumentListInfo *&TemplateArgs) {
1778  Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1779  Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1780 
1781  ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1782  Id.TemplateId->NumArgs);
1783  translateTemplateArguments(TemplateArgsPtr, Buffer);
1784 
1785  TemplateName TName = Id.TemplateId->Template.get();
1786  SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1787  NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1788  TemplateArgs = &Buffer;
1789  } else {
1790  NameInfo = GetNameFromUnqualifiedId(Id);
1791  TemplateArgs = nullptr;
1792  }
1793 }
1794 
1796  const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1797  DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1798  unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1799  DeclContext *Ctx =
1800  SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1801  if (!TC) {
1802  // Emit a special diagnostic for failed member lookups.
1803  // FIXME: computing the declaration context might fail here (?)
1804  if (Ctx)
1805  SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1806  << SS.getRange();
1807  else
1808  SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1809  return;
1810  }
1811 
1812  std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1813  bool DroppedSpecifier =
1814  TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1815  unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1816  ? diag::note_implicit_param_decl
1817  : diag::note_previous_decl;
1818  if (!Ctx)
1819  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1820  SemaRef.PDiag(NoteID));
1821  else
1822  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1823  << Typo << Ctx << DroppedSpecifier
1824  << SS.getRange(),
1825  SemaRef.PDiag(NoteID));
1826 }
1827 
1828 /// Diagnose an empty lookup.
1829 ///
1830 /// \return false if new lookup candidates were found
1831 bool
1833  std::unique_ptr<CorrectionCandidateCallback> CCC,
1834  TemplateArgumentListInfo *ExplicitTemplateArgs,
1835  ArrayRef<Expr *> Args, TypoExpr **Out) {
1836  DeclarationName Name = R.getLookupName();
1837 
1838  unsigned diagnostic = diag::err_undeclared_var_use;
1839  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1843  diagnostic = diag::err_undeclared_use;
1844  diagnostic_suggest = diag::err_undeclared_use_suggest;
1845  }
1846 
1847  // If the original lookup was an unqualified lookup, fake an
1848  // unqualified lookup. This is useful when (for example) the
1849  // original lookup would not have found something because it was a
1850  // dependent name.
1851  DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1852  while (DC) {
1853  if (isa<CXXRecordDecl>(DC)) {
1854  LookupQualifiedName(R, DC);
1855 
1856  if (!R.empty()) {
1857  // Don't give errors about ambiguities in this lookup.
1858  R.suppressDiagnostics();
1859 
1860  // During a default argument instantiation the CurContext points
1861  // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1862  // function parameter list, hence add an explicit check.
1863  bool isDefaultArgument =
1864  !CodeSynthesisContexts.empty() &&
1865  CodeSynthesisContexts.back().Kind ==
1866  CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1867  CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1868  bool isInstance = CurMethod &&
1869  CurMethod->isInstance() &&
1870  DC == CurMethod->getParent() && !isDefaultArgument;
1871 
1872  // Give a code modification hint to insert 'this->'.
1873  // TODO: fixit for inserting 'Base<T>::' in the other cases.
1874  // Actually quite difficult!
1875  if (getLangOpts().MSVCCompat)
1876  diagnostic = diag::ext_found_via_dependent_bases_lookup;
1877  if (isInstance) {
1878  Diag(R.getNameLoc(), diagnostic) << Name
1879  << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1880  CheckCXXThisCapture(R.getNameLoc());
1881  } else {
1882  Diag(R.getNameLoc(), diagnostic) << Name;
1883  }
1884 
1885  // Do we really want to note all of these?
1886  for (NamedDecl *D : R)
1887  Diag(D->getLocation(), diag::note_dependent_var_use);
1888 
1889  // Return true if we are inside a default argument instantiation
1890  // and the found name refers to an instance member function, otherwise
1891  // the function calling DiagnoseEmptyLookup will try to create an
1892  // implicit member call and this is wrong for default argument.
1893  if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1894  Diag(R.getNameLoc(), diag::err_member_call_without_object);
1895  return true;
1896  }
1897 
1898  // Tell the callee to try to recover.
1899  return false;
1900  }
1901 
1902  R.clear();
1903  }
1904 
1905  // In Microsoft mode, if we are performing lookup from within a friend
1906  // function definition declared at class scope then we must set
1907  // DC to the lexical parent to be able to search into the parent
1908  // class.
1909  if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1910  cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1911  DC->getLexicalParent()->isRecord())
1912  DC = DC->getLexicalParent();
1913  else
1914  DC = DC->getParent();
1915  }
1916 
1917  // We didn't find anything, so try to correct for a typo.
1918  TypoCorrection Corrected;
1919  if (S && Out) {
1920  SourceLocation TypoLoc = R.getNameLoc();
1921  assert(!ExplicitTemplateArgs &&
1922  "Diagnosing an empty lookup with explicit template args!");
1923  *Out = CorrectTypoDelayed(
1924  R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1925  [=](const TypoCorrection &TC) {
1926  emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1927  diagnostic, diagnostic_suggest);
1928  },
1929  nullptr, CTK_ErrorRecovery);
1930  if (*Out)
1931  return true;
1932  } else if (S && (Corrected =
1933  CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1934  &SS, std::move(CCC), CTK_ErrorRecovery))) {
1935  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1936  bool DroppedSpecifier =
1937  Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1938  R.setLookupName(Corrected.getCorrection());
1939 
1940  bool AcceptableWithRecovery = false;
1941  bool AcceptableWithoutRecovery = false;
1942  NamedDecl *ND = Corrected.getFoundDecl();
1943  if (ND) {
1944  if (Corrected.isOverloaded()) {
1948  for (NamedDecl *CD : Corrected) {
1949  if (FunctionTemplateDecl *FTD =
1950  dyn_cast<FunctionTemplateDecl>(CD))
1951  AddTemplateOverloadCandidate(
1952  FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1953  Args, OCS);
1954  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1955  if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1956  AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1957  Args, OCS);
1958  }
1959  switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1960  case OR_Success:
1961  ND = Best->FoundDecl;
1962  Corrected.setCorrectionDecl(ND);
1963  break;
1964  default:
1965  // FIXME: Arbitrarily pick the first declaration for the note.
1966  Corrected.setCorrectionDecl(ND);
1967  break;
1968  }
1969  }
1970  R.addDecl(ND);
1971  if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1972  CXXRecordDecl *Record = nullptr;
1973  if (Corrected.getCorrectionSpecifier()) {
1974  const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1975  Record = Ty->getAsCXXRecordDecl();
1976  }
1977  if (!Record)
1978  Record = cast<CXXRecordDecl>(
1979  ND->getDeclContext()->getRedeclContext());
1980  R.setNamingClass(Record);
1981  }
1982 
1983  auto *UnderlyingND = ND->getUnderlyingDecl();
1984  AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1985  isa<FunctionTemplateDecl>(UnderlyingND);
1986  // FIXME: If we ended up with a typo for a type name or
1987  // Objective-C class name, we're in trouble because the parser
1988  // is in the wrong place to recover. Suggest the typo
1989  // correction, but don't make it a fix-it since we're not going
1990  // to recover well anyway.
1991  AcceptableWithoutRecovery =
1992  isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1993  } else {
1994  // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1995  // because we aren't able to recover.
1996  AcceptableWithoutRecovery = true;
1997  }
1998 
1999  if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2000  unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2001  ? diag::note_implicit_param_decl
2002  : diag::note_previous_decl;
2003  if (SS.isEmpty())
2004  diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2005  PDiag(NoteID), AcceptableWithRecovery);
2006  else
2007  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2008  << Name << computeDeclContext(SS, false)
2009  << DroppedSpecifier << SS.getRange(),
2010  PDiag(NoteID), AcceptableWithRecovery);
2011 
2012  // Tell the callee whether to try to recover.
2013  return !AcceptableWithRecovery;
2014  }
2015  }
2016  R.clear();
2017 
2018  // Emit a special diagnostic for failed member lookups.
2019  // FIXME: computing the declaration context might fail here (?)
2020  if (!SS.isEmpty()) {
2021  Diag(R.getNameLoc(), diag::err_no_member)
2022  << Name << computeDeclContext(SS, false)
2023  << SS.getRange();
2024  return true;
2025  }
2026 
2027  // Give up, we can't recover.
2028  Diag(R.getNameLoc(), diagnostic) << Name;
2029  return true;
2030 }
2031 
2032 /// In Microsoft mode, if we are inside a template class whose parent class has
2033 /// dependent base classes, and we can't resolve an unqualified identifier, then
2034 /// assume the identifier is a member of a dependent base class. We can only
2035 /// recover successfully in static methods, instance methods, and other contexts
2036 /// where 'this' is available. This doesn't precisely match MSVC's
2037 /// instantiation model, but it's close enough.
2038 static Expr *
2040  DeclarationNameInfo &NameInfo,
2041  SourceLocation TemplateKWLoc,
2042  const TemplateArgumentListInfo *TemplateArgs) {
2043  // Only try to recover from lookup into dependent bases in static methods or
2044  // contexts where 'this' is available.
2045  QualType ThisType = S.getCurrentThisType();
2046  const CXXRecordDecl *RD = nullptr;
2047  if (!ThisType.isNull())
2048  RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2049  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2050  RD = MD->getParent();
2051  if (!RD || !RD->hasAnyDependentBases())
2052  return nullptr;
2053 
2054  // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2055  // is available, suggest inserting 'this->' as a fixit.
2056  SourceLocation Loc = NameInfo.getLoc();
2057  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2058  DB << NameInfo.getName() << RD;
2059 
2060  if (!ThisType.isNull()) {
2061  DB << FixItHint::CreateInsertion(Loc, "this->");
2063  Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2064  /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2065  /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2066  }
2067 
2068  // Synthesize a fake NNS that points to the derived class. This will
2069  // perform name lookup during template instantiation.
2070  CXXScopeSpec SS;
2071  auto *NNS =
2072  NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2073  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2075  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2076  TemplateArgs);
2077 }
2078 
2079 ExprResult
2081  SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2082  bool HasTrailingLParen, bool IsAddressOfOperand,
2083  std::unique_ptr<CorrectionCandidateCallback> CCC,
2084  bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2085  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2086  "cannot be direct & operand and have a trailing lparen");
2087  if (SS.isInvalid())
2088  return ExprError();
2089 
2090  TemplateArgumentListInfo TemplateArgsBuffer;
2091 
2092  // Decompose the UnqualifiedId into the following data.
2093  DeclarationNameInfo NameInfo;
2094  const TemplateArgumentListInfo *TemplateArgs;
2095  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2096 
2097  DeclarationName Name = NameInfo.getName();
2098  IdentifierInfo *II = Name.getAsIdentifierInfo();
2099  SourceLocation NameLoc = NameInfo.getLoc();
2100 
2101  if (II && II->isEditorPlaceholder()) {
2102  // FIXME: When typed placeholders are supported we can create a typed
2103  // placeholder expression node.
2104  return ExprError();
2105  }
2106 
2107  // C++ [temp.dep.expr]p3:
2108  // An id-expression is type-dependent if it contains:
2109  // -- an identifier that was declared with a dependent type,
2110  // (note: handled after lookup)
2111  // -- a template-id that is dependent,
2112  // (note: handled in BuildTemplateIdExpr)
2113  // -- a conversion-function-id that specifies a dependent type,
2114  // -- a nested-name-specifier that contains a class-name that
2115  // names a dependent type.
2116  // Determine whether this is a member of an unknown specialization;
2117  // we need to handle these differently.
2118  bool DependentID = false;
2120  Name.getCXXNameType()->isDependentType()) {
2121  DependentID = true;
2122  } else if (SS.isSet()) {
2123  if (DeclContext *DC = computeDeclContext(SS, false)) {
2124  if (RequireCompleteDeclContext(SS, DC))
2125  return ExprError();
2126  } else {
2127  DependentID = true;
2128  }
2129  }
2130 
2131  if (DependentID)
2132  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2133  IsAddressOfOperand, TemplateArgs);
2134 
2135  // Perform the required lookup.
2136  LookupResult R(*this, NameInfo,
2138  ? LookupObjCImplicitSelfParam
2139  : LookupOrdinaryName);
2140  if (TemplateKWLoc.isValid() || TemplateArgs) {
2141  // Lookup the template name again to correctly establish the context in
2142  // which it was found. This is really unfortunate as we already did the
2143  // lookup to determine that it was a template name in the first place. If
2144  // this becomes a performance hit, we can work harder to preserve those
2145  // results until we get here but it's likely not worth it.
2146  bool MemberOfUnknownSpecialization;
2147  if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2148  MemberOfUnknownSpecialization, TemplateKWLoc))
2149  return ExprError();
2150 
2151  if (MemberOfUnknownSpecialization ||
2153  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2154  IsAddressOfOperand, TemplateArgs);
2155  } else {
2156  bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2157  LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2158 
2159  // If the result might be in a dependent base class, this is a dependent
2160  // id-expression.
2162  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2163  IsAddressOfOperand, TemplateArgs);
2164 
2165  // If this reference is in an Objective-C method, then we need to do
2166  // some special Objective-C lookup, too.
2167  if (IvarLookupFollowUp) {
2168  ExprResult E(LookupInObjCMethod(R, S, II, true));
2169  if (E.isInvalid())
2170  return ExprError();
2171 
2172  if (Expr *Ex = E.getAs<Expr>())
2173  return Ex;
2174  }
2175  }
2176 
2177  if (R.isAmbiguous())
2178  return ExprError();
2179 
2180  // This could be an implicitly declared function reference (legal in C90,
2181  // extension in C99, forbidden in C++).
2182  if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2183  NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2184  if (D) R.addDecl(D);
2185  }
2186 
2187  // Determine whether this name might be a candidate for
2188  // argument-dependent lookup.
2189  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2190 
2191  if (R.empty() && !ADL) {
2192  if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2193  if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2194  TemplateKWLoc, TemplateArgs))
2195  return E;
2196  }
2197 
2198  // Don't diagnose an empty lookup for inline assembly.
2199  if (IsInlineAsmIdentifier)
2200  return ExprError();
2201 
2202  // If this name wasn't predeclared and if this is not a function
2203  // call, diagnose the problem.
2204  TypoExpr *TE = nullptr;
2205  auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2206  II, SS.isValid() ? SS.getScopeRep() : nullptr);
2207  DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2208  assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2209  "Typo correction callback misconfigured");
2210  if (CCC) {
2211  // Make sure the callback knows what the typo being diagnosed is.
2212  CCC->setTypoName(II);
2213  if (SS.isValid())
2214  CCC->setTypoNNS(SS.getScopeRep());
2215  }
2216  // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2217  // a template name, but we happen to have always already looked up the name
2218  // before we get here if it must be a template name.
2219  if (DiagnoseEmptyLookup(S, SS, R,
2220  CCC ? std::move(CCC) : std::move(DefaultValidator),
2221  nullptr, None, &TE)) {
2222  if (TE && KeywordReplacement) {
2223  auto &State = getTypoExprState(TE);
2224  auto BestTC = State.Consumer->getNextCorrection();
2225  if (BestTC.isKeyword()) {
2226  auto *II = BestTC.getCorrectionAsIdentifierInfo();
2227  if (State.DiagHandler)
2228  State.DiagHandler(BestTC);
2229  KeywordReplacement->startToken();
2230  KeywordReplacement->setKind(II->getTokenID());
2231  KeywordReplacement->setIdentifierInfo(II);
2232  KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2233  // Clean up the state associated with the TypoExpr, since it has
2234  // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2235  clearDelayedTypo(TE);
2236  // Signal that a correction to a keyword was performed by returning a
2237  // valid-but-null ExprResult.
2238  return (Expr*)nullptr;
2239  }
2240  State.Consumer->resetCorrectionStream();
2241  }
2242  return TE ? TE : ExprError();
2243  }
2244 
2245  assert(!R.empty() &&
2246  "DiagnoseEmptyLookup returned false but added no results");
2247 
2248  // If we found an Objective-C instance variable, let
2249  // LookupInObjCMethod build the appropriate expression to
2250  // reference the ivar.
2251  if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2252  R.clear();
2253  ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2254  // In a hopelessly buggy code, Objective-C instance variable
2255  // lookup fails and no expression will be built to reference it.
2256  if (!E.isInvalid() && !E.get())
2257  return ExprError();
2258  return E;
2259  }
2260  }
2261 
2262  // This is guaranteed from this point on.
2263  assert(!R.empty() || ADL);
2264 
2265  // Check whether this might be a C++ implicit instance member access.
2266  // C++ [class.mfct.non-static]p3:
2267  // When an id-expression that is not part of a class member access
2268  // syntax and not used to form a pointer to member is used in the
2269  // body of a non-static member function of class X, if name lookup
2270  // resolves the name in the id-expression to a non-static non-type
2271  // member of some class C, the id-expression is transformed into a
2272  // class member access expression using (*this) as the
2273  // postfix-expression to the left of the . operator.
2274  //
2275  // But we don't actually need to do this for '&' operands if R
2276  // resolved to a function or overloaded function set, because the
2277  // expression is ill-formed if it actually works out to be a
2278  // non-static member function:
2279  //
2280  // C++ [expr.ref]p4:
2281  // Otherwise, if E1.E2 refers to a non-static member function. . .
2282  // [t]he expression can be used only as the left-hand operand of a
2283  // member function call.
2284  //
2285  // There are other safeguards against such uses, but it's important
2286  // to get this right here so that we don't end up making a
2287  // spuriously dependent expression if we're inside a dependent
2288  // instance method.
2289  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2290  bool MightBeImplicitMember;
2291  if (!IsAddressOfOperand)
2292  MightBeImplicitMember = true;
2293  else if (!SS.isEmpty())
2294  MightBeImplicitMember = false;
2295  else if (R.isOverloadedResult())
2296  MightBeImplicitMember = false;
2297  else if (R.isUnresolvableResult())
2298  MightBeImplicitMember = true;
2299  else
2300  MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2301  isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2302  isa<MSPropertyDecl>(R.getFoundDecl());
2303 
2304  if (MightBeImplicitMember)
2305  return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2306  R, TemplateArgs, S);
2307  }
2308 
2309  if (TemplateArgs || TemplateKWLoc.isValid()) {
2310 
2311  // In C++1y, if this is a variable template id, then check it
2312  // in BuildTemplateIdExpr().
2313  // The single lookup result must be a variable template declaration.
2315  Id.TemplateId->Kind == TNK_Var_template) {
2316  assert(R.getAsSingle<VarTemplateDecl>() &&
2317  "There should only be one declaration found.");
2318  }
2319 
2320  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2321  }
2322 
2323  return BuildDeclarationNameExpr(SS, R, ADL);
2324 }
2325 
2326 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2327 /// declaration name, generally during template instantiation.
2328 /// There's a large number of things which don't need to be done along
2329 /// this path.
2331  CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2332  bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2333  DeclContext *DC = computeDeclContext(SS, false);
2334  if (!DC)
2335  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2336  NameInfo, /*TemplateArgs=*/nullptr);
2337 
2338  if (RequireCompleteDeclContext(SS, DC))
2339  return ExprError();
2340 
2341  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2342  LookupQualifiedName(R, DC);
2343 
2344  if (R.isAmbiguous())
2345  return ExprError();
2346 
2348  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2349  NameInfo, /*TemplateArgs=*/nullptr);
2350 
2351  if (R.empty()) {
2352  Diag(NameInfo.getLoc(), diag::err_no_member)
2353  << NameInfo.getName() << DC << SS.getRange();
2354  return ExprError();
2355  }
2356 
2357  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2358  // Diagnose a missing typename if this resolved unambiguously to a type in
2359  // a dependent context. If we can recover with a type, downgrade this to
2360  // a warning in Microsoft compatibility mode.
2361  unsigned DiagID = diag::err_typename_missing;
2362  if (RecoveryTSI && getLangOpts().MSVCCompat)
2363  DiagID = diag::ext_typename_missing;
2364  SourceLocation Loc = SS.getBeginLoc();
2365  auto D = Diag(Loc, DiagID);
2366  D << SS.getScopeRep() << NameInfo.getName().getAsString()
2367  << SourceRange(Loc, NameInfo.getEndLoc());
2368 
2369  // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2370  // context.
2371  if (!RecoveryTSI)
2372  return ExprError();
2373 
2374  // Only issue the fixit if we're prepared to recover.
2375  D << FixItHint::CreateInsertion(Loc, "typename ");
2376 
2377  // Recover by pretending this was an elaborated type.
2378  QualType Ty = Context.getTypeDeclType(TD);
2379  TypeLocBuilder TLB;
2380  TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2381 
2382  QualType ET = getElaboratedType(ETK_None, SS, Ty);
2383  ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2385  QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2386 
2387  *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2388 
2389  return ExprEmpty();
2390  }
2391 
2392  // Defend against this resolving to an implicit member access. We usually
2393  // won't get here if this might be a legitimate a class member (we end up in
2394  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2395  // a pointer-to-member or in an unevaluated context in C++11.
2396  if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2397  return BuildPossibleImplicitMemberExpr(SS,
2398  /*TemplateKWLoc=*/SourceLocation(),
2399  R, /*TemplateArgs=*/nullptr, S);
2400 
2401  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2402 }
2403 
2404 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2405 /// detected that we're currently inside an ObjC method. Perform some
2406 /// additional lookup.
2407 ///
2408 /// Ideally, most of this would be done by lookup, but there's
2409 /// actually quite a lot of extra work involved.
2410 ///
2411 /// Returns a null sentinel to indicate trivial success.
2412 ExprResult
2414  IdentifierInfo *II, bool AllowBuiltinCreation) {
2415  SourceLocation Loc = Lookup.getNameLoc();
2416  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2417 
2418  // Check for error condition which is already reported.
2419  if (!CurMethod)
2420  return ExprError();
2421 
2422  // There are two cases to handle here. 1) scoped lookup could have failed,
2423  // in which case we should look for an ivar. 2) scoped lookup could have
2424  // found a decl, but that decl is outside the current instance method (i.e.
2425  // a global variable). In these two cases, we do a lookup for an ivar with
2426  // this name, if the lookup sucedes, we replace it our current decl.
2427 
2428  // If we're in a class method, we don't normally want to look for
2429  // ivars. But if we don't find anything else, and there's an
2430  // ivar, that's an error.
2431  bool IsClassMethod = CurMethod->isClassMethod();
2432 
2433  bool LookForIvars;
2434  if (Lookup.empty())
2435  LookForIvars = true;
2436  else if (IsClassMethod)
2437  LookForIvars = false;
2438  else
2439  LookForIvars = (Lookup.isSingleResult() &&
2441  ObjCInterfaceDecl *IFace = nullptr;
2442  if (LookForIvars) {
2443  IFace = CurMethod->getClassInterface();
2444  ObjCInterfaceDecl *ClassDeclared;
2445  ObjCIvarDecl *IV = nullptr;
2446  if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2447  // Diagnose using an ivar in a class method.
2448  if (IsClassMethod)
2449  return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2450  << IV->getDeclName());
2451 
2452  // If we're referencing an invalid decl, just return this as a silent
2453  // error node. The error diagnostic was already emitted on the decl.
2454  if (IV->isInvalidDecl())
2455  return ExprError();
2456 
2457  // Check if referencing a field with __attribute__((deprecated)).
2458  if (DiagnoseUseOfDecl(IV, Loc))
2459  return ExprError();
2460 
2461  // Diagnose the use of an ivar outside of the declaring class.
2462  if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2463  !declaresSameEntity(ClassDeclared, IFace) &&
2464  !getLangOpts().DebuggerSupport)
2465  Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2466 
2467  // FIXME: This should use a new expr for a direct reference, don't
2468  // turn this into Self->ivar, just return a BareIVarExpr or something.
2469  IdentifierInfo &II = Context.Idents.get("self");
2470  UnqualifiedId SelfName;
2471  SelfName.setIdentifier(&II, SourceLocation());
2473  CXXScopeSpec SelfScopeSpec;
2474  SourceLocation TemplateKWLoc;
2475  ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2476  SelfName, false, false);
2477  if (SelfExpr.isInvalid())
2478  return ExprError();
2479 
2480  SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2481  if (SelfExpr.isInvalid())
2482  return ExprError();
2483 
2484  MarkAnyDeclReferenced(Loc, IV, true);
2485 
2486  ObjCMethodFamily MF = CurMethod->getMethodFamily();
2487  if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2488  !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2489  Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2490 
2491  ObjCIvarRefExpr *Result = new (Context)
2492  ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2493  IV->getLocation(), SelfExpr.get(), true, true);
2494 
2495  if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2496  if (!isUnevaluatedContext() &&
2497  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2498  getCurFunction()->recordUseOfWeak(Result);
2499  }
2500  if (getLangOpts().ObjCAutoRefCount) {
2501  if (CurContext->isClosure())
2502  Diag(Loc, diag::warn_implicitly_retains_self)
2503  << FixItHint::CreateInsertion(Loc, "self->");
2504  }
2505 
2506  return Result;
2507  }
2508  } else if (CurMethod->isInstanceMethod()) {
2509  // We should warn if a local variable hides an ivar.
2510  if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2511  ObjCInterfaceDecl *ClassDeclared;
2512  if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2513  if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2514  declaresSameEntity(IFace, ClassDeclared))
2515  Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2516  }
2517  }
2518  } else if (Lookup.isSingleResult() &&
2520  // If accessing a stand-alone ivar in a class method, this is an error.
2521  if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2522  return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2523  << IV->getDeclName());
2524  }
2525 
2526  if (Lookup.empty() && II && AllowBuiltinCreation) {
2527  // FIXME. Consolidate this with similar code in LookupName.
2528  if (unsigned BuiltinID = II->getBuiltinID()) {
2529  if (!(getLangOpts().CPlusPlus &&
2530  Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2531  NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2532  S, Lookup.isForRedeclaration(),
2533  Lookup.getNameLoc());
2534  if (D) Lookup.addDecl(D);
2535  }
2536  }
2537  }
2538  // Sentinel value saying that we didn't do anything special.
2539  return ExprResult((Expr *)nullptr);
2540 }
2541 
2542 /// Cast a base object to a member's actual type.
2543 ///
2544 /// Logically this happens in three phases:
2545 ///
2546 /// * First we cast from the base type to the naming class.
2547 /// The naming class is the class into which we were looking
2548 /// when we found the member; it's the qualifier type if a
2549 /// qualifier was provided, and otherwise it's the base type.
2550 ///
2551 /// * Next we cast from the naming class to the declaring class.
2552 /// If the member we found was brought into a class's scope by
2553 /// a using declaration, this is that class; otherwise it's
2554 /// the class declaring the member.
2555 ///
2556 /// * Finally we cast from the declaring class to the "true"
2557 /// declaring class of the member. This conversion does not
2558 /// obey access control.
2559 ExprResult
2561  NestedNameSpecifier *Qualifier,
2562  NamedDecl *FoundDecl,
2563  NamedDecl *Member) {
2564  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2565  if (!RD)
2566  return From;
2567 
2568  QualType DestRecordType;
2569  QualType DestType;
2570  QualType FromRecordType;
2571  QualType FromType = From->getType();
2572  bool PointerConversions = false;
2573  if (isa<FieldDecl>(Member)) {
2574  DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2575 
2576  if (FromType->getAs<PointerType>()) {
2577  DestType = Context.getPointerType(DestRecordType);
2578  FromRecordType = FromType->getPointeeType();
2579  PointerConversions = true;
2580  } else {
2581  DestType = DestRecordType;
2582  FromRecordType = FromType;
2583  }
2584  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2585  if (Method->isStatic())
2586  return From;
2587 
2588  DestType = Method->getThisType();
2589  DestRecordType = DestType->getPointeeType();
2590 
2591  if (FromType->getAs<PointerType>()) {
2592  FromRecordType = FromType->getPointeeType();
2593  PointerConversions = true;
2594  } else {
2595  FromRecordType = FromType;
2596  DestType = DestRecordType;
2597  }
2598  } else {
2599  // No conversion necessary.
2600  return From;
2601  }
2602 
2603  if (DestType->isDependentType() || FromType->isDependentType())
2604  return From;
2605 
2606  // If the unqualified types are the same, no conversion is necessary.
2607  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2608  return From;
2609 
2610  SourceRange FromRange = From->getSourceRange();
2611  SourceLocation FromLoc = FromRange.getBegin();
2612 
2613  ExprValueKind VK = From->getValueKind();
2614 
2615  // C++ [class.member.lookup]p8:
2616  // [...] Ambiguities can often be resolved by qualifying a name with its
2617  // class name.
2618  //
2619  // If the member was a qualified name and the qualified referred to a
2620  // specific base subobject type, we'll cast to that intermediate type
2621  // first and then to the object in which the member is declared. That allows
2622  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2623  //
2624  // class Base { public: int x; };
2625  // class Derived1 : public Base { };
2626  // class Derived2 : public Base { };
2627  // class VeryDerived : public Derived1, public Derived2 { void f(); };
2628  //
2629  // void VeryDerived::f() {
2630  // x = 17; // error: ambiguous base subobjects
2631  // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2632  // }
2633  if (Qualifier && Qualifier->getAsType()) {
2634  QualType QType = QualType(Qualifier->getAsType(), 0);
2635  assert(QType->isRecordType() && "lookup done with non-record type");
2636 
2637  QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2638 
2639  // In C++98, the qualifier type doesn't actually have to be a base
2640  // type of the object type, in which case we just ignore it.
2641  // Otherwise build the appropriate casts.
2642  if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2643  CXXCastPath BasePath;
2644  if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2645  FromLoc, FromRange, &BasePath))
2646  return ExprError();
2647 
2648  if (PointerConversions)
2649  QType = Context.getPointerType(QType);
2650  From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2651  VK, &BasePath).get();
2652 
2653  FromType = QType;
2654  FromRecordType = QRecordType;
2655 
2656  // If the qualifier type was the same as the destination type,
2657  // we're done.
2658  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2659  return From;
2660  }
2661  }
2662 
2663  bool IgnoreAccess = false;
2664 
2665  // If we actually found the member through a using declaration, cast
2666  // down to the using declaration's type.
2667  //
2668  // Pointer equality is fine here because only one declaration of a
2669  // class ever has member declarations.
2670  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2671  assert(isa<UsingShadowDecl>(FoundDecl));
2672  QualType URecordType = Context.getTypeDeclType(
2673  cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2674 
2675  // We only need to do this if the naming-class to declaring-class
2676  // conversion is non-trivial.
2677  if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2678  assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2679  CXXCastPath BasePath;
2680  if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2681  FromLoc, FromRange, &BasePath))
2682  return ExprError();
2683 
2684  QualType UType = URecordType;
2685  if (PointerConversions)
2686  UType = Context.getPointerType(UType);
2687  From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2688  VK, &BasePath).get();
2689  FromType = UType;
2690  FromRecordType = URecordType;
2691  }
2692 
2693  // We don't do access control for the conversion from the
2694  // declaring class to the true declaring class.
2695  IgnoreAccess = true;
2696  }
2697 
2698  CXXCastPath BasePath;
2699  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2700  FromLoc, FromRange, &BasePath,
2701  IgnoreAccess))
2702  return ExprError();
2703 
2704  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2705  VK, &BasePath);
2706 }
2707 
2709  const LookupResult &R,
2710  bool HasTrailingLParen) {
2711  // Only when used directly as the postfix-expression of a call.
2712  if (!HasTrailingLParen)
2713  return false;
2714 
2715  // Never if a scope specifier was provided.
2716  if (SS.isSet())
2717  return false;
2718 
2719  // Only in C++ or ObjC++.
2720  if (!getLangOpts().CPlusPlus)
2721  return false;
2722 
2723  // Turn off ADL when we find certain kinds of declarations during
2724  // normal lookup:
2725  for (NamedDecl *D : R) {
2726  // C++0x [basic.lookup.argdep]p3:
2727  // -- a declaration of a class member
2728  // Since using decls preserve this property, we check this on the
2729  // original decl.
2730  if (D->isCXXClassMember())
2731  return false;
2732 
2733  // C++0x [basic.lookup.argdep]p3:
2734  // -- a block-scope function declaration that is not a
2735  // using-declaration
2736  // NOTE: we also trigger this for function templates (in fact, we
2737  // don't check the decl type at all, since all other decl types
2738  // turn off ADL anyway).
2739  if (isa<UsingShadowDecl>(D))
2740  D = cast<UsingShadowDecl>(D)->getTargetDecl();
2741  else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2742  return false;
2743 
2744  // C++0x [basic.lookup.argdep]p3:
2745  // -- a declaration that is neither a function or a function
2746  // template
2747  // And also for builtin functions.
2748  if (isa<FunctionDecl>(D)) {
2749  FunctionDecl *FDecl = cast<FunctionDecl>(D);
2750 
2751  // But also builtin functions.
2752  if (FDecl->getBuiltinID() && FDecl->isImplicit())
2753  return false;
2754  } else if (!isa<FunctionTemplateDecl>(D))
2755  return false;
2756  }
2757 
2758  return true;
2759 }
2760 
2761 
2762 /// Diagnoses obvious problems with the use of the given declaration
2763 /// as an expression. This is only actually called for lookups that
2764 /// were not overloaded, and it doesn't promise that the declaration
2765 /// will in fact be used.
2766 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2767  if (D->isInvalidDecl())
2768  return true;
2769 
2770  if (isa<TypedefNameDecl>(D)) {
2771  S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2772  return true;
2773  }
2774 
2775  if (isa<ObjCInterfaceDecl>(D)) {
2776  S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2777  return true;
2778  }
2779 
2780  if (isa<NamespaceDecl>(D)) {
2781  S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2782  return true;
2783  }
2784 
2785  return false;
2786 }
2787 
2788 // Certain multiversion types should be treated as overloaded even when there is
2789 // only one result.
2791  assert(R.isSingleResult() && "Expected only a single result");
2792  const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2793  return FD &&
2794  (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2795 }
2796 
2798  LookupResult &R, bool NeedsADL,
2799  bool AcceptInvalidDecl) {
2800  // If this is a single, fully-resolved result and we don't need ADL,
2801  // just build an ordinary singleton decl ref.
2802  if (!NeedsADL && R.isSingleResult() &&
2805  return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2806  R.getRepresentativeDecl(), nullptr,
2807  AcceptInvalidDecl);
2808 
2809  // We only need to check the declaration if there's exactly one
2810  // result, because in the overloaded case the results can only be
2811  // functions and function templates.
2813  CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2814  return ExprError();
2815 
2816  // Otherwise, just build an unresolved lookup expression. Suppress
2817  // any lookup-related diagnostics; we'll hash these out later, when
2818  // we've picked a target.
2819  R.suppressDiagnostics();
2820 
2823  SS.getWithLocInContext(Context),
2824  R.getLookupNameInfo(),
2825  NeedsADL, R.isOverloadedResult(),
2826  R.begin(), R.end());
2827 
2828  return ULE;
2829 }
2830 
2831 static void
2833  ValueDecl *var, DeclContext *DC);
2834 
2835 /// Complete semantic analysis for a reference to the given declaration.
2837  const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2838  NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2839  bool AcceptInvalidDecl) {
2840  assert(D && "Cannot refer to a NULL declaration");
2841  assert(!isa<FunctionTemplateDecl>(D) &&
2842  "Cannot refer unambiguously to a function template");
2843 
2844  SourceLocation Loc = NameInfo.getLoc();
2845  if (CheckDeclInExpr(*this, Loc, D))
2846  return ExprError();
2847 
2848  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2849  // Specifically diagnose references to class templates that are missing
2850  // a template argument list.
2851  diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2852  return ExprError();
2853  }
2854 
2855  // Make sure that we're referring to a value.
2856  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2857  if (!VD) {
2858  Diag(Loc, diag::err_ref_non_value)
2859  << D << SS.getRange();
2860  Diag(D->getLocation(), diag::note_declared_at);
2861  return ExprError();
2862  }
2863 
2864  // Check whether this declaration can be used. Note that we suppress
2865  // this check when we're going to perform argument-dependent lookup
2866  // on this function name, because this might not be the function
2867  // that overload resolution actually selects.
2868  if (DiagnoseUseOfDecl(VD, Loc))
2869  return ExprError();
2870 
2871  // Only create DeclRefExpr's for valid Decl's.
2872  if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2873  return ExprError();
2874 
2875  // Handle members of anonymous structs and unions. If we got here,
2876  // and the reference is to a class member indirect field, then this
2877  // must be the subject of a pointer-to-member expression.
2878  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2879  if (!indirectField->isCXXClassMember())
2880  return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2881  indirectField);
2882 
2883  {
2884  QualType type = VD->getType();
2885  if (type.isNull())
2886  return ExprError();
2887  if (auto *FPT = type->getAs<FunctionProtoType>()) {
2888  // C++ [except.spec]p17:
2889  // An exception-specification is considered to be needed when:
2890  // - in an expression, the function is the unique lookup result or
2891  // the selected member of a set of overloaded functions.
2892  ResolveExceptionSpec(Loc, FPT);
2893  type = VD->getType();
2894  }
2895  ExprValueKind valueKind = VK_RValue;
2896 
2897  switch (D->getKind()) {
2898  // Ignore all the non-ValueDecl kinds.
2899 #define ABSTRACT_DECL(kind)
2900 #define VALUE(type, base)
2901 #define DECL(type, base) \
2902  case Decl::type:
2903 #include "clang/AST/DeclNodes.inc"
2904  llvm_unreachable("invalid value decl kind");
2905 
2906  // These shouldn't make it here.
2907  case Decl::ObjCAtDefsField:
2908  case Decl::ObjCIvar:
2909  llvm_unreachable("forming non-member reference to ivar?");
2910 
2911  // Enum constants are always r-values and never references.
2912  // Unresolved using declarations are dependent.
2913  case Decl::EnumConstant:
2914  case Decl::UnresolvedUsingValue:
2915  case Decl::OMPDeclareReduction:
2916  valueKind = VK_RValue;
2917  break;
2918 
2919  // Fields and indirect fields that got here must be for
2920  // pointer-to-member expressions; we just call them l-values for
2921  // internal consistency, because this subexpression doesn't really
2922  // exist in the high-level semantics.
2923  case Decl::Field:
2924  case Decl::IndirectField:
2925  assert(getLangOpts().CPlusPlus &&
2926  "building reference to field in C?");
2927 
2928  // These can't have reference type in well-formed programs, but
2929  // for internal consistency we do this anyway.
2930  type = type.getNonReferenceType();
2931  valueKind = VK_LValue;
2932  break;
2933 
2934  // Non-type template parameters are either l-values or r-values
2935  // depending on the type.
2936  case Decl::NonTypeTemplateParm: {
2937  if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2938  type = reftype->getPointeeType();
2939  valueKind = VK_LValue; // even if the parameter is an r-value reference
2940  break;
2941  }
2942 
2943  // For non-references, we need to strip qualifiers just in case
2944  // the template parameter was declared as 'const int' or whatever.
2945  valueKind = VK_RValue;
2946  type = type.getUnqualifiedType();
2947  break;
2948  }
2949 
2950  case Decl::Var:
2951  case Decl::VarTemplateSpecialization:
2952  case Decl::VarTemplatePartialSpecialization:
2953  case Decl::Decomposition:
2954  case Decl::OMPCapturedExpr:
2955  // In C, "extern void blah;" is valid and is an r-value.
2956  if (!getLangOpts().CPlusPlus &&
2957  !type.hasQualifiers() &&
2958  type->isVoidType()) {
2959  valueKind = VK_RValue;
2960  break;
2961  }
2962  LLVM_FALLTHROUGH;
2963 
2964  case Decl::ImplicitParam:
2965  case Decl::ParmVar: {
2966  // These are always l-values.
2967  valueKind = VK_LValue;
2968  type = type.getNonReferenceType();
2969 
2970  // FIXME: Does the addition of const really only apply in
2971  // potentially-evaluated contexts? Since the variable isn't actually
2972  // captured in an unevaluated context, it seems that the answer is no.
2973  if (!isUnevaluatedContext()) {
2974  QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2975  if (!CapturedType.isNull())
2976  type = CapturedType;
2977  }
2978 
2979  break;
2980  }
2981 
2982  case Decl::Binding: {
2983  // These are always lvalues.
2984  valueKind = VK_LValue;
2985  type = type.getNonReferenceType();
2986  // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2987  // decides how that's supposed to work.
2988  auto *BD = cast<BindingDecl>(VD);
2989  if (BD->getDeclContext()->isFunctionOrMethod() &&
2990  BD->getDeclContext() != CurContext)
2991  diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2992  break;
2993  }
2994 
2995  case Decl::Function: {
2996  if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2997  if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2998  type = Context.BuiltinFnTy;
2999  valueKind = VK_RValue;
3000  break;
3001  }
3002  }
3003 
3004  const FunctionType *fty = type->castAs<FunctionType>();
3005 
3006  // If we're referring to a function with an __unknown_anytype
3007  // result type, make the entire expression __unknown_anytype.
3008  if (fty->getReturnType() == Context.UnknownAnyTy) {
3009  type = Context.UnknownAnyTy;
3010  valueKind = VK_RValue;
3011  break;
3012  }
3013 
3014  // Functions are l-values in C++.
3015  if (getLangOpts().CPlusPlus) {
3016  valueKind = VK_LValue;
3017  break;
3018  }
3019 
3020  // C99 DR 316 says that, if a function type comes from a
3021  // function definition (without a prototype), that type is only
3022  // used for checking compatibility. Therefore, when referencing
3023  // the function, we pretend that we don't have the full function
3024  // type.
3025  if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3026  isa<FunctionProtoType>(fty))
3027  type = Context.getFunctionNoProtoType(fty->getReturnType(),
3028  fty->getExtInfo());
3029 
3030  // Functions are r-values in C.
3031  valueKind = VK_RValue;
3032  break;
3033  }
3034 
3035  case Decl::CXXDeductionGuide:
3036  llvm_unreachable("building reference to deduction guide");
3037 
3038  case Decl::MSProperty:
3039  valueKind = VK_LValue;
3040  break;
3041 
3042  case Decl::CXXMethod:
3043  // If we're referring to a method with an __unknown_anytype
3044  // result type, make the entire expression __unknown_anytype.
3045  // This should only be possible with a type written directly.
3046  if (const FunctionProtoType *proto
3047  = dyn_cast<FunctionProtoType>(VD->getType()))
3048  if (proto->getReturnType() == Context.UnknownAnyTy) {
3049  type = Context.UnknownAnyTy;
3050  valueKind = VK_RValue;
3051  break;
3052  }
3053 
3054  // C++ methods are l-values if static, r-values if non-static.
3055  if (cast<CXXMethodDecl>(VD)->isStatic()) {
3056  valueKind = VK_LValue;
3057  break;
3058  }
3059  LLVM_FALLTHROUGH;
3060 
3061  case Decl::CXXConversion:
3062  case Decl::CXXDestructor:
3063  case Decl::CXXConstructor:
3064  valueKind = VK_RValue;
3065  break;
3066  }
3067 
3068  return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3069  TemplateArgs);
3070  }
3071 }
3072 
3073 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3074  SmallString<32> &Target) {
3075  Target.resize(CharByteWidth * (Source.size() + 1));
3076  char *ResultPtr = &Target[0];
3077  const llvm::UTF8 *ErrorPtr;
3078  bool success =
3079  llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3080  (void)success;
3081  assert(success);
3082  Target.resize(ResultPtr - &Target[0]);
3083 }
3084 
3087  // Pick the current block, lambda, captured statement or function.
3088  Decl *currentDecl = nullptr;
3089  if (const BlockScopeInfo *BSI = getCurBlock())
3090  currentDecl = BSI->TheDecl;
3091  else if (const LambdaScopeInfo *LSI = getCurLambda())
3092  currentDecl = LSI->CallOperator;
3093  else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3094  currentDecl = CSI->TheCapturedDecl;
3095  else
3096  currentDecl = getCurFunctionOrMethodDecl();
3097 
3098  if (!currentDecl) {
3099  Diag(Loc, diag::ext_predef_outside_function);
3100  currentDecl = Context.getTranslationUnitDecl();
3101  }
3102 
3103  QualType ResTy;
3104  StringLiteral *SL = nullptr;
3105  if (cast<DeclContext>(currentDecl)->isDependentContext())
3106  ResTy = Context.DependentTy;
3107  else {
3108  // Pre-defined identifiers are of type char[x], where x is the length of
3109  // the string.
3110  auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3111  unsigned Length = Str.length();
3112 
3113  llvm::APInt LengthI(32, Length + 1);
3115  ResTy =
3117  SmallString<32> RawChars;
3119  Str, RawChars);
3120  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3121  /*IndexTypeQuals*/ 0);
3122  SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3123  /*Pascal*/ false, ResTy, Loc);
3124  } else {
3125  ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3126  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3127  /*IndexTypeQuals*/ 0);
3128  SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3129  /*Pascal*/ false, ResTy, Loc);
3130  }
3131  }
3132 
3133  return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3134 }
3135 
3138 
3139  switch (Kind) {
3140  default: llvm_unreachable("Unknown simple primary expr!");
3141  case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3142  case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3143  case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3144  case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3145  case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3146  case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3147  case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3148  }
3149 
3150  return BuildPredefinedExpr(Loc, IK);
3151 }
3152 
3154  SmallString<16> CharBuffer;
3155  bool Invalid = false;
3156  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3157  if (Invalid)
3158  return ExprError();
3159 
3160  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3161  PP, Tok.getKind());
3162  if (Literal.hadError())
3163  return ExprError();
3164 
3165  QualType Ty;
3166  if (Literal.isWide())
3167  Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3168  else if (Literal.isUTF8() && getLangOpts().Char8)
3169  Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3170  else if (Literal.isUTF16())
3171  Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3172  else if (Literal.isUTF32())
3173  Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3174  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3175  Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3176  else
3177  Ty = Context.CharTy; // 'x' -> char in C++
3178 
3180  if (Literal.isWide())
3182  else if (Literal.isUTF16())
3184  else if (Literal.isUTF32())
3186  else if (Literal.isUTF8())
3188 
3189  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3190  Tok.getLocation());
3191 
3192  if (Literal.getUDSuffix().empty())
3193  return Lit;
3194 
3195  // We're building a user-defined literal.
3196  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3197  SourceLocation UDSuffixLoc =
3198  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3199 
3200  // Make sure we're allowed user-defined literals here.
3201  if (!UDLScope)
3202  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3203 
3204  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3205  // operator "" X (ch)
3206  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3207  Lit, Tok.getLocation());
3208 }
3209 
3211  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3212  return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3213  Context.IntTy, Loc);
3214 }
3215 
3217  QualType Ty, SourceLocation Loc) {
3218  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3219 
3220  using llvm::APFloat;
3221  APFloat Val(Format);
3222 
3223  APFloat::opStatus result = Literal.GetFloatValue(Val);
3224 
3225  // Overflow is always an error, but underflow is only an error if
3226  // we underflowed to zero (APFloat reports denormals as underflow).
3227  if ((result & APFloat::opOverflow) ||
3228  ((result & APFloat::opUnderflow) && Val.isZero())) {
3229  unsigned diagnostic;
3230  SmallString<20> buffer;
3231  if (result & APFloat::opOverflow) {
3232  diagnostic = diag::warn_float_overflow;
3233  APFloat::getLargest(Format).toString(buffer);
3234  } else {
3235  diagnostic = diag::warn_float_underflow;
3236  APFloat::getSmallest(Format).toString(buffer);
3237  }
3238 
3239  S.Diag(Loc, diagnostic)
3240  << Ty
3241  << StringRef(buffer.data(), buffer.size());
3242  }
3243 
3244  bool isExact = (result == APFloat::opOK);
3245  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3246 }
3247 
3249  assert(E && "Invalid expression");
3250 
3251  if (E->isValueDependent())
3252  return false;
3253 
3254  QualType QT = E->getType();
3255  if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3256  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3257  return true;
3258  }
3259 
3260  llvm::APSInt ValueAPS;
3261  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3262 
3263  if (R.isInvalid())
3264  return true;
3265 
3266  bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3267  if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3268  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3269  << ValueAPS.toString(10) << ValueIsPositive;
3270  return true;
3271  }
3272 
3273  return false;
3274 }
3275 
3277  // Fast path for a single digit (which is quite common). A single digit
3278  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3279  if (Tok.getLength() == 1) {
3280  const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3281  return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3282  }
3283 
3284  SmallString<128> SpellingBuffer;
3285  // NumericLiteralParser wants to overread by one character. Add padding to
3286  // the buffer in case the token is copied to the buffer. If getSpelling()
3287  // returns a StringRef to the memory buffer, it should have a null char at
3288  // the EOF, so it is also safe.
3289  SpellingBuffer.resize(Tok.getLength() + 1);
3290 
3291  // Get the spelling of the token, which eliminates trigraphs, etc.
3292  bool Invalid = false;
3293  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3294  if (Invalid)
3295  return ExprError();
3296 
3297  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3298  if (Literal.hadError)
3299  return ExprError();
3300 
3301  if (Literal.hasUDSuffix()) {
3302  // We're building a user-defined literal.
3303  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3304  SourceLocation UDSuffixLoc =
3305  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3306 
3307  // Make sure we're allowed user-defined literals here.
3308  if (!UDLScope)
3309  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3310 
3311  QualType CookedTy;
3312  if (Literal.isFloatingLiteral()) {
3313  // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3314  // long double, the literal is treated as a call of the form
3315  // operator "" X (f L)
3316  CookedTy = Context.LongDoubleTy;
3317  } else {
3318  // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3319  // unsigned long long, the literal is treated as a call of the form
3320  // operator "" X (n ULL)
3321  CookedTy = Context.UnsignedLongLongTy;
3322  }
3323 
3324  DeclarationName OpName =
3325  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3326  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3327  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3328 
3329  SourceLocation TokLoc = Tok.getLocation();
3330 
3331  // Perform literal operator lookup to determine if we're building a raw
3332  // literal or a cooked one.
3333  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3334  switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3335  /*AllowRaw*/ true, /*AllowTemplate*/ true,
3336  /*AllowStringTemplate*/ false,
3337  /*DiagnoseMissing*/ !Literal.isImaginary)) {
3338  case LOLR_ErrorNoDiagnostic:
3339  // Lookup failure for imaginary constants isn't fatal, there's still the
3340  // GNU extension producing _Complex types.
3341  break;
3342  case LOLR_Error:
3343  return ExprError();
3344  case LOLR_Cooked: {
3345  Expr *Lit;
3346  if (Literal.isFloatingLiteral()) {
3347  Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3348  } else {
3349  llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3350  if (Literal.GetIntegerValue(ResultVal))
3351  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3352  << /* Unsigned */ 1;
3353  Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3354  Tok.getLocation());
3355  }
3356  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3357  }
3358 
3359  case LOLR_Raw: {
3360  // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3361  // literal is treated as a call of the form
3362  // operator "" X ("n")
3363  unsigned Length = Literal.getUDSuffixOffset();
3364  QualType StrTy = Context.getConstantArrayType(
3365  Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3366  llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3367  Expr *Lit = StringLiteral::Create(
3368  Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3369  /*Pascal*/false, StrTy, &TokLoc, 1);
3370  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3371  }
3372 
3373  case LOLR_Template: {
3374  // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3375  // template), L is treated as a call fo the form
3376  // operator "" X <'c1', 'c2', ... 'ck'>()
3377  // where n is the source character sequence c1 c2 ... ck.
3378  TemplateArgumentListInfo ExplicitArgs;
3379  unsigned CharBits = Context.getIntWidth(Context.CharTy);
3380  bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3381  llvm::APSInt Value(CharBits, CharIsUnsigned);
3382  for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3383  Value = TokSpelling[I];
3384  TemplateArgument Arg(Context, Value, Context.CharTy);
3385  TemplateArgumentLocInfo ArgInfo;
3386  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3387  }
3388  return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3389  &ExplicitArgs);
3390  }
3391  case LOLR_StringTemplate:
3392  llvm_unreachable("unexpected literal operator lookup result");
3393  }
3394  }
3395 
3396  Expr *Res;
3397 
3398  if (Literal.isFixedPointLiteral()) {
3399  QualType Ty;
3400 
3401  if (Literal.isAccum) {
3402  if (Literal.isHalf) {
3403  Ty = Context.ShortAccumTy;
3404  } else if (Literal.isLong) {
3405  Ty = Context.LongAccumTy;
3406  } else {
3407  Ty = Context.AccumTy;
3408  }
3409  } else if (Literal.isFract) {
3410  if (Literal.isHalf) {
3411  Ty = Context.ShortFractTy;
3412  } else if (Literal.isLong) {
3413  Ty = Context.LongFractTy;
3414  } else {
3415  Ty = Context.FractTy;
3416  }
3417  }
3418 
3419  if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3420 
3421  bool isSigned = !Literal.isUnsigned;
3422  unsigned scale = Context.getFixedPointScale(Ty);
3423  unsigned bit_width = Context.getTypeInfo(Ty).Width;
3424 
3425  llvm::APInt Val(bit_width, 0, isSigned);
3426  bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3427  bool ValIsZero = Val.isNullValue() && !Overflowed;
3428 
3429  auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3430  if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3431  // Clause 6.4.4 - The value of a constant shall be in the range of
3432  // representable values for its type, with exception for constants of a
3433  // fract type with a value of exactly 1; such a constant shall denote
3434  // the maximal value for the type.
3435  --Val;
3436  else if (Val.ugt(MaxVal) || Overflowed)
3437  Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3438 
3439  Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3440  Tok.getLocation(), scale);
3441  } else if (Literal.isFloatingLiteral()) {
3442  QualType Ty;
3443  if (Literal.isHalf){
3444  if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3445  Ty = Context.HalfTy;
3446  else {
3447  Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3448  return ExprError();
3449  }
3450  } else if (Literal.isFloat)
3451  Ty = Context.FloatTy;
3452  else if (Literal.isLong)
3453  Ty = Context.LongDoubleTy;
3454  else if (Literal.isFloat16)
3455  Ty = Context.Float16Ty;
3456  else if (Literal.isFloat128)
3457  Ty = Context.Float128Ty;
3458  else
3459  Ty = Context.DoubleTy;
3460 
3461  Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3462 
3463  if (Ty == Context.DoubleTy) {
3464  if (getLangOpts().SinglePrecisionConstants) {
3465  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3466  if (BTy->getKind() != BuiltinType::Float) {
3467  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3468  }
3469  } else if (getLangOpts().OpenCL &&
3470  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3471  // Impose single-precision float type when cl_khr_fp64 is not enabled.
3472  Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3473  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3474  }
3475  }
3476  } else if (!Literal.isIntegerLiteral()) {
3477  return ExprError();
3478  } else {
3479  QualType Ty;
3480 
3481  // 'long long' is a C99 or C++11 feature.
3482  if (!getLangOpts().C99 && Literal.isLongLong) {
3483  if (getLangOpts().CPlusPlus)
3484  Diag(Tok.getLocation(),
3485  getLangOpts().CPlusPlus11 ?
3486  diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3487  else
3488  Diag(Tok.getLocation(), diag::ext_c99_longlong);
3489  }
3490 
3491  // Get the value in the widest-possible width.
3492  unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3493  llvm::APInt ResultVal(MaxWidth, 0);
3494 
3495  if (Literal.GetIntegerValue(ResultVal)) {
3496  // If this value didn't fit into uintmax_t, error and force to ull.
3497  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3498  << /* Unsigned */ 1;
3499  Ty = Context.UnsignedLongLongTy;
3500  assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3501  "long long is not intmax_t?");
3502  } else {
3503  // If this value fits into a ULL, try to figure out what else it fits into
3504  // according to the rules of C99 6.4.4.1p5.
3505 
3506  // Octal, Hexadecimal, and integers with a U suffix are allowed to
3507  // be an unsigned int.
3508  bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3509 
3510  // Check from smallest to largest, picking the smallest type we can.
3511  unsigned Width = 0;
3512 
3513  // Microsoft specific integer suffixes are explicitly sized.
3514  if (Literal.MicrosoftInteger) {
3515  if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3516  Width = 8;
3517  Ty = Context.CharTy;
3518  } else {
3519  Width = Literal.MicrosoftInteger;
3520  Ty = Context.getIntTypeForBitwidth(Width,
3521  /*Signed=*/!Literal.isUnsigned);
3522  }
3523  }
3524 
3525  if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3526  // Are int/unsigned possibilities?
3527  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3528 
3529  // Does it fit in a unsigned int?
3530  if (ResultVal.isIntN(IntSize)) {
3531  // Does it fit in a signed int?
3532  if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3533  Ty = Context.IntTy;
3534  else if (AllowUnsigned)
3535  Ty = Context.UnsignedIntTy;
3536  Width = IntSize;
3537  }
3538  }
3539 
3540  // Are long/unsigned long possibilities?
3541  if (Ty.isNull() && !Literal.isLongLong) {
3542  unsigned LongSize = Context.getTargetInfo().getLongWidth();
3543 
3544  // Does it fit in a unsigned long?
3545  if (ResultVal.isIntN(LongSize)) {
3546  // Does it fit in a signed long?
3547  if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3548  Ty = Context.LongTy;
3549  else if (AllowUnsigned)
3550  Ty = Context.UnsignedLongTy;
3551  // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3552  // is compatible.
3553  else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3554  const unsigned LongLongSize =
3555  Context.getTargetInfo().getLongLongWidth();
3556  Diag(Tok.getLocation(),
3557  getLangOpts().CPlusPlus
3558  ? Literal.isLong
3559  ? diag::warn_old_implicitly_unsigned_long_cxx
3560  : /*C++98 UB*/ diag::
3561  ext_old_implicitly_unsigned_long_cxx
3562  : diag::warn_old_implicitly_unsigned_long)
3563  << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3564  : /*will be ill-formed*/ 1);
3565  Ty = Context.UnsignedLongTy;
3566  }
3567  Width = LongSize;
3568  }
3569  }
3570 
3571  // Check long long if needed.
3572  if (Ty.isNull()) {
3573  unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3574 
3575  // Does it fit in a unsigned long long?
3576  if (ResultVal.isIntN(LongLongSize)) {
3577  // Does it fit in a signed long long?
3578  // To be compatible with MSVC, hex integer literals ending with the
3579  // LL or i64 suffix are always signed in Microsoft mode.
3580  if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3581  (getLangOpts().MSVCCompat && Literal.isLongLong)))
3582  Ty = Context.LongLongTy;
3583  else if (AllowUnsigned)
3584  Ty = Context.UnsignedLongLongTy;
3585  Width = LongLongSize;
3586  }
3587  }
3588 
3589  // If we still couldn't decide a type, we probably have something that
3590  // does not fit in a signed long long, but has no U suffix.
3591  if (Ty.isNull()) {
3592  Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3593  Ty = Context.UnsignedLongLongTy;
3594  Width = Context.getTargetInfo().getLongLongWidth();
3595  }
3596 
3597  if (ResultVal.getBitWidth() != Width)
3598  ResultVal = ResultVal.trunc(Width);
3599  }
3600  Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3601  }
3602 
3603  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3604  if (Literal.isImaginary) {
3605  Res = new (Context) ImaginaryLiteral(Res,
3606  Context.getComplexType(Res->getType()));
3607 
3608  Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3609  }
3610  return Res;
3611 }
3612 
3614  assert(E && "ActOnParenExpr() missing expr");
3615  return new (Context) ParenExpr(L, R, E);
3616 }
3617 
3619  SourceLocation Loc,
3620  SourceRange ArgRange) {
3621  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3622  // scalar or vector data type argument..."
3623  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3624  // type (C99 6.2.5p18) or void.
3625  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3626  S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3627  << T << ArgRange;
3628  return true;
3629  }
3630 
3631  assert((T->isVoidType() || !T->isIncompleteType()) &&
3632  "Scalar types should always be complete");
3633  return false;
3634 }
3635 
3637  SourceLocation Loc,
3638  SourceRange ArgRange,
3639  UnaryExprOrTypeTrait TraitKind) {
3640  // Invalid types must be hard errors for SFINAE in C++.
3641  if (S.LangOpts.CPlusPlus)
3642  return true;
3643 
3644  // C99 6.5.3.4p1:
3645  if (T->isFunctionType() &&
3646  (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3647  TraitKind == UETT_PreferredAlignOf)) {
3648  // sizeof(function)/alignof(function) is allowed as an extension.
3649  S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3650  << TraitKind << ArgRange;
3651  return false;
3652  }
3653 
3654  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3655  // this is an error (OpenCL v1.1 s6.3.k)
3656  if (T->isVoidType()) {
3657  unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3658  : diag::ext_sizeof_alignof_void_type;
3659  S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3660  return false;
3661  }
3662 
3663  return true;
3664 }
3665 
3667  SourceLocation Loc,
3668  SourceRange ArgRange,
3669  UnaryExprOrTypeTrait TraitKind) {
3670  // Reject sizeof(interface) and sizeof(interface<proto>) if the
3671  // runtime doesn't allow it.
3673  S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3674  << T << (TraitKind == UETT_SizeOf)
3675  << ArgRange;
3676  return true;
3677  }
3678 
3679  return false;
3680 }
3681 
3682 /// Check whether E is a pointer from a decayed array type (the decayed
3683 /// pointer type is equal to T) and emit a warning if it is.
3685  Expr *E) {
3686  // Don't warn if the operation changed the type.
3687  if (T != E->getType())
3688  return;
3689 
3690  // Now look for array decays.
3691  ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3692  if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3693  return;
3694 
3695  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3696  << ICE->getType()
3697  << ICE->getSubExpr()->getType();
3698 }
3699 
3700 /// Check the constraints on expression operands to unary type expression
3701 /// and type traits.
3702 ///
3703 /// Completes any types necessary and validates the constraints on the operand
3704 /// expression. The logic mostly mirrors the type-based overload, but may modify
3705 /// the expression as it completes the type for that expression through template
3706 /// instantiation, etc.
3708  UnaryExprOrTypeTrait ExprKind) {
3709  QualType ExprTy = E->getType();
3710  assert(!ExprTy->isReferenceType());
3711 
3712  if (ExprKind == UETT_VecStep)
3713  return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3714  E->getSourceRange());
3715 
3716  // Whitelist some types as extensions
3717  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3718  E->getSourceRange(), ExprKind))
3719  return false;
3720 
3721  // 'alignof' applied to an expression only requires the base element type of
3722  // the expression to be complete. 'sizeof' requires the expression's type to
3723  // be complete (and will attempt to complete it if it's an array of unknown
3724  // bound).
3725  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3726  if (RequireCompleteType(E->getExprLoc(),
3727  Context.getBaseElementType(E->getType()),
3728  diag::err_sizeof_alignof_incomplete_type, ExprKind,
3729  E->getSourceRange()))
3730  return true;
3731  } else {
3732  if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3733  ExprKind, E->getSourceRange()))
3734  return true;
3735  }
3736 
3737  // Completing the expression's type may have changed it.
3738  ExprTy = E->getType();
3739  assert(!ExprTy->isReferenceType());
3740 
3741  if (ExprTy->isFunctionType()) {
3742  Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3743  << ExprKind << E->getSourceRange();
3744  return true;
3745  }
3746 
3747  // The operand for sizeof and alignof is in an unevaluated expression context,
3748  // so side effects could result in unintended consequences.
3749  if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3750  ExprKind == UETT_PreferredAlignOf) &&
3751  !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3752  Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3753 
3754  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3755  E->getSourceRange(), ExprKind))
3756  return true;
3757 
3758  if (ExprKind == UETT_SizeOf) {
3759  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3760  if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3761  QualType OType = PVD->getOriginalType();
3762  QualType Type = PVD->getType();
3763  if (Type->isPointerType() && OType->isArrayType()) {
3764  Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3765  << Type << OType;
3766  Diag(PVD->getLocation(), diag::note_declared_at);
3767  }
3768  }
3769  }
3770 
3771  // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3772  // decays into a pointer and returns an unintended result. This is most
3773  // likely a typo for "sizeof(array) op x".
3774  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3775  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3776  BO->getLHS());
3777  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3778  BO->getRHS());
3779  }
3780  }
3781 
3782  return false;
3783 }
3784 
3785 /// Check the constraints on operands to unary expression and type
3786 /// traits.
3787 ///
3788 /// This will complete any types necessary, and validate the various constraints
3789 /// on those operands.
3790 ///
3791 /// The UsualUnaryConversions() function is *not* called by this routine.
3792 /// C99 6.3.2.1p[2-4] all state:
3793 /// Except when it is the operand of the sizeof operator ...
3794 ///
3795 /// C++ [expr.sizeof]p4
3796 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3797 /// standard conversions are not applied to the operand of sizeof.
3798 ///
3799 /// This policy is followed for all of the unary trait expressions.
3801  SourceLocation OpLoc,
3802  SourceRange ExprRange,
3803  UnaryExprOrTypeTrait ExprKind) {
3804  if (ExprType->isDependentType())
3805  return false;
3806 
3807  // C++ [expr.sizeof]p2:
3808  // When applied to a reference or a reference type, the result
3809  // is the size of the referenced type.
3810  // C++11 [expr.alignof]p3:
3811  // When alignof is applied to a reference type, the result
3812  // shall be the alignment of the referenced type.
3813  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3814  ExprType = Ref->getPointeeType();
3815 
3816  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3817  // When alignof or _Alignof is applied to an array type, the result
3818  // is the alignment of the element type.
3819  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3820  ExprKind == UETT_OpenMPRequiredSimdAlign)
3821  ExprType = Context.getBaseElementType(ExprType);
3822 
3823  if (ExprKind == UETT_VecStep)
3824  return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3825 
3826  // Whitelist some types as extensions
3827  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3828  ExprKind))
3829  return false;
3830 
3831  if (RequireCompleteType(OpLoc, ExprType,
3832  diag::err_sizeof_alignof_incomplete_type,
3833  ExprKind, ExprRange))
3834  return true;
3835 
3836  if (ExprType->isFunctionType()) {
3837  Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3838  << ExprKind << ExprRange;
3839  return true;
3840  }
3841 
3842  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3843  ExprKind))
3844  return true;
3845 
3846  return false;
3847 }
3848 
3849 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3850  E = E->IgnoreParens();
3851 
3852  // Cannot know anything else if the expression is dependent.
3853  if (E->isTypeDependent())
3854  return false;
3855 
3856  if (E->getObjectKind() == OK_BitField) {
3857  S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3858  << 1 << E->getSourceRange();
3859  return true;
3860  }
3861 
3862  ValueDecl *D = nullptr;
3863  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3864  D = DRE->getDecl();
3865  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3866  D = ME->getMemberDecl();
3867  }
3868 
3869  // If it's a field, require the containing struct to have a
3870  // complete definition so that we can compute the layout.
3871  //
3872  // This can happen in C++11 onwards, either by naming the member
3873  // in a way that is not transformed into a member access expression
3874  // (in an unevaluated operand, for instance), or by naming the member
3875  // in a trailing-return-type.
3876  //
3877  // For the record, since __alignof__ on expressions is a GCC
3878  // extension, GCC seems to permit this but always gives the
3879  // nonsensical answer 0.
3880  //
3881  // We don't really need the layout here --- we could instead just
3882  // directly check for all the appropriate alignment-lowing
3883  // attributes --- but that would require duplicating a lot of
3884  // logic that just isn't worth duplicating for such a marginal
3885  // use-case.
3886  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3887  // Fast path this check, since we at least know the record has a
3888  // definition if we can find a member of it.
3889  if (!FD->getParent()->isCompleteDefinition()) {
3890  S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3891  << E->getSourceRange();
3892  return true;
3893  }
3894 
3895  // Otherwise, if it's a field, and the field doesn't have
3896  // reference type, then it must have a complete type (or be a
3897  // flexible array member, which we explicitly want to
3898  // white-list anyway), which makes the following checks trivial.
3899  if (!FD->getType()->isReferenceType())
3900  return false;
3901  }
3902 
3903  return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3904 }
3905 
3907  E = E->IgnoreParens();
3908 
3909  // Cannot know anything else if the expression is dependent.
3910  if (E->isTypeDependent())
3911  return false;
3912 
3913  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3914 }
3915 
3917  CapturingScopeInfo *CSI) {
3918  assert(T->isVariablyModifiedType());
3919  assert(CSI != nullptr);
3920 
3921  // We're going to walk down into the type and look for VLA expressions.
3922  do {
3923  const Type *Ty = T.getTypePtr();
3924  switch (Ty->getTypeClass()) {
3925 #define TYPE(Class, Base)
3926 #define ABSTRACT_TYPE(Class, Base)
3927 #define NON_CANONICAL_TYPE(Class, Base)
3928 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3929 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3930 #include "clang/AST/TypeNodes.def"
3931  T = QualType();
3932  break;
3933  // These types are never variably-modified.
3934  case Type::Builtin:
3935  case Type::Complex:
3936  case Type::Vector:
3937  case Type::ExtVector:
3938  case Type::Record:
3939  case Type::Enum:
3940  case Type::Elaborated:
3941  case Type::TemplateSpecialization:
3942  case Type::ObjCObject:
3943  case Type::ObjCInterface:
3944  case Type::ObjCObjectPointer:
3945  case Type::ObjCTypeParam:
3946  case Type::Pipe:
3947  llvm_unreachable("type class is never variably-modified!");
3948  case Type::Adjusted:
3949  T = cast<AdjustedType>(Ty)->getOriginalType();
3950  break;
3951  case Type::Decayed:
3952  T = cast<DecayedType>(Ty)->getPointeeType();
3953  break;
3954  case Type::Pointer:
3955  T = cast<PointerType>(Ty)->getPointeeType();
3956  break;
3957  case Type::BlockPointer:
3958  T = cast<BlockPointerType>(Ty)->getPointeeType();
3959  break;
3960  case Type::LValueReference:
3961  case Type::RValueReference:
3962  T = cast<ReferenceType>(Ty)->getPointeeType();
3963  break;
3964  case Type::MemberPointer:
3965  T = cast<MemberPointerType>(Ty)->getPointeeType();
3966  break;
3967  case Type::ConstantArray:
3968  case Type::IncompleteArray:
3969  // Losing element qualification here is fine.
3970  T = cast<ArrayType>(Ty)->getElementType();
3971  break;
3972  case Type::VariableArray: {
3973  // Losing element qualification here is fine.
3974  const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3975 
3976  // Unknown size indication requires no size computation.
3977  // Otherwise, evaluate and record it.
3978  if (auto Size = VAT->getSizeExpr()) {
3979  if (!CSI->isVLATypeCaptured(VAT)) {
3980  RecordDecl *CapRecord = nullptr;
3981  if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3982  CapRecord = LSI->Lambda;
3983  } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3984  CapRecord = CRSI->TheRecordDecl;
3985  }
3986  if (CapRecord) {
3987  auto ExprLoc = Size->getExprLoc();
3988  auto SizeType = Context.getSizeType();
3989  // Build the non-static data member.
3990  auto Field =
3991  FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3992  /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3993  /*BW*/ nullptr, /*Mutable*/ false,
3994  /*InitStyle*/ ICIS_NoInit);
3995  Field->setImplicit(true);
3996  Field->setAccess(AS_private);
3997  Field->setCapturedVLAType(VAT);
3998  CapRecord->addDecl(Field);
3999 
4000  CSI->addVLATypeCapture(ExprLoc, SizeType);
4001  }
4002  }
4003  }
4004  T = VAT->getElementType();
4005  break;
4006  }
4007  case Type::FunctionProto:
4008  case Type::FunctionNoProto:
4009  T = cast<FunctionType>(Ty)->getReturnType();
4010  break;
4011  case Type::Paren:
4012  case Type::TypeOf:
4013  case Type::UnaryTransform:
4014  case Type::Attributed:
4015  case Type::SubstTemplateTypeParm:
4016  case Type::PackExpansion:
4017  // Keep walking after single level desugaring.
4018  T = T.getSingleStepDesugaredType(Context);
4019  break;
4020  case Type::Typedef:
4021  T = cast<TypedefType>(Ty)->desugar();
4022  break;
4023  case Type::Decltype:
4024  T = cast<DecltypeType>(Ty)->desugar();
4025  break;
4026  case Type::Auto:
4027  case Type::DeducedTemplateSpecialization:
4028  T = cast<DeducedType>(Ty)->getDeducedType();
4029  break;
4030  case Type::TypeOfExpr:
4031  T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4032  break;
4033  case Type::Atomic:
4034  T = cast<AtomicType>(Ty)->getValueType();
4035  break;
4036  }
4037  } while (!T.isNull() && T->isVariablyModifiedType());
4038 }
4039 
4040 /// Build a sizeof or alignof expression given a type operand.
4041 ExprResult
4043  SourceLocation OpLoc,
4044  UnaryExprOrTypeTrait ExprKind,
4045  SourceRange R) {
4046  if (!TInfo)
4047  return ExprError();
4048 
4049  QualType T = TInfo->getType();
4050 
4051  if (!T->isDependentType() &&
4052  CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4053  return ExprError();
4054 
4055  if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4056  if (auto *TT = T->getAs<TypedefType>()) {
4057  for (auto I = FunctionScopes.rbegin(),
4058  E = std::prev(FunctionScopes.rend());
4059  I != E; ++I) {
4060  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4061  if (CSI == nullptr)
4062  break;
4063  DeclContext *DC = nullptr;
4064  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4065  DC = LSI->CallOperator;
4066  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4067  DC = CRSI->TheCapturedDecl;
4068  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4069  DC = BSI->TheDecl;
4070  if (DC) {
4071  if (DC->containsDecl(TT->getDecl()))
4072  break;
4073  captureVariablyModifiedType(Context, T, CSI);
4074  }
4075  }
4076  }
4077  }
4078 
4079  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4080  return new (Context) UnaryExprOrTypeTraitExpr(
4081  ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4082 }
4083 
4084 /// Build a sizeof or alignof expression given an expression
4085 /// operand.
4086 ExprResult
4088  UnaryExprOrTypeTrait ExprKind) {
4089  ExprResult PE = CheckPlaceholderExpr(E);
4090  if (PE.isInvalid())
4091  return ExprError();
4092 
4093  E = PE.get();
4094 
4095  // Verify that the operand is valid.
4096  bool isInvalid = false;
4097  if (E->isTypeDependent()) {
4098  // Delay type-checking for type-dependent expressions.
4099  } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4100  isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4101  } else if (ExprKind == UETT_VecStep) {
4102  isInvalid = CheckVecStepExpr(E);
4103  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4104  Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4105  isInvalid = true;
4106  } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4107  Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4108  isInvalid = true;
4109  } else {
4110  isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4111  }
4112 
4113  if (isInvalid)
4114  return ExprError();
4115 
4116  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4117  PE = TransformToPotentiallyEvaluated(E);
4118  if (PE.isInvalid()) return ExprError();
4119  E = PE.get();
4120  }
4121 
4122  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4123  return new (Context) UnaryExprOrTypeTraitExpr(
4124  ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4125 }
4126 
4127 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4128 /// expr and the same for @c alignof and @c __alignof
4129 /// Note that the ArgRange is invalid if isType is false.
4130 ExprResult
4132  UnaryExprOrTypeTrait ExprKind, bool IsType,
4133  void *TyOrEx, SourceRange ArgRange) {
4134  // If error parsing type, ignore.
4135  if (!TyOrEx) return ExprError();
4136 
4137  if (IsType) {
4138  TypeSourceInfo *TInfo;
4139  (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4140  return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4141  }
4142 
4143  Expr *ArgEx = (Expr *)TyOrEx;
4144  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4145  return Result;
4146 }
4147 
4149  bool IsReal) {
4150  if (V.get()->isTypeDependent())
4151  return S.Context.DependentTy;
4152 
4153  // _Real and _Imag are only l-values for normal l-values.
4154  if (V.get()->getObjectKind() != OK_Ordinary) {
4155  V = S.DefaultLvalueConversion(V.get());
4156  if (V.isInvalid())
4157  return QualType();
4158  }
4159 
4160  // These operators return the element type of a complex type.
4161  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4162  return CT->getElementType();
4163 
4164  // Otherwise they pass through real integer and floating point types here.
4165  if (V.get()->getType()->isArithmeticType())
4166  return V.get()->getType();
4167 
4168  // Test for placeholders.
4169  ExprResult PR = S.CheckPlaceholderExpr(V.get());
4170  if (PR.isInvalid()) return QualType();
4171  if (PR.get() != V.get()) {
4172  V = PR;
4173  return CheckRealImagOperand(S, V, Loc, IsReal);
4174  }
4175 
4176  // Reject anything else.
4177  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4178  << (IsReal ? "__real" : "__imag");
4179  return QualType();
4180 }
4181 
4182 
4183 
4184 ExprResult
4186  tok::TokenKind Kind, Expr *Input) {
4187  UnaryOperatorKind Opc;
4188  switch (Kind) {
4189  default: llvm_unreachable("Unknown unary op!");
4190  case tok::plusplus: Opc = UO_PostInc; break;
4191  case tok::minusminus: Opc = UO_PostDec; break;
4192  }
4193 
4194  // Since this might is a postfix expression, get rid of ParenListExprs.
4195  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4196  if (Result.isInvalid()) return ExprError();
4197  Input = Result.get();
4198 
4199  return BuildUnaryOp(S, OpLoc, Opc, Input);
4200 }
4201 
4202 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4203 ///
4204 /// \return true on error
4206  SourceLocation opLoc,
4207  Expr *op) {
4208  assert(op->getType()->isObjCObjectPointerType());
4210  !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4211  return false;
4212 
4213  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4214  << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4215  << op->getSourceRange();
4216  return true;
4217 }
4218 
4220  auto *BaseNoParens = Base->IgnoreParens();
4221  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4222  return MSProp->getPropertyDecl()->getType()->isArrayType();
4223  return isa<MSPropertySubscriptExpr>(BaseNoParens);
4224 }
4225 
4226 ExprResult
4228  Expr *idx, SourceLocation rbLoc) {
4229  if (base && !base->getType().isNull() &&
4230  base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4231  return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4232  /*Length=*/nullptr, rbLoc);
4233 
4234  // Since this might be a postfix expression, get rid of ParenListExprs.
4235  if (isa<ParenListExpr>(base)) {
4236  ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4237  if (result.isInvalid()) return ExprError();
4238  base = result.get();
4239  }
4240 
4241  // Handle any non-overload placeholder types in the base and index
4242  // expressions. We can't handle overloads here because the other
4243  // operand might be an overloadable type, in which case the overload
4244  // resolution for the operator overload should get the first crack
4245  // at the overload.
4246  bool IsMSPropertySubscript = false;
4247  if (base->getType()->isNonOverloadPlaceholderType()) {
4248  IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4249  if (!IsMSPropertySubscript) {
4250  ExprResult result = CheckPlaceholderExpr(base);
4251  if (result.isInvalid())
4252  return ExprError();
4253  base = result.get();
4254  }
4255  }
4256  if (idx->getType()->isNonOverloadPlaceholderType()) {
4257  ExprResult result = CheckPlaceholderExpr(idx);
4258  if (result.isInvalid()) return ExprError();
4259  idx = result.get();
4260  }
4261 
4262  // Build an unanalyzed expression if either operand is type-dependent.
4263  if (getLangOpts().CPlusPlus &&
4264  (base->isTypeDependent() || idx->isTypeDependent())) {
4265  return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4266  VK_LValue, OK_Ordinary, rbLoc);
4267  }
4268 
4269  // MSDN, property (C++)
4270  // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4271  // This attribute can also be used in the declaration of an empty array in a
4272  // class or structure definition. For example:
4273  // __declspec(property(get=GetX, put=PutX)) int x[];
4274  // The above statement indicates that x[] can be used with one or more array
4275  // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4276  // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4277  if (IsMSPropertySubscript) {
4278  // Build MS property subscript expression if base is MS property reference
4279  // or MS property subscript.
4280  return new (Context) MSPropertySubscriptExpr(
4281  base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4282  }
4283 
4284  // Use C++ overloaded-operator rules if either operand has record
4285  // type. The spec says to do this if either type is *overloadable*,
4286  // but enum types can't declare subscript operators or conversion
4287  // operators, so there's nothing interesting for overload resolution
4288  // to do if there aren't any record types involved.
4289  //
4290  // ObjC pointers have their own subscripting logic that is not tied
4291  // to overload resolution and so should not take this path.
4292  if (getLangOpts().CPlusPlus &&
4293  (base->getType()->isRecordType() ||
4294  (!base->getType()->isObjCObjectPointerType() &&
4295  idx->getType()->isRecordType()))) {
4296  return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4297  }
4298 
4299  ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4300 
4301  if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4302  CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4303 
4304  return Res;
4305 }
4306 
4307 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4308  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4309  const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4310 
4311  // For expressions like `&(*s).b`, the base is recorded and what should be
4312  // checked.
4313  const MemberExpr *Member = nullptr;
4314  while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4315  StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4316 
4317  LastRecord.PossibleDerefs.erase(StrippedExpr);
4318 }
4319 
4320 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4321  QualType ResultTy = E->getType();
4322  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4323 
4324  // Bail if the element is an array since it is not memory access.
4325  if (isa<ArrayType>(ResultTy))
4326  return;
4327 
4328  if (ResultTy->hasAttr(attr::NoDeref)) {
4329  LastRecord.PossibleDerefs.insert(E);
4330  return;
4331  }
4332 
4333  // Check if the base type is a pointer to a member access of a struct
4334  // marked with noderef.
4335  const Expr *Base = E->getBase();
4336  QualType BaseTy = Base->getType();
4337  if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4338  // Not a pointer access
4339  return;
4340 
4341  const MemberExpr *Member = nullptr;
4342  while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4343  Member->isArrow())
4344  Base = Member->getBase();
4345 
4346  if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4347  if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4348  LastRecord.PossibleDerefs.insert(E);
4349  }
4350 }
4351 
4353  Expr *LowerBound,
4354  SourceLocation ColonLoc, Expr *Length,
4355  SourceLocation RBLoc) {
4356  if (Base->getType()->isPlaceholderType() &&
4358  BuiltinType::OMPArraySection)) {
4359  ExprResult Result = CheckPlaceholderExpr(Base);
4360  if (Result.isInvalid())
4361  return ExprError();
4362  Base = Result.get();
4363  }
4364  if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4365  ExprResult Result = CheckPlaceholderExpr(LowerBound);
4366  if (Result.isInvalid())
4367  return ExprError();
4368  Result = DefaultLvalueConversion(Result.get());
4369  if (Result.isInvalid())
4370  return ExprError();
4371  LowerBound = Result.get();
4372  }
4373  if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4374  ExprResult Result = CheckPlaceholderExpr(Length);
4375  if (Result.isInvalid())
4376  return ExprError();
4377  Result = DefaultLvalueConversion(Result.get());
4378  if (Result.isInvalid())
4379  return ExprError();
4380  Length = Result.get();
4381  }
4382 
4383  // Build an unanalyzed expression if either operand is type-dependent.
4384  if (Base->isTypeDependent() ||
4385  (LowerBound &&
4386  (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4387  (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4388  return new (Context)
4389  OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4390  VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4391  }
4392 
4393  // Perform default conversions.
4395  QualType ResultTy;
4396  if (OriginalTy->isAnyPointerType()) {
4397  ResultTy = OriginalTy->getPointeeType();
4398  } else if (OriginalTy->isArrayType()) {
4399  ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4400  } else {
4401  return ExprError(
4402  Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4403  << Base->getSourceRange());
4404  }
4405  // C99 6.5.2.1p1
4406  if (LowerBound) {
4407  auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4408  LowerBound);
4409  if (Res.isInvalid())
4410  return ExprError(Diag(LowerBound->getExprLoc(),
4411  diag::err_omp_typecheck_section_not_integer)
4412  << 0 << LowerBound->getSourceRange());
4413  LowerBound = Res.get();
4414 
4415  if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4416  LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4417  Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4418  << 0 << LowerBound->getSourceRange();
4419  }
4420  if (Length) {
4421  auto Res =
4422  PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4423  if (Res.isInvalid())
4424  return ExprError(Diag(Length->getExprLoc(),
4425  diag::err_omp_typecheck_section_not_integer)
4426  << 1 << Length->getSourceRange());
4427  Length = Res.get();
4428 
4429  if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4430  Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4431  Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4432  << 1 << Length->getSourceRange();
4433  }
4434 
4435  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4436  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4437  // type. Note that functions are not objects, and that (in C99 parlance)
4438  // incomplete types are not object types.
4439  if (ResultTy->isFunctionType()) {
4440  Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4441  << ResultTy << Base->getSourceRange();
4442  return ExprError();
4443  }
4444 
4445  if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4446  diag::err_omp_section_incomplete_type, Base))
4447  return ExprError();
4448 
4449  if (LowerBound && !OriginalTy->isAnyPointerType()) {
4450  Expr::EvalResult Result;
4451  if (LowerBound->EvaluateAsInt(Result, Context)) {
4452  // OpenMP 4.5, [2.4 Array Sections]
4453  // The array section must be a subset of the original array.
4454  llvm::APSInt LowerBoundValue = Result.Val.getInt();
4455  if (LowerBoundValue.isNegative()) {
4456  Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4457  << LowerBound->getSourceRange();
4458  return ExprError();
4459  }
4460  }
4461  }
4462 
4463  if (Length) {
4464  Expr::EvalResult Result;
4465  if (Length->EvaluateAsInt(Result, Context)) {
4466  // OpenMP 4.5, [2.4 Array Sections]
4467  // The length must evaluate to non-negative integers.
4468  llvm::APSInt LengthValue = Result.Val.getInt();
4469  if (LengthValue.isNegative()) {
4470  Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4471  << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4472  << Length->getSourceRange();
4473  return ExprError();
4474  }
4475  }
4476  } else if (ColonLoc.isValid() &&
4477  (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4478  !OriginalTy->isVariableArrayType()))) {
4479  // OpenMP 4.5, [2.4 Array Sections]
4480  // When the size of the array dimension is not known, the length must be
4481  // specified explicitly.
4482  Diag(ColonLoc, diag::err_omp_section_length_undefined)
4483  << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4484  return ExprError();
4485  }
4486 
4487  if (!Base->getType()->isSpecificPlaceholderType(
4488  BuiltinType::OMPArraySection)) {
4489  ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4490  if (Result.isInvalid())
4491  return ExprError();
4492  Base = Result.get();
4493  }
4494  return new (Context)
4495  OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4496  VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4497 }
4498 
4499 ExprResult
4501  Expr *Idx, SourceLocation RLoc) {
4502  Expr *LHSExp = Base;
4503  Expr *RHSExp = Idx;
4504 
4505  ExprValueKind VK = VK_LValue;
4507 
4508  // Per C++ core issue 1213, the result is an xvalue if either operand is
4509  // a non-lvalue array, and an lvalue otherwise.
4510  if (getLangOpts().CPlusPlus11) {
4511  for (auto *Op : {LHSExp, RHSExp}) {
4512  Op = Op->IgnoreImplicit();
4513  if (Op->getType()->isArrayType() && !Op->isLValue())
4514  VK = VK_XValue;
4515  }
4516  }
4517 
4518  // Perform default conversions.
4519  if (!LHSExp->getType()->getAs<VectorType>()) {
4520  ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4521  if (Result.isInvalid())
4522  return ExprError();
4523  LHSExp = Result.get();
4524  }
4525  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4526  if (Result.isInvalid())
4527  return ExprError();
4528  RHSExp = Result.get();
4529 
4530  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4531 
4532  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4533  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4534  // in the subscript position. As a result, we need to derive the array base
4535  // and index from the expression types.
4536  Expr *BaseExpr, *IndexExpr;
4537  QualType ResultType;
4538  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4539  BaseExpr = LHSExp;
4540  IndexExpr = RHSExp;
4541  ResultType = Context.DependentTy;
4542  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4543  BaseExpr = LHSExp;
4544  IndexExpr = RHSExp;
4545  ResultType = PTy->getPointeeType();
4546  } else if (const ObjCObjectPointerType *PTy =
4547  LHSTy->getAs<ObjCObjectPointerType>()) {
4548  BaseExpr = LHSExp;
4549  IndexExpr = RHSExp;
4550 
4551  // Use custom logic if this should be the pseudo-object subscript
4552  // expression.
4553  if (!LangOpts.isSubscriptPointerArithmetic())
4554  return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4555  nullptr);
4556 
4557  ResultType = PTy->getPointeeType();
4558  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4559  // Handle the uncommon case of "123[Ptr]".
4560  BaseExpr = RHSExp;
4561  IndexExpr = LHSExp;
4562  ResultType = PTy->getPointeeType();
4563  } else if (const ObjCObjectPointerType *PTy =
4564  RHSTy->getAs<ObjCObjectPointerType>()) {
4565  // Handle the uncommon case of "123[Ptr]".
4566  BaseExpr = RHSExp;
4567  IndexExpr = LHSExp;
4568  ResultType = PTy->getPointeeType();
4569  if (!LangOpts.isSubscriptPointerArithmetic()) {
4570  Diag(LLoc, diag::err_subscript_nonfragile_interface)
4571  << ResultType << BaseExpr->getSourceRange();
4572  return ExprError();
4573  }
4574  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4575  BaseExpr = LHSExp; // vectors: V[123]
4576  IndexExpr = RHSExp;
4577  // We apply C++ DR1213 to vector subscripting too.
4578  if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4579  ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4580  if (Materialized.isInvalid())
4581  return ExprError();
4582  LHSExp = Materialized.get();
4583  }
4584  VK = LHSExp->getValueKind();
4585  if (VK != VK_RValue)
4586  OK = OK_VectorComponent;
4587 
4588  ResultType = VTy->getElementType();
4589  QualType BaseType = BaseExpr->getType();
4590  Qualifiers BaseQuals = BaseType.getQualifiers();
4591  Qualifiers MemberQuals = ResultType.getQualifiers();
4592  Qualifiers Combined = BaseQuals + MemberQuals;
4593  if (Combined != MemberQuals)
4594  ResultType = Context.getQualifiedType(ResultType, Combined);
4595  } else if (LHSTy->isArrayType()) {
4596  // If we see an array that wasn't promoted by
4597  // DefaultFunctionArrayLvalueConversion, it must be an array that
4598  // wasn't promoted because of the C90 rule that doesn't
4599  // allow promoting non-lvalue arrays. Warn, then
4600  // force the promotion here.
4601  Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4602  << LHSExp->getSourceRange();
4603  LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4604  CK_ArrayToPointerDecay).get();
4605  LHSTy = LHSExp->getType();
4606 
4607  BaseExpr = LHSExp;
4608  IndexExpr = RHSExp;
4609  ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4610  } else if (RHSTy->isArrayType()) {
4611  // Same as previous, except for 123[f().a] case
4612  Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4613  << RHSExp->getSourceRange();
4614  RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4615  CK_ArrayToPointerDecay).get();
4616  RHSTy = RHSExp->getType();
4617 
4618  BaseExpr = RHSExp;
4619  IndexExpr = LHSExp;
4620  ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4621  } else {
4622  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4623  << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4624  }
4625  // C99 6.5.2.1p1
4626  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4627  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4628  << IndexExpr->getSourceRange());
4629 
4630  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4631  IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4632  && !IndexExpr->isTypeDependent())
4633  Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4634 
4635  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4636  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4637  // type. Note that Functions are not objects, and that (in C99 parlance)
4638  // incomplete types are not object types.
4639  if (ResultType->isFunctionType()) {
4640  Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4641  << ResultType << BaseExpr->getSourceRange();
4642  return ExprError();
4643  }
4644 
4645  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4646  // GNU extension: subscripting on pointer to void
4647  Diag(LLoc, diag::ext_gnu_subscript_void_type)
4648  << BaseExpr->getSourceRange();
4649 
4650  // C forbids expressions of unqualified void type from being l-values.
4651  // See IsCForbiddenLValueType.
4652  if (!ResultType.hasQualifiers()) VK = VK_RValue;
4653  } else if (!ResultType->isDependentType() &&
4654  RequireCompleteType(LLoc, ResultType,
4655  diag::err_subscript_incomplete_type, BaseExpr))
4656  return ExprError();
4657 
4658  assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4659  !ResultType.isCForbiddenLValueType());
4660 
4661  return new (Context)
4662  ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4663 }
4664 
4666  ParmVarDecl *Param) {
4667  if (Param->hasUnparsedDefaultArg()) {
4668  Diag(CallLoc,
4669  diag::err_use_of_default_argument_to_function_declared_later) <<
4670  FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4671  Diag(UnparsedDefaultArgLocs[Param],
4672  diag::note_default_argument_declared_here);
4673  return true;
4674  }
4675 
4676  if (Param->hasUninstantiatedDefaultArg()) {
4677  Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4678 
4680  *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4681 
4682  // Instantiate the expression.
4683  //
4684  // FIXME: Pass in a correct Pattern argument, otherwise
4685  // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4686  //
4687  // template<typename T>
4688  // struct A {
4689  // static int FooImpl();
4690  //
4691  // template<typename Tp>
4692  // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4693  // // template argument list [[T], [Tp]], should be [[Tp]].
4694  // friend A<Tp> Foo(int a);
4695  // };
4696  //
4697  // template<typename T>
4698  // A<T> Foo(int a = A<T>::FooImpl());
4699  MultiLevelTemplateArgumentList MutiLevelArgList
4700  = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4701 
4702  InstantiatingTemplate Inst(*this, CallLoc, Param,
4703  MutiLevelArgList.getInnermost());
4704  if (Inst.isInvalid())
4705  return true;
4706  if (Inst.isAlreadyInstantiating()) {
4707  Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4708  Param->setInvalidDecl();
4709  return true;
4710  }
4711 
4712  ExprResult Result;
4713  {
4714  // C++ [dcl.fct.default]p5:
4715  // The names in the [default argument] expression are bound, and
4716  // the semantic constraints are checked, at the point where the
4717  // default argument expression appears.
4718  ContextRAII SavedContext(*this, FD);
4719  LocalInstantiationScope Local(*this);
4720  Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4721  /*DirectInit*/false);
4722  }
4723  if (Result.isInvalid())
4724  return true;
4725 
4726  // Check the expression as an initializer for the parameter.
4727  InitializedEntity Entity
4728  = InitializedEntity::InitializeParameter(Context, Param);
4730  Param->getLocation(),
4731  /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4732  Expr *ResultE = Result.getAs<Expr>();
4733 
4734  InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4735  Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4736  if (Result.isInvalid())
4737  return true;
4738 
4739  Result =
4740  ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4741  /*DiscardedValue*/ false);
4742  if (Result.isInvalid())
4743  return true;
4744 
4745  // Remember the instantiated default argument.
4746  Param->setDefaultArg(Result.getAs<Expr>());
4747  if (ASTMutationListener *L = getASTMutationListener()) {
4748  L->DefaultArgumentInstantiated(Param);
4749  }
4750  }
4751 
4752  // If the default argument expression is not set yet, we are building it now.
4753  if (!Param->hasInit()) {
4754  Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4755  Param->setInvalidDecl();
4756  return true;
4757  }
4758 
4759  // If the default expression creates temporaries, we need to
4760  // push them to the current stack of expression temporaries so they'll
4761  // be properly destroyed.
4762  // FIXME: We should really be rebuilding the default argument with new
4763  // bound temporaries; see the comment in PR5810.
4764  // We don't need to do that with block decls, though, because
4765  // blocks in default argument expression can never capture anything.
4766  if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4767  // Set the "needs cleanups" bit regardless of whether there are
4768  // any explicit objects.
4769  Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4770 
4771  // Append all the objects to the cleanup list. Right now, this
4772  // should always be a no-op, because blocks in default argument
4773  // expressions should never be able to capture anything.
4774  assert(!Init->getNumObjects() &&
4775  "default argument expression has capturing blocks?");
4776  }
4777 
4778  // We already type-checked the argument, so we know it works.
4779  // Just mark all of the declarations in this potentially-evaluated expression
4780  // as being "referenced".
4781  MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4782  /*SkipLocalVariables=*/true);
4783  return false;
4784 }
4785 
4787  FunctionDecl *FD, ParmVarDecl *Param) {
4788  if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4789  return ExprError();
4790  return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4791 }
4792 
4795  Expr *Fn) {
4796  if (Proto && Proto->isVariadic()) {
4797  if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4798  return VariadicConstructor;
4799  else if (Fn && Fn->getType()->isBlockPointerType())
4800  return VariadicBlock;
4801  else if (FDecl) {
4802  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4803  if (Method->isInstance())
4804  return VariadicMethod;
4805  } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4806  return VariadicMethod;
4807  return VariadicFunction;
4808  }
4809  return VariadicDoesNotApply;
4810 }
4811 
4812 namespace {
4813 class FunctionCallCCC : public FunctionCallFilterCCC {
4814 public:
4815  FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4816  unsigned NumArgs, MemberExpr *ME)
4817  : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4818  FunctionName(FuncName) {}
4819 
4820  bool ValidateCandidate(const TypoCorrection &candidate) override {
4821  if (!candidate.getCorrectionSpecifier() ||
4822  candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4823  return false;
4824  }
4825 
4826  return FunctionCallFilterCCC::ValidateCandidate(candidate);
4827  }
4828 
4829 private:
4830  const IdentifierInfo *const FunctionName;
4831 };
4832 }
4833 
4835  FunctionDecl *FDecl,
4836  ArrayRef<Expr *> Args) {
4837  MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4838  DeclarationName FuncName = FDecl->getDeclName();
4839  SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4840 
4841  if (TypoCorrection Corrected = S.CorrectTypo(
4842  DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4843  S.getScopeForContext(S.CurContext), nullptr,
4844  llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4845  Args.size(), ME),
4847  if (NamedDecl *ND = Corrected.getFoundDecl()) {
4848  if (Corrected.isOverloaded()) {
4851  for (NamedDecl *CD : Corrected) {
4852  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4853  S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4854  OCS);
4855  }
4856  switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4857  case OR_Success:
4858  ND = Best->FoundDecl;
4859  Corrected.setCorrectionDecl(ND);
4860  break;
4861  default:
4862  break;
4863  }
4864  }
4865  ND = ND->getUnderlyingDecl();
4866  if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4867  return Corrected;
4868  }
4869  }
4870  return TypoCorrection();
4871 }
4872 
4873 /// ConvertArgumentsForCall - Converts the arguments specified in
4874 /// Args/NumArgs to the parameter types of the function FDecl with
4875 /// function prototype Proto. Call is the call expression itself, and
4876 /// Fn is the function expression. For a C++ member function, this
4877 /// routine does not attempt to convert the object argument. Returns
4878 /// true if the call is ill-formed.
4879 bool
4881  FunctionDecl *FDecl,
4882  const FunctionProtoType *Proto,
4883  ArrayRef<Expr *> Args,
4884  SourceLocation RParenLoc,
4885  bool IsExecConfig) {
4886  // Bail out early if calling a builtin with custom typechecking.
4887  if (FDecl)
4888  if (unsigned ID = FDecl->getBuiltinID())
4889  if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4890  return false;
4891 
4892  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4893  // assignment, to the types of the corresponding parameter, ...
4894  unsigned NumParams = Proto->getNumParams();
4895  bool Invalid = false;
4896  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4897  unsigned FnKind = Fn->getType()->isBlockPointerType()
4898  ? 1 /* block */
4899  : (IsExecConfig ? 3 /* kernel function (exec config) */
4900  : 0 /* function */);
4901 
4902  // If too few arguments are available (and we don't have default
4903  // arguments for the remaining parameters), don't make the call.
4904  if (Args.size() < NumParams) {
4905  if (Args.size() < MinArgs) {
4906  TypoCorrection TC;
4907  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4908  unsigned diag_id =
4909  MinArgs == NumParams && !Proto->isVariadic()
4910  ? diag::err_typecheck_call_too_few_args_suggest
4911  : diag::err_typecheck_call_too_few_args_at_least_suggest;
4912  diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4913  << static_cast<unsigned>(Args.size())
4914  << TC.getCorrectionRange());
4915  } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4916  Diag(RParenLoc,
4917  MinArgs == NumParams && !Proto->isVariadic()
4918  ? diag::err_typecheck_call_too_few_args_one
4919  : diag::err_typecheck_call_too_few_args_at_least_one)
4920  << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4921  else
4922  Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4923  ? diag::err_typecheck_call_too_few_args
4924  : diag::err_typecheck_call_too_few_args_at_least)
4925  << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4926  << Fn->getSourceRange();
4927 
4928  // Emit the location of the prototype.
4929  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4930  Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
4931 
4932  return true;
4933  }
4934  // We reserve space for the default arguments when we create
4935  // the call expression, before calling ConvertArgumentsForCall.
4936  assert((Call->getNumArgs() == NumParams) &&
4937  "We should have reserved space for the default arguments before!");
4938  }
4939 
4940  // If too many are passed and not variadic, error on the extras and drop
4941  // them.
4942  if (Args.size() > NumParams) {
4943  if (!Proto->isVariadic()) {
4944  TypoCorrection TC;
4945  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4946  unsigned diag_id =
4947  MinArgs == NumParams && !Proto->isVariadic()
4948  ? diag::err_typecheck_call_too_many_args_suggest
4949  : diag::err_typecheck_call_too_many_args_at_most_suggest;
4950  diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4951  << static_cast<unsigned>(Args.size())
4952  << TC.getCorrectionRange());
4953  } else if (NumParams == 1 && FDecl &&
4954  FDecl->getParamDecl(0)->getDeclName())
4955  Diag(Args[NumParams]->getBeginLoc(),
4956  MinArgs == NumParams
4957  ? diag::err_typecheck_call_too_many_args_one
4958  : diag::err_typecheck_call_too_many_args_at_most_one)
4959  << FnKind << FDecl->getParamDecl(0)
4960  << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4961  << SourceRange(Args[NumParams]->getBeginLoc(),
4962  Args.back()->getEndLoc());
4963  else
4964  Diag(Args[NumParams]->getBeginLoc(),
4965  MinArgs == NumParams
4966  ? diag::err_typecheck_call_too_many_args
4967  : diag::err_typecheck_call_too_many_args_at_most)
4968  << FnKind << NumParams << static_cast<unsigned>(Args.size())
4969  << Fn->getSourceRange()
4970  << SourceRange(Args[NumParams]->getBeginLoc(),
4971  Args.back()->getEndLoc());
4972 
4973  // Emit the location of the prototype.
4974  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4975  Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
4976 
4977  // This deletes the extra arguments.
4978  Call->shrinkNumArgs(NumParams);
4979  return true;
4980  }
4981  }
4982  SmallVector<Expr *, 8> AllArgs;
4983  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4984 
4985  Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
4986  AllArgs, CallType);
4987  if (Invalid)
4988  return true;
4989  unsigned TotalNumArgs = AllArgs.size();
4990  for (unsigned i = 0; i < TotalNumArgs; ++i)
4991  Call->setArg(i, AllArgs[i]);
4992 
4993  return false;
4994 }
4995 
4997  const FunctionProtoType *Proto,
4998  unsigned FirstParam, ArrayRef<Expr *> Args,
4999  SmallVectorImpl<Expr *> &AllArgs,
5000  VariadicCallType CallType, bool AllowExplicit,
5001  bool IsListInitialization) {
5002  unsigned NumParams = Proto->getNumParams();
5003  bool Invalid = false;
5004  size_t ArgIx = 0;
5005  // Continue to check argument types (even if we have too few/many args).
5006  for (unsigned i = FirstParam; i < NumParams; i++) {
5007  QualType ProtoArgType = Proto->getParamType(i);
5008 
5009  Expr *Arg;
5010  ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5011  if (ArgIx < Args.size()) {
5012  Arg = Args[ArgIx++];
5013 
5014  if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5015  diag::err_call_incomplete_argument, Arg))
5016  return true;
5017 
5018  // Strip the unbridged-cast placeholder expression off, if applicable.
5019  bool CFAudited = false;
5020  if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5021  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5022  (!Param || !Param->hasAttr<CFConsumedAttr>()))
5023  Arg = stripARCUnbridgedCast(Arg);
5024  else if (getLangOpts().ObjCAutoRefCount &&
5025  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5026  (!Param || !Param->hasAttr<CFConsumedAttr>()))
5027  CFAudited = true;
5028 
5029  if (Proto->getExtParameterInfo(i).isNoEscape())
5030  if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5031  BE->getBlockDecl()->setDoesNotEscape();
5032 
5033  InitializedEntity Entity =
5034  Param ? InitializedEntity::InitializeParameter(Context, Param,
5035  ProtoArgType)
5037  Context, ProtoArgType, Proto->isParamConsumed(i));
5038 
5039  // Remember that parameter belongs to a CF audited API.
5040  if (CFAudited)
5041  Entity.setParameterCFAudited();
5042 
5043  ExprResult ArgE = PerformCopyInitialization(
5044  Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5045  if (ArgE.isInvalid())
5046  return true;
5047 
5048  Arg = ArgE.getAs<Expr>();
5049  } else {
5050  assert(Param && "can't use default arguments without a known callee");
5051 
5052  ExprResult ArgExpr =
5053  BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5054  if (ArgExpr.isInvalid())
5055  return true;
5056 
5057  Arg = ArgExpr.getAs<Expr>();
5058  }
5059 
5060  // Check for array bounds violations for each argument to the call. This
5061  // check only triggers warnings when the argument isn't a more complex Expr
5062  // with its own checking, such as a BinaryOperator.
5063  CheckArrayAccess(Arg);
5064 
5065  // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5066  CheckStaticArrayArgument(CallLoc, Param, Arg);
5067 
5068  AllArgs.push_back(Arg);
5069  }
5070 
5071  // If this is a variadic call, handle args passed through "...".
5072  if (CallType != VariadicDoesNotApply) {
5073  // Assume that extern "C" functions with variadic arguments that
5074  // return __unknown_anytype aren't *really* variadic.
5075  if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5076  FDecl->isExternC()) {
5077  for (Expr *A : Args.slice(ArgIx)) {
5078  QualType paramType; // ignored
5079  ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5080  Invalid |= arg.isInvalid();
5081  AllArgs.push_back(arg.get());
5082  }
5083 
5084  // Otherwise do argument promotion, (C99 6.5.2.2p7).
5085  } else {
5086  for (Expr *A : Args.slice(ArgIx)) {
5087  ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5088  Invalid |= Arg.isInvalid();
5089  AllArgs.push_back(Arg.get());
5090  }
5091  }
5092 
5093  // Check for array bounds violations.
5094  for (Expr *A : Args.slice(ArgIx))
5095  CheckArrayAccess(A);
5096  }
5097  return Invalid;
5098 }
5099 
5101  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5102  if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5103  TL = DTL.getOriginalLoc();
5104  if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5105  S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5106  << ATL.getLocalSourceRange();
5107 }
5108 
5109 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5110 /// array parameter, check that it is non-null, and that if it is formed by
5111 /// array-to-pointer decay, the underlying array is sufficiently large.
5112 ///
5113 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5114 /// array type derivation, then for each call to the function, the value of the
5115 /// corresponding actual argument shall provide access to the first element of
5116 /// an array with at least as many elements as specified by the size expression.
5117 void
5119  ParmVarDecl *Param,
5120  const Expr *ArgExpr) {
5121  // Static array parameters are not supported in C++.
5122  if (!Param || getLangOpts().CPlusPlus)
5123  return;
5124 
5125  QualType OrigTy = Param->getOriginalType();
5126 
5127  const ArrayType *AT = Context.getAsArrayType(OrigTy);
5128  if (!AT || AT->getSizeModifier() != ArrayType::Static)
5129  return;
5130 
5131  if (ArgExpr->isNullPointerConstant(Context,
5133  Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5134  DiagnoseCalleeStaticArrayParam(*this, Param);
5135  return;
5136  }
5137 
5138  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5139  if (!CAT)
5140  return;
5141 
5142  const ConstantArrayType *ArgCAT =
5143  Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5144  if (!ArgCAT)
5145  return;
5146 
5147  if (ArgCAT->getSize().ult(CAT->getSize())) {
5148  Diag(CallLoc, diag::warn_static_array_too_small)
5149  << ArgExpr->getSourceRange()
5150  << (unsigned) ArgCAT->getSize().getZExtValue()
5151  << (unsigned) CAT->getSize().getZExtValue();
5152  DiagnoseCalleeStaticArrayParam(*this, Param);
5153  }
5154 }
5155 
5156 /// Given a function expression of unknown-any type, try to rebuild it
5157 /// to have a function type.
5159 
5160 /// Is the given type a placeholder that we need to lower out
5161 /// immediately during argument processing?
5163  // Placeholders are never sugared.
5164  const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5165  if (!placeholder) return false;
5166 
5167  switch (placeholder->getKind()) {
5168  // Ignore all the non-placeholder types.
5169 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5170  case BuiltinType::Id:
5171 #include "clang/Basic/OpenCLImageTypes.def"
5172 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5173  case BuiltinType::Id:
5174 #include "clang/Basic/OpenCLExtensionTypes.def"
5175 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5176 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5177 #include "clang/AST/BuiltinTypes.def"
5178  return false;
5179 
5180  // We cannot lower out overload sets; they might validly be resolved
5181  // by the call machinery.
5182  case BuiltinType::Overload:
5183  return false;
5184 
5185  // Unbridged casts in ARC can be handled in some call positions and
5186  // should be left in place.
5187  case BuiltinType::ARCUnbridgedCast:
5188  return false;
5189 
5190  // Pseudo-objects should be converted as soon as possible.
5191  case BuiltinType::PseudoObject:
5192  return true;
5193 
5194  // The debugger mode could theoretically but currently does not try
5195  // to resolve unknown-typed arguments based on known parameter types.
5196  case BuiltinType::UnknownAny:
5197  return true;
5198 
5199  // These are always invalid as call arguments and should be reported.
5200  case BuiltinType::BoundMember:
5201  case BuiltinType::BuiltinFn:
5202  case BuiltinType::OMPArraySection:
5203  return true;
5204 
5205  }
5206  llvm_unreachable("bad builtin type kind");
5207 }
5208 
5209 /// Check an argument list for placeholders that we won't try to
5210 /// handle later.
5212  // Apply this processing to all the arguments at once instead of
5213  // dying at the first failure.
5214  bool hasInvalid = false;
5215  for (size_t i = 0, e = args.size(); i != e; i++) {
5216  if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5217  ExprResult result = S.CheckPlaceholderExpr(args[i]);
5218  if (result.isInvalid()) hasInvalid = true;
5219  else args[i] = result.get();
5220  } else if (hasInvalid) {
5221  (void)S.CorrectDelayedTyposInExpr(args[i]);
5222  }
5223  }
5224  return hasInvalid;
5225 }
5226 
5227 /// If a builtin function has a pointer argument with no explicit address
5228 /// space, then it should be able to accept a pointer to any address
5229 /// space as input. In order to do this, we need to replace the
5230 /// standard builtin declaration with one that uses the same address space
5231 /// as the call.
5232 ///
5233 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5234 /// it does not contain any pointer arguments without
5235 /// an address space qualifer. Otherwise the rewritten
5236 /// FunctionDecl is returned.
5237 /// TODO: Handle pointer return types.
5239  const FunctionDecl *FDecl,
5240  MultiExprArg ArgExprs) {
5241 
5242  QualType DeclType = FDecl->getType();
5243  const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5244 
5245  if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5246  !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5247  return nullptr;
5248 
5249  bool NeedsNewDecl = false;
5250  unsigned i = 0;
5251  SmallVector<QualType, 8> OverloadParams;
5252 
5253  for (QualType ParamType : FT->param_types()) {
5254 
5255  // Convert array arguments to pointer to simplify type lookup.
5256  ExprResult ArgRes =
5257  Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5258  if (ArgRes.isInvalid())
5259  return nullptr;
5260  Expr *Arg = ArgRes.get();
5261  QualType ArgType = Arg->getType();
5262  if (!ParamType->isPointerType() ||
5263  ParamType.getQualifiers().hasAddressSpace() ||
5264  !ArgType->isPointerType() ||
5265  !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5266  OverloadParams.push_back(ParamType);
5267  continue;
5268  }
5269 
5270  QualType PointeeType = ParamType->getPointeeType();
5271  if (PointeeType.getQualifiers().hasAddressSpace())
5272  continue;
5273 
5274  NeedsNewDecl = true;
5275  LangAS AS = ArgType->getPointeeType().getAddressSpace();
5276 
5277  PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5278  OverloadParams.push_back(Context.getPointerType(PointeeType));
5279  }
5280 
5281  if (!NeedsNewDecl)
5282  return nullptr;
5283 
5285  QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5286  OverloadParams, EPI);
5288  FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5289  FDecl->getLocation(),
5290  FDecl->getLocation(),
5291  FDecl->getIdentifier(),
5292  OverloadTy,
5293  /*TInfo=*/nullptr,
5294  SC_Extern, false,
5295  /*hasPrototype=*/true);
5297  FT = cast<FunctionProtoType>(OverloadTy);
5298  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5299  QualType ParamType = FT->getParamType(i);
5300  ParmVarDecl *Parm =
5301  ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5302  SourceLocation(), nullptr, ParamType,
5303  /*TInfo=*/nullptr, SC_None, nullptr);
5304  Parm->setScopeInfo(0, i);
5305  Params.push_back(Parm);
5306  }
5307  OverloadDecl->setParams(Params);
5308  return OverloadDecl;
5309 }
5310 
5311 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5312  FunctionDecl *Callee,
5313  MultiExprArg ArgExprs) {
5314  // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5315  // similar attributes) really don't like it when functions are called with an
5316  // invalid number of args.
5317  if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5318  /*PartialOverloading=*/false) &&
5319  !Callee->isVariadic())
5320  return;
5321  if (Callee->getMinRequiredArguments() > ArgExprs.size())
5322  return;
5323 
5324  if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5325  S.Diag(Fn->getBeginLoc(),
5326  isa<CXXMethodDecl>(Callee)
5327  ? diag::err_ovl_no_viable_member_function_in_call
5328  : diag::err_ovl_no_viable_function_in_call)
5329  << Callee << Callee->getSourceRange();
5330  S.Diag(Callee->getLocation(),
5331  diag::note_ovl_candidate_disabled_by_function_cond_attr)
5332  << Attr->getCond()->getSourceRange() << Attr->getMessage();
5333  return;
5334  }
5335 }
5336 
5338  const UnresolvedMemberExpr *const UME, Sema &S) {
5339 
5340  const auto GetFunctionLevelDCIfCXXClass =
5341  [](Sema &S) -> const CXXRecordDecl * {
5342  const DeclContext *const DC = S.getFunctionLevelDeclContext();
5343  if (!DC || !DC->getParent())
5344  return nullptr;
5345 
5346  // If the call to some member function was made from within a member
5347  // function body 'M' return return 'M's parent.
5348  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5349  return MD->getParent()->getCanonicalDecl();
5350  // else the call was made from within a default member initializer of a
5351  // class, so return the class.
5352  if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5353  return RD->getCanonicalDecl();
5354  return nullptr;
5355  };
5356  // If our DeclContext is neither a member function nor a class (in the
5357  // case of a lambda in a default member initializer), we can't have an
5358  // enclosing 'this'.
5359 
5360  const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5361  if (!CurParentClass)
5362  return false;
5363 
5364  // The naming class for implicit member functions call is the class in which
5365  // name lookup starts.
5366  const CXXRecordDecl *const NamingClass =
5367  UME->getNamingClass()->getCanonicalDecl();
5368  assert(NamingClass && "Must have naming class even for implicit access");
5369 
5370  // If the unresolved member functions were found in a 'naming class' that is
5371  // related (either the same or derived from) to the class that contains the
5372  // member function that itself contained the implicit member access.
5373 
5374  return CurParentClass == NamingClass ||
5375  CurParentClass->isDerivedFrom(NamingClass);
5376 }
5377 
5378 static void
5380  Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5381 
5382  if (!UME)
5383  return;
5384 
5385  LambdaScopeInfo *const CurLSI = S.getCurLambda();
5386  // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5387  // already been captured, or if this is an implicit member function call (if
5388  // it isn't, an attempt to capture 'this' should already have been made).
5389  if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5390  !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5391  return;
5392 
5393  // Check if the naming class in which the unresolved members were found is
5394  // related (same as or is a base of) to the enclosing class.
5395 
5397  return;
5398 
5399 
5400  DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5401  // If the enclosing function is not dependent, then this lambda is
5402  // capture ready, so if we can capture this, do so.
5403  if (!EnclosingFunctionCtx->isDependentContext()) {
5404  // If the current lambda and all enclosing lambdas can capture 'this' -
5405  // then go ahead and capture 'this' (since our unresolved overload set
5406  // contains at least one non-static member function).
5407  if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5408  S.CheckCXXThisCapture(CallLoc);
5409  } else if (S.CurContext->isDependentContext()) {
5410  // ... since this is an implicit member reference, that might potentially
5411  // involve a 'this' capture, mark 'this' for potential capture in
5412  // enclosing lambdas.
5413  if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5414  CurLSI->addPotentialThisCapture(CallLoc);
5415  }
5416 }
5417 
5418 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5419 /// This provides the location of the left/right parens and a list of comma
5420 /// locations.
5422  MultiExprArg ArgExprs, SourceLocation RParenLoc,
5423  Expr *ExecConfig, bool IsExecConfig) {
5424  // Since this might be a postfix expression, get rid of ParenListExprs.
5425  ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5426  if (Result.isInvalid()) return ExprError();
5427  Fn = Result.get();
5428 
5429  if (checkArgsForPlaceholders(*this, ArgExprs))
5430  return ExprError();
5431 
5432  if (getLangOpts().CPlusPlus) {
5433  // If this is a pseudo-destructor expression, build the call immediately.
5434  if (isa<CXXPseudoDestructorExpr>(Fn)) {
5435  if (!ArgExprs.empty()) {
5436  // Pseudo-destructor calls should not have any arguments.
5437  Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5439  SourceRange(ArgExprs.front()->getBeginLoc(),
5440  ArgExprs.back()->getEndLoc()));
5441  }
5442 
5443  return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5444  VK_RValue, RParenLoc);
5445  }
5446  if (Fn->getType() == Context.PseudoObjectTy) {
5447  ExprResult result = CheckPlaceholderExpr(Fn);
5448  if (result.isInvalid()) return ExprError();
5449  Fn = result.get();
5450  }
5451 
5452  // Determine whether this is a dependent call inside a C++ template,
5453  // in which case we won't do any semantic analysis now.
5454  if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5455  if (ExecConfig) {
5457  Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5458  Context.DependentTy, VK_RValue, RParenLoc);
5459  } else {
5460 
5462  *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5463  Fn->getBeginLoc());
5464 
5465  return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5466  VK_RValue, RParenLoc);
5467  }
5468  }
5469 
5470  // Determine whether this is a call to an object (C++ [over.call.object]).
5471  if (Fn->getType()->isRecordType())
5472  return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5473  RParenLoc);
5474 
5475  if (Fn->getType() == Context.UnknownAnyTy) {
5476  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5477  if (result.isInvalid()) return ExprError();
5478  Fn = result.get();
5479  }
5480 
5481  if (Fn->getType() == Context.BoundMemberTy) {
5482  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5483  RParenLoc);
5484  }
5485  }
5486 
5487  // Check for overloaded calls. This can happen even in C due to extensions.
5488  if (Fn->getType() == Context.OverloadTy) {
5490 
5491  // We aren't supposed to apply this logic if there's an '&' involved.
5492  if (!find.HasFormOfMemberPointer) {
5493  if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5494  return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5495  VK_RValue, RParenLoc);
5496  OverloadExpr *ovl = find.Expression;
5497  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5498  return BuildOverloadedCallExpr(
5499  Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5500  /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5501  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5502  RParenLoc);
5503  }
5504  }
5505 
5506  // If we're directly calling a function, get the appropriate declaration.
5507  if (Fn->getType() == Context.UnknownAnyTy) {
5508  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5509  if (result.isInvalid()) return ExprError();
5510  Fn = result.get();
5511  }
5512 
5513  Expr *NakedFn = Fn->IgnoreParens();
5514 
5515  bool CallingNDeclIndirectly = false;
5516  NamedDecl *NDecl = nullptr;
5517  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5518  if (UnOp->getOpcode() == UO_AddrOf) {
5519  CallingNDeclIndirectly = true;
5520  NakedFn = UnOp->getSubExpr()->IgnoreParens();
5521  }
5522  }
5523 
5524  if (isa<DeclRefExpr>(NakedFn)) {
5525  NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5526 
5527  FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5528  if (FDecl && FDecl->getBuiltinID()) {
5529  // Rewrite the function decl for this builtin by replacing parameters
5530  // with no explicit address space with the address space of the arguments
5531  // in ArgExprs.
5532  if ((FDecl =
5533  rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5534  NDecl = FDecl;
5535  Fn = DeclRefExpr::Create(
5536  Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5537  SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5538  }
5539  }
5540  } else if (isa<MemberExpr>(NakedFn))
5541  NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5542 
5543  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5544  if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5545  FD, /*Complain=*/true, Fn->getBeginLoc()))
5546  return ExprError();
5547 
5548  if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5549  return ExprError();
5550 
5551  checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5552  }
5553 
5554  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5555  ExecConfig, IsExecConfig);
5556 }
5557 
5558 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5559 ///
5560 /// __builtin_astype( value, dst type )
5561 ///
5563  SourceLocation BuiltinLoc,
5564  SourceLocation RParenLoc) {
5565  ExprValueKind VK = VK_RValue;
5567  QualType DstTy = GetTypeFromParser(ParsedDestTy);
5568  QualType SrcTy = E->getType();
5569  if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5570  return ExprError(Diag(BuiltinLoc,
5571  diag::err_invalid_astype_of_different_size)
5572  << DstTy
5573  << SrcTy
5574  << E->getSourceRange());
5575  return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5576 }
5577 
5578 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5579 /// provided arguments.
5580 ///
5581 /// __builtin_convertvector( value, dst type )
5582 ///
5584  SourceLocation BuiltinLoc,
5585  SourceLocation RParenLoc) {
5586  TypeSourceInfo *TInfo;
5587  GetTypeFromParser(ParsedDestTy, &TInfo);
5588  return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5589 }
5590 
5591 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5592 /// i.e. an expression not of \p OverloadTy. The expression should
5593 /// unary-convert to an expression of function-pointer or
5594 /// block-pointer type.
5595 ///
5596 /// \param NDecl the declaration being called, if available
5598  SourceLocation LParenLoc,
5599  ArrayRef<Expr *> Args,
5600  SourceLocation RParenLoc, Expr *Config,
5601  bool IsExecConfig, ADLCallKind UsesADL) {
5602  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5603  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5604 
5605  // Functions with 'interrupt' attribute cannot be called directly.
5606  if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5607  Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5608  return ExprError();
5609  }
5610 
5611  // Interrupt handlers don't save off the VFP regs automatically on ARM,
5612  // so there's some risk when calling out to non-interrupt handler functions
5613  // that the callee might not preserve them. This is easy to diagnose here,
5614  // but can be very challenging to debug.
5615  if (auto *Caller = getCurFunctionDecl())
5616  if (Caller->hasAttr<ARMInterruptAttr>()) {
5617  bool VFP = Context.getTargetInfo().hasFeature("vfp");
5618  if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5619  Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5620  }
5621 
5622  // Promote the function operand.
5623  // We special-case function promotion here because we only allow promoting
5624  // builtin functions to function pointers in the callee of a call.
5625  ExprResult Result;
5626  QualType ResultTy;
5627  if (BuiltinID &&
5628  Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5629  // Extract the return type from the (builtin) function pointer type.
5630  // FIXME Several builtins still have setType in
5631  // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5632  // Builtins.def to ensure they are correct before removing setType calls.
5633  QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5634  Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5635  ResultTy = FDecl->getCallResultType();
5636  } else {
5637  Result = CallExprUnaryConversions(Fn);
5638  ResultTy = Context.BoolTy;
5639  }
5640  if (Result.isInvalid())
5641  return ExprError();
5642  Fn = Result.get();
5643 
5644  // Check for a valid function type, but only if it is not a builtin which
5645  // requires custom type checking. These will be handled by
5646  // CheckBuiltinFunctionCall below just after creation of the call expression.
5647  const FunctionType *FuncT = nullptr;
5648  if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5649  retry:
5650  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5651  // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5652  // have type pointer to function".
5653  FuncT = PT->getPointeeType()->getAs<FunctionType>();
5654  if (!FuncT)
5655  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5656  << Fn->getType() << Fn->getSourceRange());
5657  } else if (const BlockPointerType *BPT =
5658  Fn->getType()->getAs<BlockPointerType>()) {
5659  FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5660  } else {
5661  // Handle calls to expressions of unknown-any type.
5662  if (Fn->getType() == Context.UnknownAnyTy) {
5663  ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5664  if (rewrite.isInvalid()) return ExprError();
5665  Fn = rewrite.get();
5666  goto retry;
5667  }
5668 
5669  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5670  << Fn->getType() << Fn->getSourceRange());
5671  }
5672  }
5673 
5674  // Get the number of parameters in the function prototype, if any.
5675  // We will allocate space for max(Args.size(), NumParams) arguments
5676  // in the call expression.
5677  const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5678  unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5679 
5680  CallExpr *TheCall;
5681  if (Config) {
5682  assert(UsesADL == ADLCallKind::NotADL &&
5683  "CUDAKernelCallExpr should not use ADL");
5684  TheCall =
5685  CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5686  ResultTy, VK_RValue, RParenLoc, NumParams);
5687  } else {
5688  TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5689  RParenLoc, NumParams, UsesADL);
5690  }
5691 
5692  if (!getLangOpts().CPlusPlus) {
5693  // C cannot always handle TypoExpr nodes in builtin calls and direct
5694  // function calls as their argument checking don't necessarily handle
5695  // dependent types properly, so make sure any TypoExprs have been
5696  // dealt with.
5697  ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5698  if (!Result.isUsable()) return ExprError();
5699  TheCall = dyn_cast<CallExpr>(Result.get());
5700  if (!TheCall) return Result;
5701  // TheCall at this point has max(Args.size(), NumParams) arguments,
5702  // with extra arguments nulled. We don't want to introduce nulled
5703  // arguments in Args and so we only take the first Args.size() arguments.
5704  Args = llvm::makeArrayRef(TheCall->getArgs(), Args.size());
5705  }
5706 
5707  // Bail out early if calling a builtin with custom type checking.
5708  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5709  return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5710 
5711  if (getLangOpts().CUDA) {
5712  if (Config) {
5713  // CUDA: Kernel calls must be to global functions
5714  if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5715  return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5716  << FDecl << Fn->getSourceRange());
5717 
5718  // CUDA: Kernel function must have 'void' return type
5719  if (!FuncT->getReturnType()->isVoidType())
5720  return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5721  << Fn->getType() << Fn->getSourceRange());
5722  } else {
5723  // CUDA: Calls to global functions must be configured
5724  if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5725  return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5726  << FDecl << Fn->getSourceRange());
5727  }
5728  }
5729 
5730  // Check for a valid return type
5731  if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5732  FDecl))
5733  return ExprError();
5734 
5735  // We know the result type of the call, set it.
5736  TheCall->setType(FuncT->getCallResultType(Context));
5738 
5739  if (Proto) {
5740  if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5741  IsExecConfig))
5742  return ExprError();
5743  } else {
5744  assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5745 
5746  if (FDecl) {
5747  // Check if we have too few/too many template arguments, based
5748  // on our knowledge of the function definition.
5749  const FunctionDecl *Def = nullptr;
5750  if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5751  Proto = Def->getType()->getAs<FunctionProtoType>();
5752  if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5753  Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5754  << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5755  }
5756 
5757  // If the function we're calling isn't a function prototype, but we have
5758  // a function prototype from a prior declaratiom, use that prototype.
5759  if (!FDecl->hasPrototype())
5760  Proto = FDecl->getType()->getAs<FunctionProtoType>();
5761  }
5762 
5763  // Promote the arguments (C99 6.5.2.2p6).
5764  for (unsigned i = 0, e = Args.size(); i != e; i++) {
5765  Expr *Arg = Args[i];
5766 
5767  if (Proto && i < Proto->getNumParams()) {
5769  Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5770  ExprResult ArgE =
5771  PerformCopyInitialization(Entity, SourceLocation(), Arg);
5772  if (ArgE.isInvalid())
5773  return true;
5774 
5775  Arg = ArgE.getAs<Expr>();
5776 
5777  } else {
5778  ExprResult ArgE = DefaultArgumentPromotion(Arg);
5779 
5780  if (ArgE.isInvalid())
5781  return true;
5782 
5783  Arg = ArgE.getAs<Expr>();
5784  }
5785 
5786  if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5787  diag::err_call_incomplete_argument, Arg))
5788  return ExprError();
5789 
5790  TheCall->setArg(i, Arg);
5791  }
5792  }
5793 
5794  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5795  if (!Method->isStatic())
5796  return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5797  << Fn->getSourceRange());
5798 
5799  // Check for sentinels
5800  if (NDecl)
5801  DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5802 
5803  // Do special checking on direct calls to functions.
5804  if (FDecl) {
5805  if (CheckFunctionCall(FDecl, TheCall, Proto))
5806  return ExprError();
5807 
5808  if (BuiltinID)
5809  return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5810  } else if (NDecl) {
5811  if (CheckPointerCall(NDecl, TheCall, Proto))
5812  return ExprError();
5813  } else {
5814  if (CheckOtherCall(TheCall, Proto))
5815  return ExprError();
5816  }
5817 
5818  return MaybeBindToTemporary(TheCall);
5819 }
5820 
5821 ExprResult
5823  SourceLocation RParenLoc, Expr *InitExpr) {
5824  assert(Ty && "ActOnCompoundLiteral(): missing type");
5825  assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5826 
5827  TypeSourceInfo *TInfo;
5828  QualType literalType = GetTypeFromParser(Ty, &TInfo);
5829  if (!TInfo)
5830  TInfo = Context.getTrivialTypeSourceInfo(literalType);
5831 
5832  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5833 }
5834 
5835 ExprResult
5837  SourceLocation RParenLoc, Expr *LiteralExpr) {
5838  QualType literalType = TInfo->getType();
5839 
5840  if (literalType->isArrayType()) {
5841  if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5842  diag::err_illegal_decl_array_incomplete_type,
5843  SourceRange(LParenLoc,
5844  LiteralExpr->getSourceRange().getEnd())))
5845  return ExprError();
5846  if (literalType->isVariableArrayType())
5847  return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5848  << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5849  } else if (!literalType->isDependentType() &&
5850  RequireCompleteType(LParenLoc, literalType,
5851  diag::err_typecheck_decl_incomplete_type,
5852  SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5853  return ExprError();
5854 
5855  InitializedEntity Entity
5859  SourceRange(LParenLoc, RParenLoc),
5860  /*InitList=*/true);
5861  InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5862  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5863  &literalType);
5864  if (Result.isInvalid())
5865  return ExprError();
5866  LiteralExpr = Result.get();
5867 
5868  bool isFileScope = !CurContext->isFunctionOrMethod();
5869 
5870  // In C, compound literals are l-values for some reason.
5871  // For GCC compatibility, in C++, file-scope array compound literals with
5872  // constant initializers are also l-values, and compound literals are
5873  // otherwise prvalues.
5874  //
5875  // (GCC also treats C++ list-initialized file-scope array prvalues with
5876  // constant initializers as l-values, but that's non-conforming, so we don't
5877  // follow it there.)
5878  //
5879  // FIXME: It would be better to handle the lvalue cases as materializing and
5880  // lifetime-extending a temporary object, but our materialized temporaries
5881  // representation only supports lifetime extension from a variable, not "out
5882  // of thin air".
5883  // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5884  // is bound to the result of applying array-to-pointer decay to the compound
5885  // literal.
5886  // FIXME: GCC supports compound literals of reference type, which should
5887  // obviously have a value kind derived from the kind of reference involved.
5888  ExprValueKind VK =
5889  (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5890  ? VK_RValue
5891  : VK_LValue;
5892 
5893  if (isFileScope)
5894  if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
5895  for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
5896  Expr *Init = ILE->getInit(i);
5897  ILE->setInit(i, ConstantExpr::Create(Context, Init));
5898  }
5899 
5900  Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5901  VK, LiteralExpr, isFileScope);
5902  if (isFileScope) {
5903  if (!LiteralExpr->isTypeDependent() &&
5904  !LiteralExpr->isValueDependent() &&
5905  !literalType->isDependentType()) // C99 6.5.2.5p3
5906  if (CheckForConstantInitializer(LiteralExpr, literalType))
5907  return ExprError();
5908  } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
5909  literalType.getAddressSpace() != LangAS::Default) {
5910  // Embedded-C extensions to C99 6.5.2.5:
5911  // "If the compound literal occurs inside the body of a function, the
5912  // type name shall not be qualified by an address-space qualifier."
5913  Diag(LParenLoc, diag::err_compound_literal_with_address_space)
5914  << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
5915  return ExprError();
5916  }
5917 
5918  return MaybeBindToTemporary(E);
5919 }
5920 
5921 ExprResult
5923  SourceLocation RBraceLoc) {
5924  // Immediately handle non-overload placeholders. Overloads can be
5925  // resolved contextually, but everything else here can't.
5926  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5927  if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5928  ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5929 
5930  // Ignore failures; dropping the entire initializer list because
5931  // of one failure would be terrible for indexing/etc.
5932  if (result.isInvalid()) continue;
5933 
5934  InitArgList[I] = result.get();
5935  }
5936  }
5937 
5938  // Semantic analysis for initializers is done by ActOnDeclarator() and
5939  // CheckInitializer() - it requires knowledge of the object being initialized.
5940 
5941  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5942  RBraceLoc);
5943  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5944  return E;
5945 }
5946 
5947 /// Do an explicit extend of the given block pointer if we're in ARC.
5949  assert(E.get()->getType()->isBlockPointerType());
5950  assert(E.get()->isRValue());
5951 
5952  // Only do this in an r-value context.
5953  if (!getLangOpts().ObjCAutoRefCount) return;
5954 
5955  E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5956  CK_ARCExtendBlockObject, E.get(),
5957  /*base path*/ nullptr, VK_RValue);
5958  Cleanup.setExprNeedsCleanups(true);
5959 }
5960 
5961 /// Prepare a conversion of the given expression to an ObjC object
5962 /// pointer type.
5964  QualType type = E.get()->getType();
5965  if (type->isObjCObjectPointerType()) {
5966  return CK_BitCast;
5967  } else if (type->isBlockPointerType()) {
5968  maybeExtendBlockObject(E);
5969  return CK_BlockPointerToObjCPointerCast;
5970  } else {
5971  assert(type->isPointerType());
5972  return CK_CPointerToObjCPointerCast;
5973  }
5974 }
5975 
5976 /// Prepares for a scalar cast, performing all the necessary stages
5977 /// except the final cast and returning the kind required.
5979  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5980  // Also, callers should have filtered out the invalid cases with
5981  // pointers. Everything else should be possible.
5982 
5983  QualType SrcTy = Src.get()->getType();
5984  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5985  return CK_NoOp;
5986 
5987  switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5989  llvm_unreachable("member pointer type in C");
5990 
5991  case Type::STK_CPointer:
5994  switch (DestTy->getScalarTypeKind()) {
5995  case Type::STK_CPointer: {
5996  LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5997  LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5998  if (SrcAS != DestAS)
5999  return CK_AddressSpaceConversion;
6000  if (Context.hasCvrSimilarType(SrcTy, DestTy))
6001  return CK_NoOp;
6002  return CK_BitCast;
6003  }
6005  return (SrcKind == Type::STK_BlockPointer
6006  ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6008  if (SrcKind == Type::STK_ObjCObjectPointer)
6009  return CK_BitCast;
6010  if (SrcKind == Type::STK_CPointer)
6011  return CK_CPointerToObjCPointerCast;
6012  maybeExtendBlockObject(Src);
6013  return CK_BlockPointerToObjCPointerCast;
6014  case Type::STK_Bool:
6015  return CK_PointerToBoolean;
6016  case Type::STK_Integral:
6017  return CK_PointerToIntegral;
6018  case Type::STK_Floating:
6022  case Type::STK_FixedPoint:
6023  llvm_unreachable("illegal cast from pointer");
6024  }
6025  llvm_unreachable("Should have returned before this");
6026 
6027  case Type::STK_FixedPoint:
6028  switch (DestTy->getScalarTypeKind()) {
6029  case Type::STK_FixedPoint:
6030  return CK_FixedPointCast;
6031  case Type::STK_Bool:
6032  return CK_FixedPointToBoolean;
6033  case Type::STK_Integral:
6034  case Type::STK_Floating:
6037  Diag(Src.get()->getExprLoc(),
6038  diag::err_unimplemented_conversion_with_fixed_point_type)
6039  << DestTy;
6040  return CK_IntegralCast;
6041  case Type::STK_CPointer:
6045  llvm_unreachable("illegal cast to pointer type");
6046  }
6047  llvm_unreachable("Should have returned before this");
6048 
6049  case Type::STK_Bool: // casting from bool is like casting from an integer
6050  case Type::STK_Integral:
6051  switch (DestTy->getScalarTypeKind()) {
6052  case Type::STK_CPointer:
6055  if (Src.get()->isNullPointerConstant(Context,
6057  return CK_NullToPointer;
6058  return CK_IntegralToPointer;
6059  case Type::STK_Bool:
6060  return CK_IntegralToBoolean;
6061  case Type::STK_Integral:
6062  return CK_IntegralCast;
6063  case Type::STK_Floating:
6064  return CK_IntegralToFloating;
6066  Src = ImpCastExprToType(Src.get(),
6067  DestTy->castAs<ComplexType>()->getElementType(),
6068  CK_IntegralCast);
6069  return CK_IntegralRealToComplex;
6071  Src = ImpCastExprToType(Src.get(),
6072  DestTy->castAs<ComplexType>()->getElementType(),
6073  CK_IntegralToFloating);
6074  return CK_FloatingRealToComplex;
6076  llvm_unreachable("member pointer type in C");
6077  case Type::STK_FixedPoint:
6078  Diag(Src.get()->getExprLoc(),
6079  diag::err_unimplemented_conversion_with_fixed_point_type)
6080  << SrcTy;
6081  return CK_IntegralCast;
6082  }
6083  llvm_unreachable("Should have returned before this");
6084 
6085  case Type::STK_Floating:
6086  switch (DestTy->getScalarTypeKind()) {
6087  case Type::STK_Floating:
6088  return CK_FloatingCast;
6089  case Type::STK_Bool:
6090  return CK_FloatingToBoolean;
6091  case Type::STK_Integral:
6092  return CK_FloatingToIntegral;
6094  Src = ImpCastExprToType(Src.get(),
6095  DestTy->castAs<ComplexType>()->getElementType(),
6096  CK_FloatingCast);
6097  return CK_FloatingRealToComplex;
6099  Src = ImpCastExprToType(Src.get(),
6100  DestTy->castAs<ComplexType>()->getElementType(),
6101  CK_FloatingToIntegral);
6102  return CK_IntegralRealToComplex;
6103  case Type::STK_CPointer:
6106  llvm_unreachable("valid float->pointer cast?");
6108  llvm_unreachable("member pointer type in C");
6109  case Type::STK_FixedPoint:
6110  Diag(Src.get()->getExprLoc(),
6111  diag::err_unimplemented_conversion_with_fixed_point_type)
6112  << SrcTy;
6113  return CK_IntegralCast;
6114  }
6115  llvm_unreachable("Should have returned before this");
6116 
6118  switch (DestTy->getScalarTypeKind()) {
6120  return CK_FloatingComplexCast;
6122  return CK_FloatingComplexToIntegralComplex;
6123  case Type::STK_Floating: {
6124  QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6125  if (Context.hasSameType(ET, DestTy))
6126  return CK_FloatingComplexToReal;
6127  Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6128  return CK_FloatingCast;
6129  }
6130  case Type::STK_Bool:
6131  return CK_FloatingComplexToBoolean;
6132  case Type::STK_Integral:
6133  Src = ImpCastExprToType(Src.get(),
6134  SrcTy->castAs<ComplexType>()->getElementType(),
6135  CK_FloatingComplexToReal);
6136  return CK_FloatingToIntegral;
6137  case Type::STK_CPointer:
6140  llvm_unreachable("valid complex float->pointer cast?");
6142  llvm_unreachable("member pointer type in C");
6143  case Type::STK_FixedPoint:
6144  Diag(Src.get()->getExprLoc(),
6145  diag::err_unimplemented_conversion_with_fixed_point_type)
6146  << SrcTy;
6147  return CK_IntegralCast;
6148  }
6149  llvm_unreachable("Should have returned before this");
6150 
6152  switch (DestTy->getScalarTypeKind()) {
6154  return CK_IntegralComplexToFloatingComplex;
6156  return CK_IntegralComplexCast;
6157  case Type::STK_Integral: {
6158  QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6159  if (Context.hasSameType(ET, DestTy))
6160  return CK_IntegralComplexToReal;
6161  Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6162  return CK_IntegralCast;
6163  }
6164  case Type::STK_Bool:
6165  return CK_IntegralComplexToBoolean;
6166  case Type::STK_Floating:
6167  Src = ImpCastExprToType(Src.get(),
6168  SrcTy->castAs<ComplexType>()->getElementType(),
6169  CK_IntegralComplexToReal);
6170  return CK_IntegralToFloating;
6171  case Type::STK_CPointer:
6174  llvm_unreachable("valid complex int->pointer cast?");
6176  llvm_unreachable("member pointer type in C");
6177  case Type::STK_FixedPoint:
6178  Diag(Src.get()->getExprLoc(),
6179  diag::err_unimplemented_conversion_with_fixed_point_type)
6180  << SrcTy;
6181  return CK_IntegralCast;
6182  }
6183  llvm_unreachable("Should have returned before this");
6184  }
6185 
6186  llvm_unreachable("Unhandled scalar cast");
6187 }
6188 
6189 static bool breakDownVectorType(QualType type, uint64_t &len,
6190  QualType &eltType) {
6191  // Vectors are simple.
6192  if (const VectorType *vecType = type->getAs<VectorType>()) {
6193  len = vecType->getNumElements();
6194  eltType = vecType->getElementType();
6195  assert(eltType->isScalarType());
6196  return true;
6197  }
6198 
6199  // We allow lax conversion to and from non-vector types, but only if
6200  // they're real types (i.e. non-complex, non-pointer scalar types).
6201  if (!type->isRealType()) return false;
6202 
6203  len = 1;
6204  eltType = type;
6205  return true;
6206 }
6207 
6208 /// Are the two types lax-compatible vector types? That is, given
6209 /// that one of them is a vector, do they have equal storage sizes,
6210 /// where the storage size is the number of elements times the element
6211 /// size?
6212 ///
6213 /// This will also return false if either of the types is neither a
6214 /// vector nor a real type.
6216  assert(destTy->isVectorType() || srcTy->isVectorType());
6217 
6218  // Disallow lax conversions between scalars and ExtVectors (these
6219  // conversions are allowed for other vector types because common headers
6220  // depend on them). Most scalar OP ExtVector cases are handled by the
6221  // splat path anyway, which does what we want (convert, not bitcast).
6222  // What this rules out for ExtVectors is crazy things like char4*float.
6223  if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6224  if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6225 
6226  uint64_t srcLen, destLen;
6227  QualType srcEltTy, destEltTy;
6228  if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6229  if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6230 
6231  // ASTContext::getTypeSize will return the size rounded up to a
6232  // power of 2, so instead of using that, we need to use the raw
6233  // element size multiplied by the element count.
6234  uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6235  uint64_t destEltSize = Context.getTypeSize(destEltTy);
6236 
6237  return (srcLen * srcEltSize == destLen * destEltSize);
6238 }
6239 
6240 /// Is this a legal conversion between two types, one of which is
6241 /// known to be a vector type?
6243  assert(destTy->isVectorType() || srcTy->isVectorType());
6244 
6245  if (!Context.getLangOpts().LaxVectorConversions)
6246  return false;
6247  return areLaxCompatibleVectorTypes(srcTy, destTy);
6248 }
6249 
6251  CastKind &Kind) {
6252  assert(VectorTy->isVectorType() && "Not a vector type!");
6253 
6254  if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6255  if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6256  return Diag(R.getBegin(),
6257  Ty->isVectorType() ?
6258  diag::err_invalid_conversion_between_vectors :
6259  diag::err_invalid_conversion_between_vector_and_integer)
6260  << VectorTy << Ty << R;
6261  } else
6262  return Diag(R.getBegin(),
6263  diag::err_invalid_conversion_between_vector_and_scalar)
6264  << VectorTy << Ty << R;
6265 
6266  Kind = CK_BitCast;
6267  return false;
6268 }
6269 
6271  QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6272 
6273  if (DestElemTy == SplattedExpr->getType())
6274  return SplattedExpr;
6275 
6276  assert(DestElemTy->isFloatingType() ||
6277  DestElemTy->isIntegralOrEnumerationType());
6278 
6279  CastKind CK;
6280  if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6281  // OpenCL requires that we convert `true` boolean expressions to -1, but
6282  // only when splatting vectors.
6283  if (DestElemTy->isFloatingType()) {
6284  // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6285  // in two steps: boolean to signed integral, then to floating.
6286  ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6287  CK_BooleanToSignedIntegral);
6288  SplattedExpr = CastExprRes.get();
6289  CK = CK_IntegralToFloating;
6290  } else {
6291  CK = CK_BooleanToSignedIntegral;
6292  }
6293  } else {
6294  ExprResult CastExprRes = SplattedExpr;
6295  CK = PrepareScalarCast(CastExprRes, DestElemTy);
6296  if (CastExprRes.isInvalid())
6297  return ExprError();
6298  SplattedExpr = CastExprRes.get();
6299  }
6300  return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6301 }
6302 
6304  Expr *CastExpr, CastKind &Kind) {
6305  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6306 
6307  QualType SrcTy = CastExpr->getType();
6308 
6309  // If SrcTy is a VectorType, the total size must match to explicitly cast to
6310  // an ExtVectorType.
6311  // In OpenCL, casts between vectors of different types are not allowed.
6312  // (See OpenCL 6.2).
6313  if (SrcTy->isVectorType()) {
6314  if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6315  (getLangOpts().OpenCL &&
6316  !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6317  Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6318  << DestTy << SrcTy << R;
6319  return ExprError();
6320  }
6321  Kind = CK_BitCast;
6322  return CastExpr;
6323  }
6324 
6325  // All non-pointer scalars can be cast to ExtVector type. The appropriate
6326  // conversion will take place first from scalar to elt type, and then
6327  // splat from elt type to vector.
6328  if (SrcTy->isPointerType())
6329  return Diag(R.getBegin(),
6330  diag::err_invalid_conversion_between_vector_and_scalar)
6331  << DestTy << SrcTy << R;
6332 
6333  Kind = CK_VectorSplat;
6334  return prepareVectorSplat(DestTy, CastExpr);
6335 }
6336 
6337 ExprResult
6339  Declarator &D, ParsedType &Ty,
6340  SourceLocation RParenLoc, Expr *CastExpr) {
6341  assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6342  "ActOnCastExpr(): missing type or expr");
6343 
6344  TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6345  if (D.isInvalidType())
6346  return ExprError();
6347 
6348  if (getLangOpts().CPlusPlus) {
6349  // Check that there are no default arguments (C++ only).
6350  CheckExtraCXXDefaultArguments(D);
6351  } else {
6352  // Make sure any TypoExprs have been dealt with.
6353  ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6354  if (!Res.isUsable())
6355  return ExprError();
6356  CastExpr = Res.get();
6357  }
6358 
6359  checkUnusedDeclAttributes(D);
6360 
6361  QualType castType = castTInfo->getType();
6362  Ty = CreateParsedType(castType, castTInfo);
6363 
6364  bool isVectorLiteral = false;
6365 
6366  // Check for an altivec or OpenCL literal,
6367  // i.e. all the elements are integer constants.
6368  ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6369  ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6370  if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6371  && castType->isVectorType() && (PE || PLE)) {
6372  if (PLE && PLE->getNumExprs() == 0) {
6373  Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6374  return ExprError();
6375  }
6376  if (PE || PLE->getNumExprs() == 1) {
6377  Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6378  if (!E->getType()->isVectorType())
6379  isVectorLiteral = true;
6380  }
6381  else
6382  isVectorLiteral = true;
6383  }
6384 
6385  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6386  // then handle it as such.
6387  if (isVectorLiteral)
6388  return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6389 
6390  // If the Expr being casted is a ParenListExpr, handle it specially.
6391  // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6392  // sequence of BinOp comma operators.
6393  if (isa<ParenListExpr>(CastExpr)) {
6394  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6395  if (Result.isInvalid()) return ExprError();
6396  CastExpr = Result.get();
6397  }
6398 
6399  if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6400  !getSourceManager().isInSystemMacro(LParenLoc))
6401  Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6402 
6403  CheckTollFreeBridgeCast(castType, CastExpr);
6404 
6405  CheckObjCBridgeRelatedCast(castType, CastExpr);
6406 
6407  DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6408 
6409  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6410 }
6411 
6413  SourceLocation RParenLoc, Expr *E,
6414  TypeSourceInfo *TInfo) {
6415  assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6416  "Expected paren or paren list expression");
6417 
6418  Expr **exprs;
6419  unsigned numExprs;
6420  Expr *subExpr;
6421  SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6422  if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6423  LiteralLParenLoc = PE->getLParenLoc();
6424  LiteralRParenLoc = PE->getRParenLoc();
6425  exprs = PE->getExprs();
6426  numExprs = PE->getNumExprs();
6427  } else { // isa<ParenExpr> by assertion at function entrance
6428  LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6429  LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6430  subExpr = cast<ParenExpr>(E)->getSubExpr();
6431  exprs = &subExpr;
6432  numExprs = 1;
6433  }
6434 
6435  QualType Ty = TInfo->getType();
6436  assert(Ty->isVectorType() && "Expected vector type");
6437 
6438  SmallVector<Expr *, 8> initExprs;
6439  const VectorType *VTy = Ty->getAs<VectorType>();
6440  unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6441 
6442  // '(...)' form of vector initialization in AltiVec: the number of
6443  // initializers must be one or must match the size of the vector.
6444  // If a single value is specified in the initializer then it will be
6445  // replicated to all the components of the vector
6446  if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6447  // The number of initializers must be one or must match the size of the
6448  // vector. If a single value is specified in the initializer then it will
6449  // be replicated to all the components of the vector
6450  if (numExprs == 1) {
6451  QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6452  ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6453  if (Literal.isInvalid())
6454  return ExprError();
6455  Literal = ImpCastExprToType(Literal.get(), ElemTy,
6456  PrepareScalarCast(Literal, ElemTy));
6457  return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6458  }
6459  else if (numExprs < numElems) {
6460  Diag(E->getExprLoc(),
6461  diag::err_incorrect_number_of_vector_initializers);
6462  return ExprError();
6463  }
6464  else
6465  initExprs.append(exprs, exprs + numExprs);
6466  }
6467  else {
6468  // For OpenCL, when the number of initializers is a single value,
6469  // it will be replicated to all components of the vector.
6470  if (getLangOpts().OpenCL &&
6472  numExprs == 1) {
6473  QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6474  ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6475  if (Literal.isInvalid())
6476  return ExprError();
6477  Literal = ImpCastExprToType(Literal.get(), ElemTy,
6478  PrepareScalarCast(Literal, ElemTy));
6479  return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6480  }
6481 
6482  initExprs.append(exprs, exprs + numExprs);
6483  }
6484  // FIXME: This means that pretty-printing the final AST will produce curly
6485  // braces instead of the original commas.
6486  InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6487  initExprs, LiteralRParenLoc);
6488  initE->setType(Ty);
6489  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6490 }
6491 
6492 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6493 /// the ParenListExpr into a sequence of comma binary operators.
6494 ExprResult
6496  ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6497  if (!E)
6498  return OrigExpr;
6499 
6500  ExprResult Result(E->getExpr(0));
6501 
6502  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6503  Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6504  E->getExpr(i));
6505 
6506  if (Result.isInvalid()) return ExprError();
6507 
6508  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6509 }
6510 
6512  SourceLocation R,
6513  MultiExprArg Val) {
6514  return ParenListExpr::Create(Context, L, Val, R);
6515 }
6516 
6517 /// Emit a specialized diagnostic when one expression is a null pointer
6518 /// constant and the other is not a pointer. Returns true if a diagnostic is
6519 /// emitted.
6521  SourceLocation QuestionLoc) {
6522  Expr *NullExpr = LHSExpr;
6523  Expr *NonPointerExpr = RHSExpr;
6525  NullExpr->isNullPointerConstant(Context,
6527 
6528  if (NullKind == Expr::NPCK_NotNull) {
6529  NullExpr = RHSExpr;
6530  NonPointerExpr = LHSExpr;
6531  NullKind =
6532  NullExpr->isNullPointerConstant(Context,
6534  }
6535 
6536  if (NullKind == Expr::NPCK_NotNull)
6537  return false;
6538 
6539  if (NullKind == Expr::NPCK_ZeroExpression)
6540  return false;
6541 
6542  if (NullKind == Expr::NPCK_ZeroLiteral) {
6543  // In this case, check to make sure that we got here from a "NULL"
6544  // string in the source code.
6545  NullExpr = NullExpr->IgnoreParenImpCasts();
6546  SourceLocation loc = NullExpr->getExprLoc();
6547  if (!findMacroSpelling(loc, "NULL"))
6548  return false;
6549  }
6550 
6551  int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6552  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6553  << NonPointerExpr->getType() << DiagType
6554  << NonPointerExpr->getSourceRange();
6555  return true;
6556 }
6557 
6558 /// Return false if the condition expression is valid, true otherwise.
6559 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6560  QualType CondTy = Cond->getType();
6561 
6562  // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6563  if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6564  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6565  << CondTy << Cond->getSourceRange();
6566  return true;
6567  }
6568 
6569  // C99 6.5.15p2
6570  if (CondTy->isScalarType()) return false;
6571 
6572  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6573  << CondTy << Cond->getSourceRange();
6574  return true;
6575 }
6576 
6577 /// Handle when one or both operands are void type.
6579  ExprResult &RHS) {
6580  Expr *LHSExpr = LHS.get();
6581  Expr *RHSExpr = RHS.get();
6582 
6583  if (!LHSExpr->getType()->isVoidType())
6584  S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6585  << RHSExpr->getSourceRange();
6586  if (!RHSExpr->getType()->isVoidType())
6587  S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6588  << LHSExpr->getSourceRange();
6589  LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6590  RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6591  return S.Context.VoidTy;
6592 }
6593 
6594 /// Return false if the NullExpr can be promoted to PointerTy,
6595 /// true otherwise.
6596 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6597  QualType PointerTy) {
6598  if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6599  !NullExpr.get()->isNullPointerConstant(S.Context,
6601  return true;
6602 
6603  NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6604  return false;
6605 }
6606 
6607 /// Checks compatibility between two pointers and return the resulting
6608 /// type.
6610  ExprResult &RHS,
6611  SourceLocation Loc) {
6612  QualType LHSTy = LHS.get()->getType();
6613  QualType RHSTy = RHS.get()->getType();
6614 
6615  if (S.Context.hasSameType(LHSTy, RHSTy)) {
6616  // Two identical pointers types are always compatible.
6617  return LHSTy;
6618  }
6619 
6620  QualType lhptee, rhptee;
6621 
6622  // Get the pointee types.
6623  bool IsBlockPointer = false;
6624  if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6625  lhptee = LHSBTy->getPointeeType();
6626  rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6627  IsBlockPointer = true;
6628  } else {
6629  lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6630  rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6631  }
6632 
6633  // C99 6.5.15p6: If both operands are pointers to compatible types or to
6634  // differently qualified versions of compatible types, the result type is
6635  // a pointer to an appropriately qualified version of the composite
6636  // type.
6637 
6638  // Only CVR-qualifiers exist in the standard, and the differently-qualified
6639  // clause doesn't make sense for our extensions. E.g. address space 2 should
6640  // be incompatible with address space 3: they may live on different devices or
6641  // anything.
6642  Qualifiers lhQual = lhptee.getQualifiers();
6643  Qualifiers rhQual = rhptee.getQualifiers();
6644 
6645  LangAS ResultAddrSpace = LangAS::Default;
6646  LangAS LAddrSpace = lhQual.getAddressSpace();
6647  LangAS RAddrSpace = rhQual.getAddressSpace();
6648 
6649  // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6650  // spaces is disallowed.
6651  if (lhQual.isAddressSpaceSupersetOf(rhQual))
6652  ResultAddrSpace = LAddrSpace;
6653  else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6654  ResultAddrSpace = RAddrSpace;
6655  else {
6656  S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6657  << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6658  << RHS.get()->getSourceRange();
6659  return QualType();
6660  }
6661 
6662  unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6663  auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6664  lhQual.removeCVRQualifiers();
6665  rhQual.removeCVRQualifiers();
6666 
6667  // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6668  // (C99 6.7.3) for address spaces. We assume that the check should behave in
6669  // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6670  // qual types are compatible iff
6671  // * corresponded types are compatible
6672  // * CVR qualifiers are equal
6673  // * address spaces are equal
6674  // Thus for conditional operator we merge CVR and address space unqualified
6675  // pointees and if there is a composite type we return a pointer to it with
6676  // merged qualifiers.
6677  LHSCastKind =
6678  LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6679  RHSCastKind =
6680  RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6681  lhQual.removeAddressSpace();
6682  rhQual.removeAddressSpace();
6683 
6684  lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6685  rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6686 
6687  QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6688 
6689  if (CompositeTy.isNull()) {
6690  // In this situation, we assume void* type. No especially good
6691  // reason, but this is what gcc does, and we do have to pick
6692  // to get a consistent AST.
6693  QualType incompatTy;
6694  incompatTy = S.Context.getPointerType(
6695  S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6696  LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6697  RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6698 
6699  // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6700  // for casts between types with incompatible address space qualifiers.
6701  // For the following code the compiler produces casts between global and
6702  // local address spaces of the corresponded innermost pointees:
6703  // local int *global *a;
6704  // global int *global *b;
6705  // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6706  S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6707  << LHSTy << RHSTy << LHS.get()->getSourceRange()
6708  << RHS.get()->getSourceRange();
6709 
6710  return incompatTy;
6711  }
6712 
6713  // The pointer types are compatible.
6714  // In case of OpenCL ResultTy should have the address space qualifier
6715  // which is a superset of address spaces of both the 2nd and the 3rd
6716  // operands of the conditional operator.
6717  QualType ResultTy = [&, ResultAddrSpace]() {
6718  if (S.getLangOpts().OpenCL) {
6719  Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6720  CompositeQuals.setAddressSpace(ResultAddrSpace);
6721  return S.Context
6722  .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6723  .withCVRQualifiers(MergedCVRQual);
6724  }
6725  return CompositeTy.withCVRQualifiers(MergedCVRQual);
6726  }();
6727  if (IsBlockPointer)
6728  ResultTy = S.Context.getBlockPointerType(ResultTy);
6729  else
6730  ResultTy = S.Context.getPointerType(ResultTy);
6731 
6732  LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6733  RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6734  return ResultTy;
6735 }
6736 
6737 /// Return the resulting type when the operands are both block pointers.
6739  ExprResult &LHS,
6740  ExprResult &RHS,
6741  SourceLocation Loc) {
6742  QualType LHSTy = LHS.get()->getType();
6743  QualType RHSTy = RHS.get()->getType();
6744 
6745  if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6746  if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6747  QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6748  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6749  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6750  return destType;
6751  }
6752  S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6753  << LHSTy << RHSTy << LHS.get()->getSourceRange()
6754  << RHS.get()->getSourceRange();
6755  return QualType();
6756  }
6757 
6758  // We have 2 block pointer types.
6759  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6760 }
6761 
6762 /// Return the resulting type when the operands are both pointers.
6763 static QualType
6765  ExprResult &RHS,
6766  SourceLocation Loc) {
6767  // get the pointer types
6768  QualType LHSTy = LHS.get()->getType();
6769  QualType RHSTy = RHS.get()->getType();
6770 
6771  // get the "pointed to" types
6772  QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6773  QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6774 
6775  // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6776  if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6777  // Figure out necessary qualifiers (C99 6.5.15p6)
6778  QualType destPointee
6779  = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6780  QualType destType = S.Context.getPointerType(destPointee);
6781  // Add qualifiers if necessary.
6782  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6783  // Promote to void*.
6784  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6785  return destType;
6786  }
6787  if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6788  QualType destPointee
6789  = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6790  QualType destType = S.Context.getPointerType(destPointee);
6791  // Add qualifiers if necessary.
6792  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6793  // Promote to void*.
6794  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6795  return destType;
6796  }
6797 
6798  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6799 }
6800 
6801 /// Return false if the first expression is not an integer and the second
6802 /// expression is not a pointer, true otherwise.
6804  Expr* PointerExpr, SourceLocation Loc,
6805  bool IsIntFirstExpr) {
6806  if (!PointerExpr->getType()->isPointerType() ||
6807  !Int.get()->getType()->isIntegerType())
6808  return false;
6809 
6810  Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6811  Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6812 
6813  S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6814  << Expr1->getType() << Expr2->getType()
6815  << Expr1->getSourceRange() << Expr2->getSourceRange();
6816  Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6817  CK_IntegralToPointer);
6818  return true;
6819 }
6820 
6821 /// Simple conversion between integer and floating point types.
6822 ///
6823 /// Used when handling the OpenCL conditional operator where the
6824 /// condition is a vector while the other operands are scalar.
6825 ///
6826 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6827 /// types are either integer or floating type. Between the two
6828 /// operands, the type with the higher rank is defined as the "result
6829 /// type". The other operand needs to be promoted to the same type. No
6830 /// other type promotion is allowed. We cannot use
6831 /// UsualArithmeticConversions() for this purpose, since it always
6832 /// promotes promotable types.
6834  ExprResult &RHS,
6835  SourceLocation QuestionLoc) {
6837  if (LHS.isInvalid())
6838  return QualType();
6840  if (RHS.isInvalid())
6841  return QualType();
6842 
6843  // For conversion purposes, we ignore any qualifiers.
6844  // For example, "const float" and "float" are equivalent.
6845  QualType LHSType =
6846  S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6847  QualType RHSType =
6848  S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6849 
6850  if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6851  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6852  << LHSType << LHS.get()->getSourceRange();
6853  return QualType();
6854  }
6855 
6856  if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6857  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6858  << RHSType << RHS.get()->getSourceRange();
6859  return QualType();
6860  }
6861 
6862  // If both types are identical, no conversion is needed.
6863  if (LHSType == RHSType)
6864  return LHSType;
6865 
6866  // Now handle "real" floating types (i.e. float, double, long double).
6867  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6868  return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6869  /*IsCompAssign = */ false);
6870 
6871  // Finally, we have two differing integer types.
6872  return handleIntegerConversion<doIntegralCast, doIntegralCast>
6873  (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6874 }
6875 
6876 /// Convert scalar operands to a vector that matches the
6877 /// condition in length.
6878 ///
6879 /// Used when handling the OpenCL conditional operator where the
6880 /// condition is a vector while the other operands are scalar.
6881 ///
6882 /// We first compute the "result type" for the scalar operands
6883 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6884 /// into a vector of that type where the length matches the condition
6885 /// vector type. s6.11.6 requires that the element types of the result
6886 /// and the condition must have the same number of bits.
6887 static QualType
6889  QualType CondTy, SourceLocation QuestionLoc) {
6890  QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6891  if (ResTy.isNull()) return QualType();
6892 
6893  const VectorType *CV = CondTy->getAs<VectorType>();
6894  assert(CV);
6895 
6896  // Determine the vector result type
6897  unsigned NumElements = CV->getNumElements();
6898  QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6899 
6900  // Ensure that all types have the same number of bits
6901  if (S.Context.getTypeSize(CV->getElementType())
6902  != S.Context.getTypeSize(ResTy)) {
6903  // Since VectorTy is created internally, it does not pretty print
6904  // with an OpenCL name. Instead, we just print a description.
6905  std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6906  SmallString<64> Str;
6907  llvm::raw_svector_ostream OS(Str);
6908  OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6909  S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6910  << CondTy << OS.str();
6911  return QualType();
6912  }
6913 
6914  // Convert operands to the vector result type
6915  LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6916  RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6917 
6918  return VectorTy;
6919 }
6920 
6921 /// Return false if this is a valid OpenCL condition vector
6922 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6923  SourceLocation QuestionLoc) {
6924  // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6925  // integral type.
6926  const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6927  assert(CondTy);
6928  QualType EleTy = CondTy->getElementType();
6929  if (EleTy->isIntegerType()) return false;
6930 
6931  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6932  << Cond->getType() << Cond->getSourceRange();
6933  return true;
6934 }
6935 
6936 /// Return false if the vector condition type and the vector
6937 /// result type are compatible.
6938 ///
6939 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6940 /// number of elements, and their element types have the same number
6941 /// of bits.
6942 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6943  SourceLocation QuestionLoc) {
6944  const VectorType *CV = CondTy->getAs<VectorType>();
6945  const VectorType *RV = VecResTy->getAs<VectorType>();
6946  assert(CV && RV);
6947 
6948  if (CV->getNumElements() != RV->getNumElements()) {
6949  S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6950  << CondTy << VecResTy;
6951  return true;
6952  }
6953 
6954  QualType CVE = CV->getElementType();
6955  QualType RVE = RV->getElementType();
6956 
6957  if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6958  S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6959  << CondTy << VecResTy;
6960  return true;
6961  }
6962 
6963  return false;
6964 }
6965 
6966 /// Return the resulting type for the conditional operator in
6967 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
6968 /// s6.3.i) when the condition is a vector type.
6969 static QualType
6971  ExprResult &LHS, ExprResult &RHS,
6972  SourceLocation QuestionLoc) {
6973  Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6974  if (Cond.isInvalid())
6975  return QualType();
6976  QualType CondTy = Cond.get()->getType();
6977 
6978  if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6979  return QualType();
6980 
6981  // If either operand is a vector then find the vector type of the
6982  // result as specified in OpenCL v1.1 s6.3.i.
6983  if (LHS.get()->getType()->isVectorType() ||
6984  RHS.get()->getType()->isVectorType()) {
6985  QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6986  /*isCompAssign*/false,
6987  /*AllowBothBool*/true,
6988  /*AllowBoolConversions*/false);
6989  if (VecResTy.isNull()) return QualType();
6990  // The result type must match the condition type as specified in
6991  // OpenCL v1.1 s6.11.6.
6992  if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6993  return QualType();
6994  return VecResTy;
6995  }
6996 
6997  // Both operands are scalar.
6998  return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6999 }
7000 
7001 /// Return true if the Expr is block type
7002 static bool checkBlockType(Sema &S, const Expr *E) {
7003  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7004  QualType Ty = CE->getCallee()->getType();
7005  if (Ty->isBlockPointerType()) {
7006  S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7007  return true;
7008  }
7009  }
7010  return false;
7011 }
7012 
7013 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7014 /// In that case, LHS = cond.
7015 /// C99 6.5.15
7017  ExprResult &RHS, ExprValueKind &VK,
7018  ExprObjectKind &OK,
7019  SourceLocation QuestionLoc) {
7020 
7021  ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7022  if (!LHSResult.isUsable()) return QualType();
7023  LHS = LHSResult;
7024 
7025  ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7026  if (!RHSResult.isUsable()) return QualType();
7027  RHS = RHSResult;
7028 
7029  // C++ is sufficiently different to merit its own checker.
7030  if (getLangOpts().CPlusPlus)
7031  return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7032 
7033  VK = VK_RValue;
7034  OK = OK_Ordinary;
7035 
7036  // The OpenCL operator with a vector condition is sufficiently
7037  // different to merit its own checker.
7038  if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7039  return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7040 
7041  // First, check the condition.
7042  Cond = UsualUnaryConversions(Cond.get());
7043  if (Cond.isInvalid())
7044  return QualType();
7045  if (checkCondition(*this, Cond.get(), QuestionLoc))
7046  return QualType();
7047 
7048  // Now check the two expressions.
7049  if (LHS.get()->getType()->isVectorType() ||
7050  RHS.get()->getType()->isVectorType())
7051  return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7052  /*AllowBothBool*/true,
7053  /*AllowBoolConversions*/false);
7054 
7055  QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7056  if (LHS.isInvalid() || RHS.isInvalid())
7057  return QualType();
7058 
7059  QualType LHSTy = LHS.get()->getType();
7060  QualType RHSTy = RHS.get()->getType();
7061 
7062  // Diagnose attempts to convert between __float128 and long double where
7063  // such conversions currently can't be handled.
7064  if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7065  Diag(QuestionLoc,
7066  diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7067  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7068  return QualType();
7069  }
7070 
7071  // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7072  // selection operator (?:).
7073  if (getLangOpts().OpenCL &&
7074  (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7075  return QualType();
7076  }
7077 
7078  // If both operands have arithmetic type, do the usual arithmetic conversions
7079  // to find a common type: C99 6.5.15p3,5.
7080  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7081  LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7082  RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7083 
7084  return ResTy;
7085  }
7086 
7087  // If both operands are the same structure or union type, the result is that
7088  // type.
7089  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
7090  if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7091  if (LHSRT->getDecl() == RHSRT->getDecl())
7092  // "If both the operands have structure or union type, the result has
7093  // that type." This implies that CV qualifiers are dropped.
7094  return LHSTy.getUnqualifiedType();
7095  // FIXME: Type of conditional expression must be complete in C mode.
7096  }
7097 
7098  // C99 6.5.15p5: "If both operands have void type, the result has void type."
7099  // The following || allows only one side to be void (a GCC-ism).
7100  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7101  return checkConditionalVoidType(*this, LHS, RHS);
7102  }
7103 
7104  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7105  // the type of the other operand."
7106  if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7107  if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7108 
7109  // All objective-c pointer type analysis is done here.
7110  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7111  QuestionLoc);
7112  if (LHS.isInvalid() || RHS.isInvalid())
7113  return QualType();
7114  if (!compositeType.isNull())
7115  return compositeType;
7116 
7117 
7118  // Handle block pointer types.
7119  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7120  return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7121  QuestionLoc);
7122 
7123  // Check constraints for C object pointers types (C99 6.5.15p3,6).
7124  if (LHSTy->isPointerType() && RHSTy->isPointerType())
7125  return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7126  QuestionLoc);
7127 
7128  // GCC compatibility: soften pointer/integer mismatch. Note that
7129  // null pointers have been filtered out by this point.
7130  if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7131  /*isIntFirstExpr=*/true))
7132  return RHSTy;
7133  if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7134  /*isIntFirstExpr=*/false))
7135  return LHSTy;
7136 
7137  // Emit a better diagnostic if one of the expressions is a null pointer
7138  // constant and the other is not a pointer type. In this case, the user most
7139  // likely forgot to take the address of the other expression.
7140  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7141  return QualType();
7142 
7143  // Otherwise, the operands are not compatible.
7144  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7145  << LHSTy << RHSTy << LHS.get()->getSourceRange()
7146  << RHS.get()->getSourceRange();
7147  return QualType();
7148 }
7149 
7150 /// FindCompositeObjCPointerType - Helper method to find composite type of
7151 /// two objective-c pointer types of the two input expressions.
7153  SourceLocation QuestionLoc) {
7154  QualType LHSTy = LHS.get()->getType();
7155  QualType RHSTy = RHS.get()->getType();
7156 
7157  // Handle things like Class and struct objc_class*. Here we case the result
7158  // to the pseudo-builtin, because that will be implicitly cast back to the
7159  // redefinition type if an attempt is made to access its fields.
7160  if (LHSTy->isObjCClassType() &&
7161  (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7162  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7163  return LHSTy;
7164  }
7165  if (RHSTy->isObjCClassType() &&
7166  (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7167  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7168  return RHSTy;
7169  }
7170  // And the same for struct objc_object* / id
7171  if (LHSTy->isObjCIdType() &&
7172  (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7173  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7174  return LHSTy;
7175  }
7176  if (RHSTy->isObjCIdType() &&
7177  (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7178  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7179  return RHSTy;
7180  }
7181  // And the same for struct objc_selector* / SEL
7182  if (Context.isObjCSelType(LHSTy) &&
7183  (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7184  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7185  return LHSTy;
7186  }
7187  if (Context.isObjCSelType(RHSTy) &&
7188  (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7189  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7190  return RHSTy;
7191  }
7192  // Check constraints for Objective-C object pointers types.
7193  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7194 
7195  if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7196  // Two identical object pointer types are always compatible.
7197  return LHSTy;
7198  }
7199  const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7200  const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7201  QualType compositeType = LHSTy;
7202 
7203  // If both operands are interfaces and either operand can be
7204  // assigned to the other, use that type as the composite
7205  // type. This allows
7206  // xxx ? (A*) a : (B*) b
7207  // where B is a subclass of A.
7208  //
7209  // Additionally, as for assignment, if either type is 'id'
7210  // allow silent coercion. Finally, if the types are
7211  // incompatible then make sure to use 'id' as the composite
7212  // type so the result is acceptable for sending messages to.
7213 
7214  // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7215  // It could return the composite type.
7216  if (!(compositeType =
7217  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7218  // Nothing more to do.
7219  } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7220  compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7221  } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7222  compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7223  } else if ((LHSTy->isObjCQualifiedIdType() ||
7224  RHSTy->isObjCQualifiedIdType()) &&
7225  Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7226  // Need to handle "id<xx>" explicitly.
7227  // GCC allows qualified id and any Objective-C type to devolve to
7228  // id. Currently localizing to here until clear this should be
7229  // part of ObjCQualifiedIdTypesAreCompatible.
7230  compositeType = Context.getObjCIdType();
7231  } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7232  compositeType = Context.getObjCIdType();
7233  } else {
7234  Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7235  << LHSTy << RHSTy
7236  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7237  QualType incompatTy = Context.getObjCIdType();
7238  LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7239  RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7240  return incompatTy;
7241  }
7242  // The object pointer types are compatible.
7243  LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7244  RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7245  return compositeType;
7246  }
7247  // Check Objective-C object pointer types and 'void *'
7248  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7249  if (getLangOpts().ObjCAutoRefCount) {
7250  // ARC forbids the implicit conversion of object pointers to 'void *',
7251  // so these types are not compatible.
7252  Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7253  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7254  LHS = RHS = true;
7255  return QualType();
7256  }
7257  QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7258  QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7259  QualType destPointee
7260  = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7261  QualType destType = Context.getPointerType(destPointee);
7262  // Add qualifiers if necessary.
7263  LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7264  // Promote to void*.
7265  RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7266  return destType;
7267  }
7268  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7269  if (getLangOpts().ObjCAutoRefCount) {
7270  // ARC forbids the implicit conversion of object pointers to 'void *',
7271  // so these types are not compatible.
7272  Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7273  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7274  LHS = RHS = true;
7275  return QualType();
7276  }
7277  QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7278  QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7279  QualType destPointee
7280  = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7281  QualType destType = Context.getPointerType(destPointee);
7282  // Add qualifiers if necessary.
7283  RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7284  // Promote to void*.
7285  LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7286  return destType;
7287  }
7288  return QualType();
7289 }
7290 
7291 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7292 /// ParenRange in parentheses.
7293 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7294  const PartialDiagnostic &Note,
7295  SourceRange ParenRange) {
7296  SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7297  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7298  EndLoc.isValid()) {
7299  Self.Diag(Loc, Note)
7300  << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7301  << FixItHint::CreateInsertion(EndLoc, ")");
7302  } else {
7303  // We can't display the parentheses, so just show the bare note.
7304  Self.Diag(Loc, Note) << ParenRange;
7305  }
7306 }
7307 
7309  return BinaryOperator::isAdditiveOp(Opc) ||
7312 }
7313 
7314 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7315 /// expression, either using a built-in or overloaded operator,
7316 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7317 /// expression.
7319  Expr **RHSExprs) {
7320  // Don't strip parenthesis: we should not warn if E is in parenthesis.
7321  E = E->IgnoreImpCasts();
7322  E = E->IgnoreConversionOperator();
7323  E = E->IgnoreImpCasts();
7324  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7325  E = MTE->GetTemporaryExpr();
7326  E = E->IgnoreImpCasts();
7327  }
7328 
7329  // Built-in binary operator.
7330  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7331  if (IsArithmeticOp(OP->getOpcode())) {
7332  *Opcode = OP->getOpcode();
7333  *RHSExprs = OP->getRHS();
7334  return true;
7335  }
7336  }
7337 
7338  // Overloaded operator.
7339  if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7340  if (Call->getNumArgs() != 2)
7341  return false;
7342 
7343  // Make sure this is really a binary operator that is safe to pass into
7344  // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7345  OverloadedOperatorKind OO = Call->getOperator();
7346  if (OO < OO_Plus || OO > OO_Arrow ||
7347  OO == OO_PlusPlus || OO == OO_MinusMinus)
7348  return false;
7349 
7351  if (IsArithmeticOp(OpKind)) {
7352  *Opcode = OpKind;
7353  *RHSExprs = Call->getArg(1);
7354  return true;
7355  }
7356  }
7357 
7358  return false;
7359 }
7360 
7361 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7362 /// or is a logical expression such as (x==y) which has int type, but is
7363 /// commonly interpreted as boolean.
7364 static bool ExprLooksBoolean(Expr *E) {
7365  E = E->IgnoreParenImpCasts();
7366 
7367  if (E->getType()->isBooleanType())
7368  return true;
7369  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7370  return OP->isComparisonOp() || OP->isLogicalOp();
7371  if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7372  return OP->getOpcode() == UO_LNot;
7373  if (E->getType()->isPointerType())
7374  return true;
7375  // FIXME: What about overloaded operator calls returning "unspecified boolean
7376  // type"s (commonly pointer-to-members)?
7377 
7378  return false;
7379 }
7380 
7381 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7382 /// and binary operator are mixed in a way that suggests the programmer assumed
7383 /// the conditional operator has higher precedence, for example:
7384 /// "int x = a + someBinaryCondition ? 1 : 2".
7386  SourceLocation OpLoc,
7387  Expr *Condition,
7388  Expr *LHSExpr,
7389  Expr *RHSExpr) {
7390  BinaryOperatorKind CondOpcode;
7391  Expr *CondRHS;
7392 
7393  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7394  return;
7395  if (!ExprLooksBoolean(CondRHS))
7396  return;
7397 
7398  // The condition is an arithmetic binary expression, with a right-
7399  // hand side that looks boolean, so warn.
7400 
7401  Self.Diag(OpLoc, diag::warn_precedence_conditional)
7402  << Condition->getSourceRange()
7403  << BinaryOperator::getOpcodeStr(CondOpcode);
7404 
7406  Self, OpLoc,
7407  Self.PDiag(diag::note_precedence_silence)
7408  << BinaryOperator::getOpcodeStr(CondOpcode),
7409  SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7410 
7411  SuggestParentheses(Self, OpLoc,
7412  Self.PDiag(diag::note_precedence_conditional_first),
7413  SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7414 }
7415 
7416 /// Compute the nullability of a conditional expression.
7418  QualType LHSTy, QualType RHSTy,
7419  ASTContext &Ctx) {
7420  if (!ResTy->isAnyPointerType())
7421  return ResTy;
7422 
7423  auto GetNullability = [&Ctx](QualType Ty) {
7424  Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7425  if (Kind)
7426  return *Kind;
7428  };
7429 
7430  auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7431  NullabilityKind MergedKind;
7432 
7433  // Compute nullability of a binary conditional expression.
7434  if (IsBin) {
7435  if (LHSKind == NullabilityKind::NonNull)
7436  MergedKind = NullabilityKind::NonNull;
7437  else
7438  MergedKind = RHSKind;
7439  // Compute nullability of a normal conditional expression.
7440  } else {
7441  if (LHSKind == NullabilityKind::Nullable ||
7442  RHSKind == NullabilityKind::Nullable)
7443  MergedKind = NullabilityKind::Nullable;
7444  else if (LHSKind == NullabilityKind::NonNull)
7445  MergedKind = RHSKind;
7446  else if (RHSKind == NullabilityKind::NonNull)
7447  MergedKind = LHSKind;
7448  else
7449  MergedKind = NullabilityKind::Unspecified;
7450  }
7451 
7452  // Return if ResTy already has the correct nullability.
7453  if (GetNullability(ResTy) == MergedKind)
7454  return ResTy;
7455 
7456  // Strip all nullability from ResTy.
7457  while (ResTy->getNullability(Ctx))
7458  ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7459 
7460  // Create a new AttributedType with the new nullability kind.
7461  auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7462  return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7463 }
7464 
7465 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7466 /// in the case of a the GNU conditional expr extension.
7469  Expr *CondExpr, Expr *LHSExpr,
7470  Expr *RHSExpr) {
7471  if (!getLangOpts().CPlusPlus) {
7472  // C cannot handle TypoExpr nodes in the condition because it
7473  // doesn't handle dependent types properly, so make sure any TypoExprs have
7474  // been dealt with before checking the operands.
7475  ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7476  ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7477  ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7478 
7479  if (!CondResult.isUsable())
7480  return ExprError();
7481 
7482  if (LHSExpr) {
7483  if (!LHSResult.isUsable())
7484  return ExprError();
7485  }
7486 
7487  if (!RHSResult.isUsable())
7488  return ExprError();
7489 
7490  CondExpr = CondResult.get();
7491  LHSExpr = LHSResult.get();
7492  RHSExpr = RHSResult.get();
7493  }
7494 
7495  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7496  // was the condition.
7497  OpaqueValueExpr *opaqueValue = nullptr;
7498  Expr *commonExpr = nullptr;
7499  if (!LHSExpr) {
7500  commonExpr = CondExpr;
7501  // Lower out placeholder types first. This is important so that we don't
7502  // try to capture a placeholder. This happens in few cases in C++; such
7503  // as Objective-C++'s dictionary subscripting syntax.
7504  if (commonExpr->hasPlaceholderType()) {
7505  ExprResult result = CheckPlaceholderExpr(commonExpr);
7506  if (!result.isUsable()) return ExprError();
7507  commonExpr = result.get();
7508  }
7509  // We usually want to apply unary conversions *before* saving, except
7510  // in the special case of a C++ l-value conditional.
7511  if (!(getLangOpts().CPlusPlus
7512  && !commonExpr->isTypeDependent()
7513  && commonExpr->getValueKind() == RHSExpr->getValueKind()
7514  && commonExpr->isGLValue()
7515  && commonExpr->isOrdinaryOrBitFieldObject()
7516  && RHSExpr->isOrdinaryOrBitFieldObject()
7517  && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7518  ExprResult commonRes = UsualUnaryConversions(commonExpr);
7519  if (commonRes.isInvalid())
7520  return ExprError();
7521  commonExpr = commonRes.get();
7522  }
7523 
7524  // If the common expression is a class or array prvalue, materialize it
7525  // so that we can safely refer to it multiple times.
7526  if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7527  commonExpr->getType()->isArrayType())) {
7528  ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7529  if (MatExpr.isInvalid())
7530  return ExprError();
7531  commonExpr = MatExpr.get();
7532  }
7533 
7534  opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7535  commonExpr->getType(),
7536  commonExpr->getValueKind(),
7537  commonExpr->getObjectKind(),
7538  commonExpr);
7539  LHSExpr = CondExpr = opaqueValue;
7540  }
7541 
7542  QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7543  ExprValueKind VK = VK_RValue;
7545  ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7546  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7547  VK, OK, QuestionLoc);
7548  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7549  RHS.isInvalid())
7550  return ExprError();
7551 
7552  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7553  RHS.get());
7554 
7555  CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7556 
7557  result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7558  Context);
7559 
7560  if (!commonExpr)
7561  return new (Context)
7562  ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7563  RHS.get(), result, VK, OK);
7564 
7565  return new (Context) BinaryConditionalOperator(
7566  commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7567  ColonLoc, result, VK, OK);
7568 }
7569 
7570 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7571 // being closely modeled after the C99 spec:-). The odd characteristic of this
7572 // routine is it effectively iqnores the qualifiers on the top level pointee.
7573 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7574 // FIXME: add a couple examples in this comment.
7577  assert(LHSType.isCanonical() && "LHS not canonicalized!");
7578  assert(RHSType.isCanonical() && "RHS not canonicalized!");
7579 
7580  // get the "pointed to" type (ignoring qualifiers at the top level)
7581  const Type *lhptee, *rhptee;
7582  Qualifiers lhq, rhq;
7583  std::tie(lhptee, lhq) =
7584  cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7585  std::tie(rhptee, rhq) =
7586  cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7587 
7589 
7590  // C99 6.5.16.1p1: This following citation is common to constraints
7591  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7592  // qualifiers of the type *pointed to* by the right;
7593 
7594  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7595  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7596  lhq.compatiblyIncludesObjCLifetime(rhq)) {
7597  // Ignore lifetime for further calculation.
7598  lhq.removeObjCLifetime();
7599  rhq.removeObjCLifetime();
7600  }
7601 
7602  if (!lhq.compatiblyIncludes(rhq)) {
7603  // Treat address-space mismatches as fatal. TODO: address subspaces
7604  if (!lhq.isAddressSpaceSupersetOf(rhq))
7606 
7607  // It's okay to add or remove GC or lifetime qualifiers when converting to
7608  // and from void*.
7609  else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7612  && (lhptee->isVoidType() || rhptee->isVoidType()))
7613  ; // keep old
7614 
7615  // Treat lifetime mismatches as fatal.
7616  else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7618 
7619  // For GCC/MS compatibility, other qualifier mismatches are treated
7620  // as still compatible in C.
7622  }
7623 
7624  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7625  // incomplete type and the other is a pointer to a qualified or unqualified
7626  // version of void...
7627  if (lhptee->isVoidType()) {
7628  if (rhptee->isIncompleteOrObjectType())
7629  return ConvTy;
7630 
7631  // As an extension, we allow cast to/from void* to function pointer.
7632  assert(rhptee->isFunctionType());
7634  }
7635 
7636  if (rhptee->isVoidType()) {
7637  if (lhptee->isIncompleteOrObjectType())
7638  return ConvTy;
7639 
7640  // As an extension, we allow cast to/from void* to function pointer.
7641  assert(lhptee->isFunctionType());
7643  }
7644 
7645  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7646  // unqualified versions of compatible types, ...
7647  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7648  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7649  // Check if the pointee types are compatible ignoring the sign.
7650  // We explicitly check for char so that we catch "char" vs
7651  // "unsigned char" on systems where "char" is unsigned.
7652  if (lhptee->isCharType())
7653  ltrans = S.Context.UnsignedCharTy;
7654  else if (lhptee->hasSignedIntegerRepresentation())
7655  ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7656 
7657  if (rhptee->isCharType())
7658  rtrans = S.Context.UnsignedCharTy;
7659  else if (rhptee->hasSignedIntegerRepresentation())
7660  rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7661 
7662  if (ltrans == rtrans) {
7663  // Types are compatible ignoring the sign. Qualifier incompatibility
7664  // takes priority over sign incompatibility because the sign
7665  // warning can be disabled.
7666  if (ConvTy != Sema::Compatible)
7667  return ConvTy;
7668 
7670  }
7671 
7672  // If we are a multi-level pointer, it's possible that our issue is simply
7673  // one of qualification - e.g. char ** -> const char ** is not allowed. If
7674  // the eventual target type is the same and the pointers have the same
7675  // level of indirection, this must be the issue.
7676  if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7677  do {
7678  lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7679  rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7680  } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7681 
7682  if (lhptee == rhptee)
7684  }
7685 
7686  // General pointer incompatibility takes priority over qualifiers.
7688  }
7689  if (!S.getLangOpts().CPlusPlus &&
7690  S.IsFunctionConversion(ltrans, rtrans, ltrans))
7692  return ConvTy;
7693 }
7694 
7695 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7696 /// block pointer types are compatible or whether a block and normal pointer
7697 /// are compatible. It is more restrict than comparing two function pointer
7698 // types.
7701  QualType RHSType) {
7702  assert(LHSType.isCanonical() && "LHS not canonicalized!");
7703  assert(RHSType.isCanonical() && "RHS not canonicalized!");
7704 
7705  QualType lhptee, rhptee;
7706 
7707  // get the "pointed to" type (ignoring qualifiers at the top level)
7708  lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7709  rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7710 
7711  // In C++, the types have to match exactly.
7712  if (S.getLangOpts().CPlusPlus)
7714 
7716 
7717  // For blocks we enforce that qualifiers are identical.
7718  Qualifiers LQuals = lhptee.getLocalQualifiers();
7719  Qualifiers RQuals = rhptee.getLocalQualifiers();
7720  if (S.getLangOpts().OpenCL) {
7721  LQuals.removeAddressSpace();
7722  RQuals.removeAddressSpace();
7723  }
7724  if (LQuals != RQuals)
7726 
7727  // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7728  // assignment.
7729  // The current behavior is similar to C++ lambdas. A block might be
7730  // assigned to a variable iff its return type and parameters are compatible
7731  // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7732  // an assignment. Presumably it should behave in way that a function pointer
7733  // assignment does in C, so for each parameter and return type:
7734  // * CVR and address space of LHS should be a superset of CVR and address
7735  // space of RHS.
7736  // * unqualified types should be compatible.
7737  if (S.getLangOpts().OpenCL) {
7739  S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7740  S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7742  } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7744 
7745  return ConvTy;
7746 }
7747 
7748 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7749 /// for assignment compatibility.
7752  QualType RHSType) {
7753  assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7754  assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7755 
7756  if (LHSType->isObjCBuiltinType()) {
7757  // Class is not compatible with ObjC object pointers.
7758  if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7759  !RHSType->isObjCQualifiedClassType())
7761  return Sema::Compatible;
7762  }
7763  if (RHSType->isObjCBuiltinType()) {
7764  if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7765  !LHSType->isObjCQualifiedClassType())
7767  return Sema::Compatible;
7768  }
7769  QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7770  QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7771 
7772  if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7773  // make an exception for id<P>
7774  !LHSType->isObjCQualifiedIdType())
7776 
7777  if (S.Context.typesAreCompatible(LHSType, RHSType))
7778  return Sema::Compatible;
7779  if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7782 }
7783 
7786  QualType LHSType, QualType RHSType) {
7787  // Fake up an opaque expression. We don't actually care about what
7788  // cast operations are required, so if CheckAssignmentConstraints
7789  // adds casts to this they'll be wasted, but fortunately that doesn't
7790  // usually happen on valid code.
7791  OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7792  ExprResult RHSPtr = &RHSExpr;
7793  CastKind K;
7794 
7795  return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7796 }
7797 
7798 /// This helper function returns true if QT is a vector type that has element
7799 /// type ElementType.
7800 static bool isVector(QualType QT, QualType ElementType) {
7801  if (const VectorType *VT = QT->getAs<VectorType>())
7802  return VT->getElementType() == ElementType;
7803  return false;
7804 }
7805 
7806 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7807 /// has code to accommodate several GCC extensions when type checking
7808 /// pointers. Here are some objectionable examples that GCC considers warnings:
7809 ///
7810 /// int a, *pint;
7811 /// short *pshort;
7812 /// struct foo *pfoo;
7813 ///
7814 /// pint = pshort; // warning: assignment from incompatible pointer type
7815 /// a = pint; // warning: assignment makes integer from pointer without a cast
7816 /// pint = a; // warning: assignment makes pointer from integer without a cast
7817 /// pint = pfoo; // warning: assignment from incompatible pointer type
7818 ///
7819 /// As a result, the code for dealing with pointers is more complex than the
7820 /// C99 spec dictates.
7821 ///
7822 /// Sets 'Kind' for any result kind except Incompatible.
7825  CastKind &Kind, bool ConvertRHS) {
7826  QualType RHSType = RHS.get()->getType();
7827  QualType OrigLHSType = LHSType;
7828 
7829  // Get canonical types. We're not formatting these types, just comparing
7830  // them.
7831  LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7832  RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7833 
7834  // Common case: no conversion required.
7835  if (LHSType == RHSType) {
7836  Kind = CK_NoOp;
7837  return Compatible;
7838  }
7839 
7840  // If we have an atomic type, try a non-atomic assignment, then just add an
7841  // atomic qualification step.
7842  if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7843  Sema::AssignConvertType result =
7844  CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7845  if (result != Compatible)
7846  return result;
7847  if (Kind != CK_NoOp && ConvertRHS)
7848  RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7849  Kind = CK_NonAtomicToAtomic;
7850  return Compatible;
7851  }
7852 
7853  // If the left-hand side is a reference type, then we are in a
7854  // (rare!) case where we've allowed the use of references in C,
7855  // e.g., as a parameter type in a built-in function. In this case,
7856  // just make sure that the type referenced is compatible with the
7857  // right-hand side type. The caller is responsible for adjusting
7858  // LHSType so that the resulting expression does not have reference
7859  // type.
7860  if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7861  if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7862  Kind = CK_LValueBitCast;
7863  return Compatible;
7864  }
7865  return Incompatible;
7866  }
7867 
7868  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7869  // to the same ExtVector type.
7870  if (LHSType->isExtVectorType()) {
7871  if (RHSType->isExtVectorType())
7872  return Incompatible;
7873  if (RHSType->isArithmeticType()) {
7874  // CK_VectorSplat does T -> vector T, so first cast to the element type.
7875  if (ConvertRHS)
7876  RHS = prepareVectorSplat(LHSType, RHS.get());
7877  Kind = CK_VectorSplat;
7878  return Compatible;
7879  }
7880  }
7881 
7882  // Conversions to or from vector type.
7883  if (LHSType->isVectorType() || RHSType->isVectorType()) {
7884  if (LHSType->isVectorType() && RHSType->isVectorType()) {
7885  // Allow assignments of an AltiVec vector type to an equivalent GCC
7886  // vector type and vice versa
7887  if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7888  Kind = CK_BitCast;
7889  return Compatible;
7890  }
7891 
7892  // If we are allowing lax vector conversions, and LHS and RHS are both
7893  // vectors, the total size only needs to be the same. This is a bitcast;
7894  // no bits are changed but the result type is different.
7895  if (isLaxVectorConversion(RHSType, LHSType)) {
7896  Kind = CK_BitCast;
7897  return IncompatibleVectors;
7898  }
7899  }
7900 
7901  // When the RHS comes from another lax conversion (e.g. binops between
7902  // scalars and vectors) the result is canonicalized as a vector. When the
7903  // LHS is also a vector, the lax is allowed by the condition above. Handle
7904  // the case where LHS is a scalar.
7905  if (LHSType->isScalarType()) {
7906  const VectorType *VecType = RHSType->getAs<VectorType>();
7907  if (VecType && VecType->getNumElements() == 1 &&
7908  isLaxVectorConversion(RHSType, LHSType)) {
7909  ExprResult *VecExpr = &RHS;
7910  *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7911  Kind = CK_BitCast;
7912  return Compatible;
7913  }
7914  }
7915 
7916  return Incompatible;
7917  }
7918 
7919  // Diagnose attempts to convert between __float128 and long double where
7920  // such conversions currently can't be handled.
7921  if (unsupportedTypeConversion(*this, LHSType, RHSType))
7922  return Incompatible;
7923 
7924  // Disallow assigning a _Complex to a real type in C++ mode since it simply
7925  // discards the imaginary part.
7926  if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7927  !LHSType->getAs<ComplexType>())
7928  return Incompatible;
7929 
7930  // Arithmetic conversions.
7931  if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7932  !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7933  if (ConvertRHS)
7934  Kind = PrepareScalarCast(RHS, LHSType);
7935  return Compatible;
7936  }
7937 
7938  // Conversions to normal pointers.
7939  if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7940  // U* -> T*
7941  if (isa<PointerType>(RHSType)) {
7942  LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7943  LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7944  if (AddrSpaceL != AddrSpaceR)
7945  Kind = CK_AddressSpaceConversion;
7946  else if (Context.hasCvrSimilarType(RHSType, LHSType))
7947  Kind = CK_NoOp;
7948  else
7949  Kind = CK_BitCast;
7950  return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7951  }
7952 
7953  // int -> T*
7954  if (RHSType->isIntegerType()) {
7955  Kind = CK_IntegralToPointer; // FIXME: null?
7956  return IntToPointer;
7957  }
7958 
7959  // C pointers are not compatible with ObjC object pointers,
7960  // with two exceptions:
7961  if (isa<ObjCObjectPointerType>(RHSType)) {
7962  // - conversions to void*
7963  if (LHSPointer->getPointeeType()->isVoidType()) {
7964  Kind = CK_BitCast;
7965  return Compatible;
7966  }
7967 
7968  // - conversions from 'Class' to the redefinition type
7969  if (RHSType->isObjCClassType() &&
7970  Context.hasSameType(LHSType,
7971  Context.getObjCClassRedefinitionType())) {
7972  Kind = CK_BitCast;
7973  return Compatible;
7974  }
7975 
7976  Kind = CK_BitCast;
7977  return IncompatiblePointer;
7978  }
7979 
7980  // U^ -> void*
7981  if (RHSType->getAs<BlockPointerType>()) {
7982  if (LHSPointer->getPointeeType()->isVoidType()) {
7983  LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7984  LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7985  ->getPointeeType()
7986  .getAddressSpace();
7987  Kind =
7988  AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7989  return Compatible;
7990  }
7991  }
7992 
7993  return Incompatible;
7994  }
7995 
7996  // Conversions to block pointers.
7997  if (isa<BlockPointerType>(LHSType)) {
7998  // U^ -> T^
7999  if (RHSType->isBlockPointerType()) {
8000  LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8001  ->getPointeeType()
8002  .getAddressSpace();
8003  LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8004  ->getPointeeType()
8005  .getAddressSpace();
8006  Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8007  return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8008  }
8009 
8010  // int or null -> T^
8011  if (RHSType->isIntegerType()) {
8012  Kind = CK_IntegralToPointer; // FIXME: null
8013  return IntToBlockPointer;
8014  }
8015 
8016  // id -> T^
8017  if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8018  Kind = CK_AnyPointerToBlockPointerCast;
8019  return Compatible;
8020  }
8021 
8022  // void* -> T^
8023  if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8024  if (RHSPT->getPointeeType()->isVoidType()) {
8025  Kind = CK_AnyPointerToBlockPointerCast;
8026  return Compatible;
8027  }
8028 
8029  return Incompatible;
8030  }
8031 
8032  // Conversions to Objective-C pointers.
8033  if (isa<ObjCObjectPointerType>(LHSType)) {
8034  // A* -> B*
8035  if (RHSType->isObjCObjectPointerType()) {
8036  Kind = CK_BitCast;
8037  Sema::AssignConvertType result =
8038  checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8039  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8040  result == Compatible &&
8041  !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8042  result = IncompatibleObjCWeakRef;
8043  return result;
8044  }
8045 
8046  // int or null -> A*
8047  if (RHSType->isIntegerType()) {
8048  Kind = CK_IntegralToPointer; // FIXME: null
8049  return IntToPointer;
8050  }
8051 
8052  // In general, C pointers are not compatible with ObjC object pointers,
8053  // with two exceptions:
8054  if (isa<PointerType>(RHSType)) {
8055  Kind = CK_CPointerToObjCPointerCast;
8056 
8057  // - conversions from 'void*'
8058  if (RHSType->isVoidPointerType()) {
8059  return Compatible;
8060  }
8061 
8062  // - conversions to 'Class' from its redefinition type
8063  if (LHSType->isObjCClassType() &&
8064  Context.hasSameType(RHSType,
8065  Context.getObjCClassRedefinitionType())) {
8066  return Compatible;
8067  }
8068 
8069  return IncompatiblePointer;
8070  }
8071 
8072  // Only under strict condition T^ is compatible with an Objective-C pointer.
8073  if (RHSType->isBlockPointerType() &&
8074  LHSType->isBlockCompatibleObjCPointerType(Context)) {
8075  if (ConvertRHS)
8076  maybeExtendBlockObject(RHS);
8077  Kind = CK_BlockPointerToObjCPointerCast;
8078  return Compatible;
8079  }
8080 
8081  return Incompatible;
8082  }
8083 
8084  // Conversions from pointers that are not covered by the above.
8085  if (isa<PointerType>(RHSType)) {
8086  // T* -> _Bool
8087  if (LHSType == Context.BoolTy) {
8088  Kind = CK_PointerToBoolean;
8089  return Compatible;
8090  }
8091 
8092  // T* -> int
8093  if (LHSType->isIntegerType()) {
8094  Kind = CK_PointerToIntegral;
8095  return PointerToInt;
8096  }
8097 
8098  return Incompatible;
8099  }
8100 
8101  // Conversions from Objective-C pointers that are not covered by the above.
8102  if (isa<ObjCObjectPointerType>(RHSType)) {
8103  // T* -> _Bool
8104  if (LHSType == Context.BoolTy) {
8105  Kind = CK_PointerToBoolean;
8106  return Compatible;
8107  }
8108 
8109  // T* -> int
8110  if (LHSType->isIntegerType()) {
8111  Kind = CK_PointerToIntegral;
8112  return PointerToInt;
8113  }
8114 
8115  return Incompatible;
8116  }
8117 
8118  // struct A -> struct B
8119  if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8120  if (Context.typesAreCompatible(LHSType, RHSType)) {
8121  Kind = CK_NoOp;
8122  return Compatible;
8123  }
8124  }
8125 
8126  if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8127  Kind = CK_IntToOCLSampler;
8128  return Compatible;
8129  }
8130 
8131  return Incompatible;
8132 }
8133 
8134 /// Constructs a transparent union from an expression that is
8135 /// used to initialize the transparent union.
8137  ExprResult &EResult, QualType UnionType,
8138  FieldDecl *Field) {
8139  // Build an initializer list that designates the appropriate member
8140  // of the transparent union.
8141  Expr *E = EResult.get();
8142  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8143  E, SourceLocation());
8144  Initializer->setType(UnionType);
8145  Initializer->setInitializedFieldInUnion(Field);
8146 
8147  // Build a compound literal constructing a value of the transparent
8148  // union type from this initializer list.
8149  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8150  EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8151  VK_RValue, Initializer, false);
8152 }
8153 
8156  ExprResult &RHS) {
8157  QualType RHSType = RHS.get()->getType();
8158 
8159  // If the ArgType is a Union type, we want to handle a potential
8160  // transparent_union GCC extension.
8161  const RecordType *UT = ArgType->getAsUnionType();
8162  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8163  return Incompatible;
8164 
8165  // The field to initialize within the transparent union.
8166  RecordDecl *UD = UT->getDecl();
8167  FieldDecl *InitField = nullptr;
8168  // It's compatible if the expression matches any of the fields.
8169  for (auto *it : UD->fields()) {
8170  if (it->getType()->isPointerType()) {
8171  // If the transparent union contains a pointer type, we allow:
8172  // 1) void pointer
8173  // 2) null pointer constant
8174  if (RHSType->isPointerType())
8175  if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8176  RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8177  InitField = it;
8178  break;
8179  }
8180 
8181  if (RHS.get()->isNullPointerConstant(Context,
8183  RHS = ImpCastExprToType(RHS.get(), it->getType(),
8184  CK_NullToPointer);
8185  InitField = it;
8186  break;
8187  }
8188  }
8189 
8190  CastKind Kind;
8191  if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8192  == Compatible) {
8193  RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8194  InitField = it;
8195  break;
8196  }
8197  }
8198 
8199  if (!InitField)
8200  return Incompatible;
8201 
8202  ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8203  return Compatible;
8204 }
8205 
8208  bool Diagnose,
8209  bool DiagnoseCFAudited,
8210  bool ConvertRHS) {
8211  // We need to be able to tell the caller whether we diagnosed a problem, if
8212  // they ask us to issue diagnostics.
8213  assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8214 
8215  // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8216  // we can't avoid *all* modifications at the moment, so we need some somewhere
8217  // to put the updated value.
8218  ExprResult LocalRHS = CallerRHS;
8219  ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8220 
8221  if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8222  if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8223  if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8224  !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8225  Diag(RHS.get()->getExprLoc(),
8226  diag::warn_noderef_to_dereferenceable_pointer)
8227  << RHS.get()->getSourceRange();
8228  }
8229  }
8230  }
8231 
8232  if (getLangOpts().CPlusPlus) {
8233  if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8234  // C++ 5.17p3: If the left operand is not of class type, the
8235  // expression is implicitly converted (C++ 4) to the
8236  // cv-unqualified type of the left operand.
8237  QualType RHSType = RHS.get()->getType();
8238  if (Diagnose) {
8239  RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8240  AA_Assigning);
8241  } else {
8243  TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8244  /*SuppressUserConversions=*/false,
8245  /*AllowExplicit=*/false,
8246  /*InOverloadResolution=*/false,
8247  /*CStyle=*/false,
8248  /*AllowObjCWritebackConversion=*/false);
8249  if (ICS.isFailure())
8250  return Incompatible;
8251  RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8252  ICS, AA_Assigning);
8253  }
8254  if (RHS.isInvalid())
8255  return Incompatible;
8256  Sema::AssignConvertType result = Compatible;
8257  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8258  !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8259  result = IncompatibleObjCWeakRef;
8260  return result;
8261  }
8262 
8263  // FIXME: Currently, we fall through and treat C++ classes like C
8264  // structures.
8265  // FIXME: We also fall through for atomics; not sure what should
8266  // happen there, though.
8267  } else if (RHS.get()->getType() == Context.OverloadTy) {
8268  // As a set of extensions to C, we support overloading on functions. These
8269  // functions need to be resolved here.
8270  DeclAccessPair DAP;
8271  if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8272  RHS.get(), LHSType, /*Complain=*/false, DAP))
8273  RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8274  else
8275  return Incompatible;
8276  }
8277 
8278  // C99 6.5.16.1p1: the left operand is a pointer and the right is
8279  // a null pointer constant.
8280  if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8281  LHSType->isBlockPointerType()) &&
8282  RHS.get()->isNullPointerConstant(Context,
8284  if (Diagnose || ConvertRHS) {
8285  CastKind Kind;
8286  CXXCastPath Path;
8287  CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8288  /*IgnoreBaseAccess=*/false, Diagnose);
8289  if (ConvertRHS)
8290  RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8291  }
8292  return Compatible;
8293  }
8294 
8295  // OpenCL queue_t type assignment.
8296  if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8297  Context, Expr::NPC_ValueDependentIsNull)) {
8298  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8299  return Compatible;
8300  }
8301 
8302  // This check seems unnatural, however it is necessary to ensure the proper
8303  // conversion of functions/arrays. If the conversion were done for all
8304  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8305  // expressions that suppress this implicit conversion (&, sizeof).
8306  //
8307  // Suppress this for references: C++ 8.5.3p5.
8308  if (!LHSType->isReferenceType()) {
8309  // FIXME: We potentially allocate here even if ConvertRHS is false.
8310  RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8311  if (RHS.isInvalid())
8312  return Incompatible;
8313  }
8314  CastKind Kind;
8315  Sema::AssignConvertType result =
8316  CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8317 
8318  // C99 6.5.16.1p2: The value of the right operand is converted to the
8319  // type of the assignment expression.
8320  // CheckAssignmentConstraints allows the left-hand side to be a reference,
8321  // so that we can use references in built-in functions even in C.
8322  // The getNonReferenceType() call makes sure that the resulting expression
8323  // does not have reference type.
8324  if (result != Incompatible && RHS.get()->getType() != LHSType) {
8325  QualType Ty = LHSType.getNonLValueExprType(Context);
8326  Expr *E = RHS.get();
8327 
8328  // Check for various Objective-C errors. If we are not reporting
8329  // diagnostics and just checking for errors, e.g., during overload
8330  // resolution, return Incompatible to indicate the failure.
8331  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8332  CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8333  Diagnose, DiagnoseCFAudited) != ACR_okay) {
8334  if (!Diagnose)
8335  return Incompatible;
8336  }
8337  if (getLangOpts().ObjC &&
8338  (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8339  E->getType(), E, Diagnose) ||
8340  ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8341  if (!Diagnose)
8342  return Incompatible;
8343  // Replace the expression with a corrected version and continue so we
8344  // can find further errors.
8345  RHS = E;
8346  return Compatible;
8347  }
8348 
8349  if (ConvertRHS)
8350  RHS = ImpCastExprToType(E, Ty, Kind);
8351  }
8352 
8353  return result;
8354 }
8355 
8356 namespace {
8357 /// The original operand to an operator, prior to the application of the usual
8358 /// arithmetic conversions and converting the arguments of a builtin operator
8359 /// candidate.
8360 struct OriginalOperand {
8361  explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8362  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8363  Op = MTE->GetTemporaryExpr();
8364  if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8365  Op = BTE->getSubExpr();
8366  if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8367  Orig = ICE->getSubExprAsWritten();
8368  Conversion = ICE->getConversionFunction();
8369  }
8370  }
8371 
8372  QualType getType() const { return Orig->getType(); }
8373 
8374  Expr *Orig;
8375  NamedDecl *Conversion;
8376 };
8377 }
8378 
8380  ExprResult &RHS) {
8381  OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8382 
8383  Diag(Loc, diag::err_typecheck_invalid_operands)
8384  << OrigLHS.getType() << OrigRHS.getType()
8385  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8386 
8387  // If a user-defined conversion was applied to either of the operands prior
8388  // to applying the built-in operator rules, tell the user about it.
8389  if (OrigLHS.Conversion) {
8390  Diag(OrigLHS.Conversion->getLocation(),
8391  diag::note_typecheck_invalid_operands_converted)
8392  << 0 << LHS.get()->getType();
8393  }
8394  if (OrigRHS.Conversion) {
8395  Diag(OrigRHS.Conversion->getLocation(),
8396  diag::note_typecheck_invalid_operands_converted)
8397  << 1 << RHS.get()->getType();
8398  }
8399 
8400  return QualType();
8401 }
8402 
8403 // Diagnose cases where a scalar was implicitly converted to a vector and
8404 // diagnose the underlying types. Otherwise, diagnose the error
8405 // as invalid vector logical operands for non-C++ cases.
8407  ExprResult &RHS) {
8408  QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8409  QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8410 
8411  bool LHSNatVec = LHSType->isVectorType();
8412  bool RHSNatVec = RHSType->isVectorType();
8413 
8414  if (!(LHSNatVec && RHSNatVec)) {
8415  Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8416  Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8417  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8418  << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8419  << Vector->getSourceRange();
8420  return QualType();
8421  }
8422 
8423  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8424  << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8425  << RHS.get()->getSourceRange();
8426 
8427  return QualType();
8428 }
8429 
8430 /// Try to convert a value of non-vector type to a vector type by converting
8431 /// the type to the element type of the vector and then performing a splat.
8432 /// If the language is OpenCL, we only use conversions that promote scalar
8433 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8434 /// for float->int.
8435 ///
8436 /// OpenCL V2.0 6.2.6.p2:
8437 /// An error shall occur if any scalar operand type has greater rank
8438 /// than the type of the vector element.
8439 ///
8440 /// \param scalar - if non-null, actually perform the conversions
8441 /// \return true if the operation fails (but without diagnosing the failure)
8442 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8443  QualType scalarTy,
8444  QualType vectorEltTy,
8445  QualType vectorTy,
8446  unsigned &DiagID) {
8447  // The conversion to apply to the scalar before splatting it,
8448  // if necessary.
8449  CastKind scalarCast = CK_NoOp;
8450 
8451  if (vectorEltTy->isIntegralType(S.Context)) {
8452  if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8453  (scalarTy->isIntegerType() &&
8454  S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8455  DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8456  return true;
8457  }
8458  if (!scalarTy->isIntegralType(S.Context))
8459  return true;
8460  scalarCast = CK_IntegralCast;
8461  } else if (vectorEltTy->isRealFloatingType()) {
8462  if (scalarTy->isRealFloatingType()) {
8463  if (S.getLangOpts().OpenCL &&
8464  S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8465  DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8466  return true;
8467  }
8468  scalarCast = CK_FloatingCast;
8469  }
8470  else if (scalarTy->isIntegralType(S.Context))
8471  scalarCast = CK_IntegralToFloating;
8472  else
8473  return true;
8474  } else {
8475  return true;
8476  }
8477 
8478  // Adjust scalar if desired.
8479  if (scalar) {
8480  if (scalarCast != CK_NoOp)
8481  *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8482  *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8483  }
8484  return false;
8485 }
8486 
8487 /// Convert vector E to a vector with the same number of elements but different
8488 /// element type.
8489 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8490  const auto *VecTy = E->getType()->getAs<VectorType>();
8491  assert(VecTy && "Expression E must be a vector");
8492  QualType NewVecTy = S.Context.getVectorType(ElementType,
8493  VecTy->getNumElements(),
8494  VecTy->getVectorKind());
8495 
8496  // Look through the implicit cast. Return the subexpression if its type is
8497  // NewVecTy.
8498  if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8499  if (ICE->getSubExpr()->getType() == NewVecTy)
8500  return ICE->getSubExpr();
8501 
8502  auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8503  return S.ImpCastExprToType(E, NewVecTy, Cast);
8504 }
8505 
8506 /// Test if a (constant) integer Int can be casted to another integer type
8507 /// IntTy without losing precision.
8509  QualType OtherIntTy) {
8510  QualType IntTy = Int->get()->getType().getUnqualifiedType();
8511 
8512  // Reject cases where the value of the Int is unknown as that would
8513  // possibly cause truncation, but accept cases where the scalar can be
8514  // demoted without loss of precision.
8515  Expr::EvalResult EVResult;
8516  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8517  int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8518  bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8519  bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8520 
8521  if (CstInt) {
8522  // If the scalar is constant and is of a higher order and has more active
8523  // bits that the vector element type, reject it.
8524  llvm::APSInt Result = EVResult.Val.getInt();
8525  unsigned NumBits = IntSigned
8526  ? (Result.isNegative() ? Result.getMinSignedBits()
8527  : Result.getActiveBits())
8528  : Result.getActiveBits();
8529  if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8530  return true;
8531 
8532  // If the signedness of the scalar type and the vector element type
8533  // differs and the number of bits is greater than that of the vector
8534  // element reject it.
8535  return (IntSigned != OtherIntSigned &&
8536  NumBits > S.Context.getIntWidth(OtherIntTy));
8537  }
8538 
8539  // Reject cases where the value of the scalar is not constant and it's
8540  // order is greater than that of the vector element type.
8541  return (Order < 0);
8542 }
8543 
8544 /// Test if a (constant) integer Int can be casted to floating point type
8545 /// FloatTy without losing precision.
8547  QualType FloatTy) {
8548  QualType IntTy = Int->get()->getType().getUnqualifiedType();
8549 
8550  // Determine if the integer constant can be expressed as a floating point
8551  // number of the appropriate type.
8552  Expr::EvalResult EVResult;
8553  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8554 
8555  uint64_t Bits = 0;
8556  if (CstInt) {
8557  // Reject constants that would be truncated if they were converted to
8558  // the floating point type. Test by simple to/from conversion.
8559  // FIXME: Ideally the conversion to an APFloat and from an APFloat
8560  // could be avoided if there was a convertFromAPInt method
8561  // which could signal back if implicit truncation occurred.
8562  llvm::APSInt Result = EVResult.Val.getInt();
8563  llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8564  Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8565  llvm::APFloat::rmTowardZero);
8566  llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8567  !IntTy->hasSignedIntegerRepresentation());
8568  bool Ignored = false;
8569  Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8570  &Ignored);
8571  if (Result != ConvertBack)
8572  return true;
8573  } else {
8574  // Reject types that cannot be fully encoded into the mantissa of
8575  // the float.
8576  Bits = S.Context.getTypeSize(IntTy);
8577  unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8578  S.Context.getFloatTypeSemantics(FloatTy));
8579  if (Bits > FloatPrec)
8580  return true;
8581  }
8582 
8583  return false;
8584 }
8585 
8586 /// Attempt to convert and splat Scalar into a vector whose types matches
8587 /// Vector following GCC conversion rules. The rule is that implicit
8588 /// conversion can occur when Scalar can be casted to match Vector's element
8589 /// type without causing truncation of Scalar.
8591  ExprResult *Vector) {
8592  QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8593  QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8594  const VectorType *VT = VectorTy->getAs<VectorType>();
8595 
8596  assert(!isa<ExtVectorType>(VT) &&
8597  "ExtVectorTypes should not be handled here!");
8598 
8599  QualType VectorEltTy = VT->getElementType();
8600 
8601  // Reject cases where the vector element type or the scalar element type are
8602  // not integral or floating point types.
8603  if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8604  return true;
8605 
8606  // The conversion to apply to the scalar before splatting it,
8607  // if necessary.
8608  CastKind ScalarCast = CK_NoOp;
8609 
8610  // Accept cases where the vector elements are integers and the scalar is
8611  // an integer.
8612  // FIXME: Notionally if the scalar was a floating point value with a precise
8613  // integral representation, we could cast it to an appropriate integer
8614  // type and then perform the rest of the checks here. GCC will perform
8615  // this conversion in some cases as determined by the input language.
8616  // We should accept it on a language independent basis.
8617  if (VectorEltTy->isIntegralType(S.Context) &&
8618  ScalarTy->isIntegralType(S.Context) &&
8619  S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8620 
8621  if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8622  return true;
8623 
8624  ScalarCast = CK_IntegralCast;
8625  } else if (VectorEltTy->isRealFloatingType()) {
8626  if (ScalarTy->isRealFloatingType()) {
8627 
8628  // Reject cases where the scalar type is not a constant and has a higher
8629  // Order than the vector element type.
8630  llvm::APFloat Result(0.0);
8631  bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8632  int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8633  if (!CstScalar && Order < 0)
8634  return true;
8635 
8636  // If the scalar cannot be safely casted to the vector element type,
8637  // reject it.
8638  if (CstScalar) {
8639  bool Truncated = false;
8640  Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8641  llvm::APFloat::rmNearestTiesToEven, &Truncated);
8642  if (Truncated)
8643  return true;
8644  }
8645 
8646  ScalarCast = CK_FloatingCast;
8647  } else if (ScalarTy->isIntegralType(S.Context)) {
8648  if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8649  return true;
8650 
8651  ScalarCast = CK_IntegralToFloating;
8652  } else
8653  return true;
8654  }
8655 
8656  // Adjust scalar if desired.
8657  if (Scalar) {
8658  if (ScalarCast != CK_NoOp)
8659  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8660  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8661  }
8662  return false;
8663 }
8664 
8666  SourceLocation Loc, bool IsCompAssign,
8667  bool AllowBothBool,
8668  bool AllowBoolConversions) {
8669  if (!IsCompAssign) {
8670  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8671  if (LHS.isInvalid())
8672  return QualType();
8673  }
8674  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8675  if (RHS.isInvalid())
8676  return QualType();
8677 
8678  // For conversion purposes, we ignore any qualifiers.
8679  // For example, "const float" and "float" are equivalent.
8680  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8681  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8682 
8683  const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8684  const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8685  assert(LHSVecType || RHSVecType);
8686 
8687  // AltiVec-style "vector bool op vector bool" combinations are allowed
8688  // for some operators but not others.
8689  if (!AllowBothBool &&
8690  LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8691  RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8692  return InvalidOperands(Loc, LHS, RHS);
8693 
8694  // If the vector types are identical, return.
8695  if (Context.hasSameType(LHSType, RHSType))
8696  return LHSType;
8697 
8698  // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8699  if (LHSVecType && RHSVecType &&
8700  Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8701  if (isa<ExtVectorType>(LHSVecType)) {
8702  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8703  return LHSType;
8704  }
8705 
8706  if (!IsCompAssign)
8707  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8708  return RHSType;
8709  }
8710 
8711  // AllowBoolConversions says that bool and non-bool AltiVec vectors
8712  // can be mixed, with the result being the non-bool type. The non-bool
8713  // operand must have integer element type.
8714  if (AllowBoolConversions && LHSVecType && RHSVecType &&
8715  LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8716  (Context.getTypeSize(LHSVecType->getElementType()) ==
8717  Context.getTypeSize(RHSVecType->getElementType()))) {
8718  if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8719  LHSVecType->getElementType()->isIntegerType() &&
8720  RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8721  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8722  return LHSType;
8723  }
8724  if (!IsCompAssign &&
8725  LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8726  RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8727  RHSVecType->getElementType()->isIntegerType()) {
8728  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8729  return RHSType;
8730  }
8731  }
8732 
8733  // If there's a vector type and a scalar, try to convert the scalar to
8734  // the vector element type and splat.
8735  unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8736  if (!RHSVecType) {
8737  if (isa<ExtVectorType>(LHSVecType)) {
8738  if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8739  LHSVecType->getElementType(), LHSType,
8740  DiagID))
8741  return LHSType;
8742  } else {
8743  if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8744  return LHSType;
8745  }
8746  }
8747  if (!LHSVecType) {
8748  if (isa<ExtVectorType>(RHSVecType)) {
8749  if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8750  LHSType, RHSVecType->getElementType(),
8751  RHSType, DiagID))
8752  return RHSType;
8753  } else {
8754  if (LHS.get()->getValueKind() == VK_LValue ||
8755  !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8756  return RHSType;
8757  }
8758  }
8759 
8760  // FIXME: The code below also handles conversion between vectors and
8761  // non-scalars, we should break this down into fine grained specific checks
8762  // and emit proper diagnostics.
8763  QualType VecType = LHSVecType ? LHSType : RHSType;
8764  const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8765  QualType OtherType = LHSVecType ? RHSType : LHSType;
8766  ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8767  if (isLaxVectorConversion(OtherType, VecType)) {
8768  // If we're allowing lax vector conversions, only the total (data) size
8769  // needs to be the same. For non compound assignment, if one of the types is
8770  // scalar, the result is always the vector type.
8771  if (!IsCompAssign) {
8772  *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8773  return VecType;
8774  // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8775  // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8776  // type. Note that this is already done by non-compound assignments in
8777  // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8778  // <1 x T> -> T. The result is also a vector type.
8779  } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8780  (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8781  ExprResult *RHSExpr = &RHS;
8782  *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8783  return VecType;
8784  }
8785  }
8786 
8787  // Okay, the expression is invalid.
8788 
8789  // If there's a non-vector, non-real operand, diagnose that.
8790  if ((!RHSVecType && !RHSType->isRealType()) ||
8791  (!LHSVecType && !LHSType->isRealType())) {
8792  Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8793  << LHSType << RHSType
8794  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8795  return QualType();
8796  }
8797 
8798  // OpenCL V1.1 6.2.6.p1:
8799  // If the operands are of more than one vector type, then an error shall
8800  // occur. Implicit conversions between vector types are not permitted, per
8801  // section 6.2.1.
8802  if (getLangOpts().OpenCL &&
8803  RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8804  LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8805  Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8806  << RHSType;
8807  return QualType();
8808  }
8809 
8810 
8811  // If there is a vector type that is not a ExtVector and a scalar, we reach
8812  // this point if scalar could not be converted to the vector's element type
8813  // without truncation.
8814  if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8815  (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8816  QualType Scalar = LHSVecType ? RHSType : LHSType;
8817  QualType Vector = LHSVecType ? LHSType : RHSType;
8818  unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8819  Diag(Loc,
8820  diag::err_typecheck_vector_not_convertable_implict_truncation)
8821  << ScalarOrVector << Scalar << Vector;
8822 
8823  return QualType();
8824  }
8825 
8826  // Otherwise, use the generic diagnostic.
8827  Diag(Loc, DiagID)
8828  << LHSType << RHSType
8829  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8830  return QualType();
8831 }
8832 
8833 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8834 // expression. These are mainly cases where the null pointer is used as an
8835 // integer instead of a pointer.
8836 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8837  SourceLocation Loc, bool IsCompare) {
8838  // The canonical way to check for a GNU null is with isNullPointerConstant,
8839  // but we use a bit of a hack here for speed; this is a relatively
8840  // hot path, and isNullPointerConstant is slow.
8841  bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8842  bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8843 
8844  QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8845 
8846  // Avoid analyzing cases where the result will either be invalid (and
8847  // diagnosed as such) or entirely valid and not something to warn about.
8848  if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8849  NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8850  return;
8851 
8852  // Comparison operations would not make sense with a null pointer no matter
8853  // what the other expression is.
8854  if (!IsCompare) {
8855  S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8856  << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8857  << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8858  return;
8859  }
8860 
8861  // The rest of the operations only make sense with a null pointer
8862  // if the other expression is a pointer.
8863  if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8864  NonNullType->canDecayToPointerType())
8865  return;
8866 
8867  S.Diag(Loc, diag::warn_null_in_comparison_operation)
8868  << LHSNull /* LHS is NULL */ << NonNullType
8869  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8870 }
8871 
8872 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
8873  SourceLocation Loc) {
8874  const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
8875  const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
8876  if (!LUE || !RUE)
8877  return;
8878  if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
8879  RUE->getKind() != UETT_SizeOf)
8880  return;
8881 
8882  QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
8883  QualType RHSTy;
8884 
8885  if (RUE->isArgumentType())
8886  RHSTy = RUE->getArgumentType();
8887  else
8888  RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
8889 
8890  if (!LHSTy->isPointerType() || RHSTy->isPointerType())
8891  return;
8892  if (LHSTy->getPointeeType() != RHSTy)
8893  return;
8894 
8895  S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
8896 }
8897 
8899  ExprResult &RHS,
8900  SourceLocation Loc, bool IsDiv) {
8901  // Check for division/remainder by zero.
8902  Expr::EvalResult RHSValue;
8903  if (!RHS.get()->isValueDependent() &&
8904  RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
8905  RHSValue.Val.getInt() == 0)
8906  S.DiagRuntimeBehavior(Loc, RHS.get(),
8907  S.PDiag(diag::warn_remainder_division_by_zero)
8908  << IsDiv << RHS.get()->getSourceRange());
8909 }
8910 
8912  SourceLocation Loc,
8913  bool IsCompAssign, bool IsDiv) {
8914  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8915 
8916  if (LHS.get()->getType()->isVectorType() ||
8917  RHS.get()->getType()->isVectorType())
8918  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8919  /*AllowBothBool*/getLangOpts().AltiVec,
8920  /*AllowBoolConversions*/false);
8921 
8922  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8923  if (LHS.isInvalid() || RHS.isInvalid())
8924  return QualType();
8925 
8926 
8927  if (compType.isNull() || !compType->isArithmeticType())
8928  return InvalidOperands(Loc, LHS, RHS);
8929  if (IsDiv) {
8930  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8931  DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
8932  }
8933  return compType;
8934 }
8935 
8937  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8938  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8939 
8940  if (LHS.get()->getType()->isVectorType() ||
8941  RHS.get()->getType()->isVectorType()) {
8942  if (LHS.get()->getType()->hasIntegerRepresentation() &&
8943  RHS.get()->getType()->hasIntegerRepresentation())
8944  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8945  /*AllowBothBool*/getLangOpts().AltiVec,
8946  /*AllowBoolConversions*/false);
8947  return InvalidOperands(Loc, LHS, RHS);
8948  }
8949 
8950  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8951  if (LHS.isInvalid() || RHS.isInvalid())
8952  return QualType();
8953 
8954  if (compType.isNull() || !compType->isIntegerType())
8955  return InvalidOperands(Loc, LHS, RHS);
8956  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8957  return compType;
8958 }
8959 
8960 /// Diagnose invalid arithmetic on two void pointers.
8962  Expr *LHSExpr, Expr *RHSExpr) {
8963  S.Diag(Loc, S.getLangOpts().CPlusPlus
8964  ? diag::err_typecheck_pointer_arith_void_type
8965  : diag::ext_gnu_void_ptr)
8966  << 1 /* two pointers */ << LHSExpr->getSourceRange()
8967  << RHSExpr->getSourceRange();
8968 }
8969 
8970 /// Diagnose invalid arithmetic on a void pointer.
8972  Expr *Pointer) {
8973  S.Diag(Loc, S.getLangOpts().CPlusPlus
8974  ? diag::err_typecheck_pointer_arith_void_type
8975  : diag::ext_gnu_void_ptr)
8976  << 0 /* one pointer */ << Pointer->getSourceRange();
8977 }
8978 
8979 /// Diagnose invalid arithmetic on a null pointer.
8980 ///
8981 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8982 /// idiom, which we recognize as a GNU extension.
8983 ///
8985  Expr *Pointer, bool IsGNUIdiom) {
8986  if (IsGNUIdiom)
8987  S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8988  << Pointer->getSourceRange();
8989  else
8990  S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8991  << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8992 }
8993 
8994 /// Diagnose invalid arithmetic on two function pointers.
8996  Expr *LHS, Expr *RHS) {
8997  assert(LHS->getType()->isAnyPointerType());
8998  assert(RHS->getType()->isAnyPointerType());
8999  S.Diag(Loc, S.getLangOpts().CPlusPlus
9000  ? diag::err_typecheck_pointer_arith_function_type
9001  : diag::ext_gnu_ptr_func_arith)
9002  << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9003  // We only show the second type if it differs from the first.
9004  << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9005  RHS->getType())
9006  << RHS->getType()->getPointeeType()
9007  << LHS->getSourceRange() << RHS->getSourceRange();
9008 }
9009 
9010 /// Diagnose invalid arithmetic on a function pointer.
9012  Expr *Pointer) {
9013  assert(Pointer->getType()->isAnyPointerType());
9014  S.Diag(Loc, S.getLangOpts().CPlusPlus
9015  ? diag::err_typecheck_pointer_arith_function_type
9016  : diag::ext_gnu_ptr_func_arith)
9017  << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9018  << 0 /* one pointer, so only one type */
9019  << Pointer->getSourceRange();
9020 }
9021 
9022 /// Emit error if Operand is incomplete pointer type
9023 ///
9024 /// \returns True if pointer has incomplete type
9026  Expr *Operand) {
9027  QualType ResType = Operand->getType();
9028  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9029  ResType = ResAtomicType->getValueType();
9030 
9031  assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9032  QualType PointeeTy = ResType->getPointeeType();
9033  return S.RequireCompleteType(Loc, PointeeTy,
9034  diag::err_typecheck_arithmetic_incomplete_type,
9035  PointeeTy, Operand->getSourceRange());
9036 }
9037 
9038 /// Check the validity of an arithmetic pointer operand.
9039 ///
9040 /// If the operand has pointer type, this code will check for pointer types
9041 /// which are invalid in arithmetic operations. These will be diagnosed
9042 /// appropriately, including whether or not the use is supported as an
9043 /// extension.
9044 ///
9045 /// \returns True when the operand is valid to use (even if as an extension).
9047  Expr *Operand) {
9048  QualType ResType = Operand->getType();
9049  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9050  ResType = ResAtomicType->getValueType();
9051 
9052  if (!ResType->isAnyPointerType()) return true;
9053 
9054  QualType PointeeTy = ResType->getPointeeType();
9055  if (PointeeTy->isVoidType()) {
9056  diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9057  return !S.getLangOpts().CPlusPlus;
9058  }
9059  if (PointeeTy->isFunctionType()) {
9060  diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9061  return !S.getLangOpts().CPlusPlus;
9062  }
9063 
9064  if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9065 
9066  return true;
9067 }
9068 
9069 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9070 /// operands.
9071 ///
9072 /// This routine will diagnose any invalid arithmetic on pointer operands much
9073 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9074 /// for emitting a single diagnostic even for operations where both LHS and RHS
9075 /// are (potentially problematic) pointers.
9076 ///
9077 /// \returns True when the operand is valid to use (even if as an extension).
9079  Expr *LHSExpr, Expr *RHSExpr) {
9080  bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9081  bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9082  if (!isLHSPointer && !isRHSPointer) return true;
9083 
9084  QualType LHSPointeeTy, RHSPointeeTy;
9085  if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9086  if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9087 
9088  // if both are pointers check if operation is valid wrt address spaces
9089  if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9090  const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9091  const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9092  if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9093  S.Diag(Loc,
9094  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9095  << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9096  << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9097  return false;
9098  }
9099  }
9100 
9101  // Check for arithmetic on pointers to incomplete types.
9102  bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9103  bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9104  if (isLHSVoidPtr || isRHSVoidPtr) {
9105  if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9106  else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9107  else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9108 
9109  return !S.getLangOpts().CPlusPlus;
9110  }
9111 
9112  bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9113  bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9114  if (isLHSFuncPtr || isRHSFuncPtr) {
9115  if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9116  else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9117  RHSExpr);
9118  else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9119 
9120  return !S.getLangOpts().CPlusPlus;
9121  }
9122 
9123  if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9124  return false;
9125  if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9126  return false;
9127 
9128  return true;
9129 }
9130 
9131 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9132 /// literal.
9133 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9134  Expr *LHSExpr, Expr *RHSExpr) {
9135  StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9136  Expr* IndexExpr = RHSExpr;
9137  if (!StrExpr) {
9138  StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9139  IndexExpr = LHSExpr;
9140  }
9141 
9142  bool IsStringPlusInt = StrExpr &&
9144  if (!IsStringPlusInt || IndexExpr->isValueDependent())
9145  return;
9146 
9147  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9148  Self.Diag(OpLoc, diag::warn_string_plus_int)
9149  << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9150 
9151  // Only print a fixit for "str" + int, not for int + "str".
9152  if (IndexExpr == RHSExpr) {
9153  SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9154  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9155  << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9157  << FixItHint::CreateInsertion(EndLoc, "]");
9158  } else
9159  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9160 }
9161 
9162 /// Emit a warning when adding a char literal to a string.
9163 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9164  Expr *LHSExpr, Expr *RHSExpr) {
9165  const Expr *StringRefExpr = LHSExpr;
9166  const CharacterLiteral *CharExpr =
9167  dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9168 
9169  if (!CharExpr) {
9170  CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9171  StringRefExpr = RHSExpr;
9172  }
9173 
9174  if (!CharExpr || !StringRefExpr)
9175  return;
9176 
9177  const QualType StringType = StringRefExpr->getType();
9178 
9179  // Return if not a PointerType.
9180  if (!StringType->isAnyPointerType())
9181  return;
9182 
9183  // Return if not a CharacterType.
9184  if (!StringType->getPointeeType()->isAnyCharacterType())
9185  return;
9186 
9187  ASTContext &Ctx = Self.getASTContext();
9188  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9189 
9190  const QualType CharType = CharExpr->getType();
9191  if (!CharType->isAnyCharacterType() &&
9192  CharType->isIntegerType() &&
9193  llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9194  Self.Diag(OpLoc, diag::warn_string_plus_char)
9195  << DiagRange << Ctx.CharTy;
9196  } else {
9197  Self.Diag(OpLoc, diag::warn_string_plus_char)
9198  << DiagRange << CharExpr->getType();
9199  }
9200 
9201  // Only print a fixit for str + char, not for char + str.
9202  if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9203  SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9204  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9205  << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9207  << FixItHint::CreateInsertion(EndLoc, "]");
9208  } else {
9209  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9210  }
9211 }
9212 
9213 /// Emit error when two pointers are incompatible.
9215  Expr *LHSExpr, Expr *RHSExpr) {
9216  assert(LHSExpr->getType()->isAnyPointerType());
9217  assert(RHSExpr->getType()->isAnyPointerType());
9218  S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9219  << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9220  << RHSExpr->getSourceRange();
9221 }
9222 
9223 // C99 6.5.6
9226  QualType* CompLHSTy) {
9227  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9228 
9229  if (LHS.get()->getType()->isVectorType() ||
9230  RHS.get()->getType()->isVectorType()) {
9231  QualType compType = CheckVectorOperands(
9232  LHS, RHS, Loc, CompLHSTy,
9233  /*AllowBothBool*/getLangOpts().AltiVec,
9234  /*AllowBoolConversions*/getLangOpts().ZVector);
9235  if (CompLHSTy) *CompLHSTy = compType;
9236  return compType;
9237  }
9238 
9239  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9240  if (LHS.isInvalid() || RHS.isInvalid())
9241  return QualType();
9242 
9243  // Diagnose "string literal" '+' int and string '+' "char literal".
9244  if (Opc == BO_Add) {
9245  diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9246  diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9247  }
9248 
9249  // handle the common case first (both operands are arithmetic).
9250  if (!compType.isNull() && compType->isArithmeticType()) {
9251  if (CompLHSTy) *CompLHSTy = compType;
9252  return compType;
9253  }
9254 
9255  // Type-checking. Ultimately the pointer's going to be in PExp;
9256  // note that we bias towards the LHS being the pointer.
9257  Expr *PExp = LHS.get(), *IExp = RHS.get();
9258 
9259  bool isObjCPointer;
9260  if (PExp->getType()->isPointerType()) {
9261  isObjCPointer = false;
9262  } else if (PExp->getType()->isObjCObjectPointerType()) {
9263  isObjCPointer = true;
9264  } else {
9265  std::swap(PExp, IExp);
9266  if (PExp->getType()->isPointerType()) {
9267  isObjCPointer = false;
9268  } else if (PExp->getType()->isObjCObjectPointerType()) {
9269  isObjCPointer = true;
9270  } else {
9271  return InvalidOperands(Loc, LHS, RHS);
9272  }
9273  }
9274  assert(PExp->getType()->isAnyPointerType());
9275 
9276  if (!IExp->getType()->isIntegerType())
9277  return InvalidOperands(Loc, LHS, RHS);
9278 
9279  // Adding to a null pointer results in undefined behavior.
9282  // In C++ adding zero to a null pointer is defined.
9283  Expr::EvalResult KnownVal;
9284  if (!getLangOpts().CPlusPlus ||
9285  (!IExp->isValueDependent() &&
9286  (!IExp->EvaluateAsInt(KnownVal, Context) ||
9287  KnownVal.Val.getInt() != 0))) {
9288  // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9290  Context, BO_Add, PExp, IExp);
9291  diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9292  }
9293  }
9294 
9295  if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9296  return QualType();
9297 
9298  if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9299  return QualType();
9300 
9301  // Check array bounds for pointer arithemtic
9302  CheckArrayAccess(PExp, IExp);
9303 
9304  if (CompLHSTy) {
9305  QualType LHSTy = Context.isPromotableBitField(LHS.get());
9306  if (LHSTy.isNull()) {
9307  LHSTy = LHS.get()->getType();
9308  if (LHSTy->isPromotableIntegerType())
9309  LHSTy = Context.getPromotedIntegerType(LHSTy);
9310  }
9311  *CompLHSTy = LHSTy;
9312  }
9313 
9314  return PExp->getType();
9315 }
9316 
9317 // C99 6.5.6
9319  SourceLocation Loc,
9320  QualType* CompLHSTy) {
9321  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9322 
9323  if (LHS.get()->getType()->isVectorType() ||
9324  RHS.get()->getType()->isVectorType()) {
9325  QualType compType = CheckVectorOperands(
9326  LHS, RHS, Loc, CompLHSTy,
9327  /*AllowBothBool*/getLangOpts().AltiVec,
9328  /*AllowBoolConversions*/getLangOpts().ZVector);
9329  if (CompLHSTy) *CompLHSTy = compType;
9330  return compType;
9331  }
9332 
9333  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9334  if (LHS.isInvalid() || RHS.isInvalid())
9335  return QualType();
9336 
9337  // Enforce type constraints: C99 6.5.6p3.
9338 
9339  // Handle the common case first (both operands are arithmetic).
9340  if (!compType.isNull() && compType->isArithmeticType()) {
9341  if (CompLHSTy) *CompLHSTy = compType;
9342  return compType;
9343  }
9344 
9345  // Either ptr - int or ptr - ptr.
9346  if (LHS.get()->getType()->isAnyPointerType()) {
9347  QualType lpointee = LHS.get()->getType()->getPointeeType();
9348 
9349  // Diagnose bad cases where we step over interface counts.
9350  if (LHS.get()->getType()->isObjCObjectPointerType() &&
9351  checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9352  return QualType();
9353 
9354  // The result type of a pointer-int computation is the pointer type.
9355  if (RHS.get()->getType()->isIntegerType()) {
9356  // Subtracting from a null pointer should produce a warning.
9357  // The last argument to the diagnose call says this doesn't match the
9358  // GNU int-to-pointer idiom.
9359  if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9361  // In C++ adding zero to a null pointer is defined.
9362  Expr::EvalResult KnownVal;
9363  if (!getLangOpts().CPlusPlus ||
9364  (!RHS.get()->isValueDependent() &&
9365  (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9366  KnownVal.Val.getInt() != 0))) {
9367  diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9368  }
9369  }
9370 
9371  if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9372  return QualType();
9373 
9374  // Check array bounds for pointer arithemtic
9375  CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9376  /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9377 
9378  if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9379  return LHS.get()->getType();
9380  }
9381 
9382  // Handle pointer-pointer subtractions.
9383  if (const PointerType *RHSPTy
9384  = RHS.get()->getType()->getAs<PointerType>()) {
9385  QualType rpointee = RHSPTy->getPointeeType();
9386 
9387  if (getLangOpts().CPlusPlus) {
9388  // Pointee types must be the same: C++ [expr.add]
9389  if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9390  diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9391  }
9392  } else {
9393  // Pointee types must be compatible C99 6.5.6p3
9394  if (!Context.typesAreCompatible(
9395  Context.getCanonicalType(lpointee).getUnqualifiedType(),
9396  Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9397  diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9398  return QualType();
9399  }
9400  }
9401 
9402  if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9403  LHS.get(), RHS.get()))
9404  return QualType();
9405 
9406  // FIXME: Add warnings for nullptr - ptr.
9407 
9408  // The pointee type may have zero size. As an extension, a structure or
9409  // union may have zero size or an array may have zero length. In this
9410  // case subtraction does not make sense.
9411  if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9412  CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9413  if (ElementSize.isZero()) {
9414  Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9415  << rpointee.getUnqualifiedType()
9416  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9417  }
9418  }
9419 
9420  if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9421  return Context.getPointerDiffType();
9422  }
9423  }
9424 
9425  return InvalidOperands(Loc, LHS, RHS);
9426 }
9427 
9429  if (const EnumType *ET = T->getAs<EnumType>())
9430  return ET->getDecl()->isScoped();
9431  return false;
9432 }
9433 
9436  QualType LHSType) {
9437  // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9438  // so skip remaining warnings as we don't want to modify values within Sema.
9439  if (S.getLangOpts().OpenCL)
9440  return;
9441 
9442  // Check right/shifter operand
9443  Expr::EvalResult RHSResult;
9444  if (RHS.get()->isValueDependent() ||
9445  !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9446  return;
9447  llvm::APSInt Right = RHSResult.Val.getInt();
9448 
9449  if (Right.isNegative()) {
9450  S.DiagRuntimeBehavior(Loc, RHS.get(),
9451  S.PDiag(diag::warn_shift_negative)
9452  << RHS.get()->getSourceRange());
9453  return;
9454  }
9455  llvm::APInt LeftBits(Right.getBitWidth(),
9456  S.Context.getTypeSize(LHS.get()->getType()));
9457  if (Right.uge(LeftBits)) {
9458  S.DiagRuntimeBehavior(Loc, RHS.get(),
9459  S.PDiag(diag::warn_shift_gt_typewidth)
9460  << RHS.get()->getSourceRange());
9461  return;
9462  }
9463  if (Opc != BO_Shl)
9464  return;
9465 
9466  // When left shifting an ICE which is signed, we can check for overflow which
9467  // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9468  // integers have defined behavior modulo one more than the maximum value
9469  // representable in the result type, so never warn for those.
9470  Expr::EvalResult LHSResult;
9471  if (LHS.get()->isValueDependent() ||
9472  LHSType->hasUnsignedIntegerRepresentation() ||
9473  !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9474  return;
9475  llvm::APSInt Left = LHSResult.Val.getInt();
9476 
9477  // If LHS does not have a signed type and non-negative value
9478  // then, the behavior is undefined. Warn about it.
9479  if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9480  S.DiagRuntimeBehavior(Loc, LHS.get(),
9481  S.PDiag(diag::warn_shift_lhs_negative)
9482  << LHS.get()->getSourceRange());
9483  return;
9484  }
9485 
9486  llvm::APInt ResultBits =
9487  static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9488  if (LeftBits.uge(ResultBits))
9489  return;
9490  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9491  Result = Result.shl(Right);
9492 
9493  // Print the bit representation of the signed integer as an unsigned
9494  // hexadecimal number.
9495  SmallString<40> HexResult;
9496  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9497 
9498  // If we are only missing a sign bit, this is less likely to result in actual
9499  // bugs -- if the result is cast back to an unsigned type, it will have the
9500  // expected value. Thus we place this behind a different warning that can be
9501  // turned off separately if needed.
9502  if (LeftBits == ResultBits - 1) {
9503  S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9504  << HexResult << LHSType
9505  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9506  return;
9507  }
9508 
9509  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9510  << HexResult.str() << Result.getMinSignedBits() << LHSType
9511  << Left.getBitWidth() << LHS.get()->getSourceRange()
9512  << RHS.get()->getSourceRange();
9513 }
9514 
9515 /// Return the resulting type when a vector is shifted
9516 /// by a scalar or vector shift amount.
9518  SourceLocation Loc, bool IsCompAssign) {
9519  // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9520  if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9521  !LHS.get()->getType()->isVectorType()) {
9522  S.Diag(Loc, diag::err_shift_rhs_only_vector)
9523  << RHS.get()->getType() << LHS.get()->getType()
9524  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9525  return QualType();
9526  }
9527 
9528  if (!IsCompAssign) {
9529  LHS = S.UsualUnaryConversions(LHS.get());
9530  if (LHS.isInvalid()) return QualType();
9531  }
9532 
9533  RHS = S.UsualUnaryConversions(RHS.get());
9534  if (RHS.isInvalid()) return QualType();
9535 
9536  QualType LHSType = LHS.get()->getType();
9537  // Note that LHS might be a scalar because the routine calls not only in
9538  // OpenCL case.
9539  const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9540  QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9541 
9542  // Note that RHS might not be a vector.
9543  QualType RHSType = RHS.get()->getType();
9544  const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9545  QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9546 
9547  // The operands need to be integers.
9548  if (!LHSEleType->isIntegerType()) {
9549  S.Diag(Loc, diag::err_typecheck_expect_int)
9550  << LHS.get()->getType() << LHS.get()->getSourceRange();
9551  return QualType();
9552  }
9553 
9554  if (!RHSEleType->isIntegerType()) {
9555  S.Diag(Loc, diag::err_typecheck_expect_int)
9556  << RHS.get()->getType() << RHS.get()->getSourceRange();
9557  return QualType();
9558  }
9559 
9560  if (!LHSVecTy) {
9561  assert(RHSVecTy);
9562  if (IsCompAssign)
9563  return RHSType;
9564  if (LHSEleType != RHSEleType) {
9565  LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9566  LHSEleType = RHSEleType;
9567  }
9568  QualType VecTy =
9569  S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9570  LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9571  LHSType = VecTy;
9572  } else if (RHSVecTy) {
9573  // OpenCL v1.1 s6.3.j says that for vector types, the operators
9574  // are applied component-wise. So if RHS is a vector, then ensure
9575  // that the number of elements is the same as LHS...
9576  if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9577  S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9578  << LHS.get()->getType() << RHS.get()->getType()
9579  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9580  return QualType();
9581  }
9582  if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9583  const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9584  const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9585  if (LHSBT != RHSBT &&
9586  S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9587  S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9588  << LHS.get()->getType() << RHS.get()->getType()
9589  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9590  }
9591  }
9592  } else {
9593  // ...else expand RHS to match the number of elements in LHS.
9594  QualType VecTy =
9595  S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9596  RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9597  }
9598 
9599  return LHSType;
9600 }
9601 
9602 // C99 6.5.7
9605  bool IsCompAssign) {
9606  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9607 
9608  // Vector shifts promote their scalar inputs to vector type.
9609  if (LHS.get()->getType()->isVectorType() ||
9610  RHS.get()->getType()->isVectorType()) {
9611  if (LangOpts.ZVector) {
9612  // The shift operators for the z vector extensions work basically
9613  // like general shifts, except that neither the LHS nor the RHS is
9614  // allowed to be a "vector bool".
9615  if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9616  if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9617  return InvalidOperands(Loc, LHS, RHS);
9618  if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9619  if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9620  return InvalidOperands(Loc, LHS, RHS);
9621  }
9622  return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9623  }
9624 
9625  // Shifts don't perform usual arithmetic conversions, they just do integer
9626  // promotions on each operand. C99 6.5.7p3
9627 
9628  // For the LHS, do usual unary conversions, but then reset them away
9629  // if this is a compound assignment.
9630  ExprResult OldLHS = LHS;
9631  LHS = UsualUnaryConversions(LHS.get());
9632  if (LHS.isInvalid())
9633  return QualType();
9634  QualType LHSType = LHS.get()->getType();
9635  if (IsCompAssign) LHS = OldLHS;
9636 
9637  // The RHS is simpler.
9638  RHS = UsualUnaryConversions(RHS.get());
9639  if (RHS.isInvalid())
9640  return QualType();
9641  QualType RHSType = RHS.get()->getType();
9642 
9643  // C99 6.5.7p2: Each of the operands shall have integer type.
9644  if (!LHSType->hasIntegerRepresentation() ||
9645  !RHSType->hasIntegerRepresentation())
9646  return InvalidOperands(Loc, LHS, RHS);
9647 
9648  // C++0x: Don't allow scoped enums. FIXME: Use something better than
9649  // hasIntegerRepresentation() above instead of this.
9650  if (isScopedEnumerationType(LHSType) ||
9651  isScopedEnumerationType(RHSType)) {
9652  return InvalidOperands(Loc, LHS, RHS);
9653  }
9654  // Sanity-check shift operands
9655  DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9656 
9657  // "The type of the result is that of the promoted left operand."
9658  return LHSType;
9659 }
9660 
9661 /// If two different enums are compared, raise a warning.
9662 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9663  Expr *RHS) {
9664  QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9665  QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9666 
9667  const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9668  if (!LHSEnumType)
9669  return;
9670  const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9671  if (!RHSEnumType)
9672  return;
9673 
9674  // Ignore anonymous enums.
9675  if (!LHSEnumType->getDecl()->getIdentifier() &&
9676  !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9677  return;
9678  if (!RHSEnumType->getDecl()->getIdentifier() &&
9679  !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9680  return;
9681 
9682  if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9683  return;
9684 
9685  S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9686  << LHSStrippedType << RHSStrippedType
9687  << LHS->getSourceRange() << RHS->getSourceRange();
9688 }
9689 
9690 /// Diagnose bad pointer comparisons.
9692  ExprResult &LHS, ExprResult &RHS,
9693  bool IsError) {
9694  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9695  : diag::ext_typecheck_comparison_of_distinct_pointers)
9696  << LHS.get()->getType() << RHS.get()->getType()
9697  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9698 }
9699 
9700 /// Returns false if the pointers are converted to a composite type,
9701 /// true otherwise.
9703  ExprResult &LHS, ExprResult &RHS) {
9704  // C++ [expr.rel]p2:
9705  // [...] Pointer conversions (4.10) and qualification
9706  // conversions (4.4) are performed on pointer operands (or on
9707  // a pointer operand and a null pointer constant) to bring
9708  // them to their composite pointer type. [...]
9709  //
9710  // C++ [expr.eq]p1 uses the same notion for (in)equality
9711  // comparisons of pointers.
9712 
9713  QualType LHSType = LHS.get()->getType();
9714  QualType RHSType = RHS.get()->getType();
9715  assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9716  LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9717 
9718  QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9719  if (T.isNull()) {
9720  if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9721  (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9722  diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9723  else
9724  S.InvalidOperands(Loc, LHS, RHS);
9725  return true;
9726  }
9727 
9728  LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9729  RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9730  return false;
9731 }
9732 
9734  ExprResult &LHS,
9735  ExprResult &RHS,
9736  bool IsError) {
9737  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9738  : diag::ext_typecheck_comparison_of_fptr_to_void)
9739  << LHS.get()->getType() << RHS.get()->getType()
9740  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9741 }
9742 
9744  switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9745  case Stmt::ObjCArrayLiteralClass:
9746  case Stmt::ObjCDictionaryLiteralClass:
9747  case Stmt::ObjCStringLiteralClass:
9748  case Stmt::ObjCBoxedExprClass:
9749  return true;
9750  default:
9751  // Note that ObjCBoolLiteral is NOT an object literal!
9752  return false;
9753  }
9754 }
9755 
9756 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9757  const ObjCObjectPointerType *Type =
9758  LHS->getType()->getAs<ObjCObjectPointerType>();
9759 
9760  // If this is not actually an Objective-C object, bail out.
9761  if (!Type)
9762  return false;
9763 
9764  // Get the LHS object's interface type.
9765  QualType InterfaceType = Type->getPointeeType();
9766 
9767  // If the RHS isn't an Objective-C object, bail out.
9768  if (!RHS->getType()->isObjCObjectPointerType())
9769  return false;
9770 
9771  // Try to find the -isEqual: method.
9772  Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9773  ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9774  InterfaceType,
9775  /*instance=*/true);
9776  if (!Method) {
9777  if (Type->isObjCIdType()) {
9778  // For 'id', just check the global pool.
9779  Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9780  /*receiverId=*/true);
9781  } else {
9782  // Check protocols.
9783  Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9784  /*instance=*/true);
9785  }
9786  }
9787 
9788  if (!Method)
9789  return false;
9790 
9791  QualType T = Method->parameters()[0]->getType();
9792  if (!T->isObjCObjectPointerType())
9793  return false;
9794 
9795  QualType R = Method->getReturnType();
9796  if (!R->isScalarType())
9797  return false;
9798 
9799  return true;
9800 }
9801 
9803  FromE = FromE->IgnoreParenImpCasts();
9804  switch (FromE->getStmtClass()) {
9805  default:
9806  break;
9807  case Stmt::ObjCStringLiteralClass:
9808  // "string literal"
9809  return LK_String;
9810  case Stmt::ObjCArrayLiteralClass:
9811  // "array literal"
9812  return LK_Array;
9813  case Stmt::ObjCDictionaryLiteralClass:
9814  // "dictionary literal"
9815  return LK_Dictionary;
9816  case Stmt::BlockExprClass:
9817  return LK_Block;
9818  case Stmt::ObjCBoxedExprClass: {
9819  Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9820  switch (Inner->getStmtClass()) {
9821  case Stmt::IntegerLiteralClass:
9822  case Stmt::FloatingLiteralClass:
9823  case Stmt::CharacterLiteralClass:
9824  case Stmt::ObjCBoolLiteralExprClass:
9825  case Stmt::CXXBoolLiteralExprClass:
9826  // "numeric literal"
9827  return LK_Numeric;
9828  case Stmt::ImplicitCastExprClass: {
9829  CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9830  // Boolean literals can be represented by implicit casts.
9831  if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9832  return LK_Numeric;
9833  break;
9834  }
9835  default:
9836  break;
9837  }
9838  return LK_Boxed;
9839  }
9840  }
9841  return LK_None;
9842 }
9843 
9845  ExprResult &LHS, ExprResult &RHS,
9847  Expr *Literal;
9848  Expr *Other;
9849  if (isObjCObjectLiteral(LHS)) {
9850  Literal = LHS.get();
9851  Other = RHS.get();
9852  } else {
9853  Literal = RHS.get();
9854  Other = LHS.get();
9855  }
9856 
9857  // Don't warn on comparisons against nil.
9858  Other = Other->IgnoreParenCasts();
9859  if (Other->isNullPointerConstant(S.getASTContext(),
9861  return;
9862 
9863  // This should be kept in sync with warn_objc_literal_comparison.
9864  // LK_String should always be after the other literals, since it has its own
9865  // warning flag.
9866  Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9867  assert(LiteralKind != Sema::LK_Block);
9868  if (LiteralKind == Sema::LK_None) {
9869  llvm_unreachable("Unknown Objective-C object literal kind");
9870  }
9871 
9872  if (LiteralKind == Sema::LK_String)
9873  S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9874  << Literal->getSourceRange();
9875  else
9876  S.Diag(Loc, diag::warn_objc_literal_comparison)
9877  << LiteralKind << Literal->getSourceRange();
9878 
9879  if (BinaryOperator::isEqualityOp(Opc) &&
9880  hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9881  SourceLocation Start = LHS.get()->getBeginLoc();
9882  SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
9883  CharSourceRange OpRange =
9885 
9886  S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9887  << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9888  << FixItHint::CreateReplacement(OpRange, " isEqual:")
9889  << FixItHint::CreateInsertion(End, "]");
9890  }
9891 }
9892 
9893 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9895  ExprResult &RHS, SourceLocation Loc,
9896  BinaryOperatorKind Opc) {
9897  // Check that left hand side is !something.
9898  UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9899  if (!UO || UO->getOpcode() != UO_LNot) return;
9900 
9901  // Only check if the right hand side is non-bool arithmetic type.
9902  if (RHS.get()->isKnownToHaveBooleanValue()) return;
9903 
9904  // Make sure that the something in !something is not bool.
9905  Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9906  if (SubExpr->isKnownToHaveBooleanValue()) return;
9907 
9908  // Emit warning.
9909  bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9910  S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9911  << Loc << IsBitwiseOp;
9912 
9913  // First note suggest !(x < y)
9914  SourceLocation FirstOpen = SubExpr->getBeginLoc();
9915  SourceLocation FirstClose = RHS.get()->getEndLoc();
9916  FirstClose = S.getLocForEndOfToken(FirstClose);
9917  if (FirstClose.isInvalid())
9918  FirstOpen = SourceLocation();
9919  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9920  << IsBitwiseOp
9921  << FixItHint::CreateInsertion(FirstOpen, "(")
9922  << FixItHint::CreateInsertion(FirstClose, ")");
9923 
9924  // Second note suggests (!x) < y
9925  SourceLocation SecondOpen = LHS.get()->getBeginLoc();
9926  SourceLocation SecondClose = LHS.get()->getEndLoc();
9927  SecondClose = S.getLocForEndOfToken(SecondClose);
9928  if (SecondClose.isInvalid())
9929  SecondOpen = SourceLocation();
9930  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9931  << FixItHint::CreateInsertion(SecondOpen, "(")
9932  << FixItHint::CreateInsertion(SecondClose, ")");
9933 }
9934 
9935 // Get the decl for a simple expression: a reference to a variable,
9936 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9938  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9939  return DR->getDecl();
9940  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9941  if (Ivar->isFreeIvar())
9942  return Ivar->getDecl();
9943  }
9944  if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9945  if (Mem->isImplicitAccess())
9946  return Mem->getMemberDecl();
9947  }
9948  return nullptr;
9949 }
9950 
9951 /// Diagnose some forms of syntactically-obvious tautological comparison.
9953  Expr *LHS, Expr *RHS,
9954  BinaryOperatorKind Opc) {
9955  Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9956  Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9957 
9958  QualType LHSType = LHS->getType();
9959  QualType RHSType = RHS->getType();
9960  if (LHSType->hasFloatingRepresentation() ||
9961  (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9962  LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
9964  return;
9965 
9966  // Comparisons between two array types are ill-formed for operator<=>, so
9967  // we shouldn't emit any additional warnings about it.
9968  if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9969  return;
9970 
9971  // For non-floating point types, check for self-comparisons of the form
9972  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9973  // often indicate logic errors in the program.
9974  //
9975  // NOTE: Don't warn about comparison expressions resulting from macro
9976  // expansion. Also don't warn about comparisons which are only self
9977  // comparisons within a template instantiation. The warnings should catch
9978  // obvious cases in the definition of the template anyways. The idea is to
9979  // warn when the typed comparison operator will always evaluate to the same
9980  // result.
9981  ValueDecl *DL = getCompareDecl(LHSStripped);
9982  ValueDecl *DR = getCompareDecl(RHSStripped);
9983  if (DL && DR && declaresSameEntity(DL, DR)) {
9984  StringRef Result;
9985  switch (Opc) {
9986  case BO_EQ: case BO_LE: case BO_GE:
9987  Result = "true";
9988  break;
9989  case BO_NE: case BO_LT: case BO_GT:
9990  Result = "false";
9991  break;
9992  case BO_Cmp:
9993  Result = "'std::strong_ordering::equal'";
9994  break;
9995  default:
9996  break;
9997  }
9998  S.DiagRuntimeBehavior(Loc, nullptr,
9999  S.PDiag(diag::warn_comparison_always)
10000  << 0 /*self-comparison*/ << !Result.empty()
10001  << Result);
10002  } else if (DL && DR &&
10003  DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10004  !DL->isWeak() && !DR->isWeak()) {
10005  // What is it always going to evaluate to?
10006  StringRef Result;
10007  switch(Opc) {
10008  case BO_EQ: // e.g. array1 == array2
10009  Result = "false";
10010  break;
10011  case BO_NE: // e.g. array1 != array2
10012  Result = "true";
10013  break;
10014  default: // e.g. array1 <= array2
10015  // The best we can say is 'a constant'
10016  break;
10017  }
10018  S.DiagRuntimeBehavior(Loc, nullptr,
10019  S.PDiag(diag::warn_comparison_always)
10020  << 1 /*array comparison*/
10021  << !Result.empty() << Result);
10022  }
10023 
10024  if (isa<CastExpr>(LHSStripped))
10025  LHSStripped = LHSStripped->IgnoreParenCasts();
10026  if (isa<CastExpr>(RHSStripped))
10027  RHSStripped = RHSStripped->IgnoreParenCasts();
10028 
10029  // Warn about comparisons against a string constant (unless the other
10030  // operand is null); the user probably wants strcmp.
10031  Expr *LiteralString = nullptr;
10032  Expr *LiteralStringStripped = nullptr;
10033  if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10034  !RHSStripped->isNullPointerConstant(S.Context,
10036  LiteralString = LHS;
10037  LiteralStringStripped = LHSStripped;
10038  } else if ((isa<StringLiteral>(RHSStripped) ||
10039  isa<ObjCEncodeExpr>(RHSStripped)) &&
10040  !LHSStripped->isNullPointerConstant(S.Context,
10042  LiteralString = RHS;
10043  LiteralStringStripped = RHSStripped;
10044  }
10045 
10046  if (LiteralString) {
10047  S.DiagRuntimeBehavior(Loc, nullptr,
10048  S.PDiag(diag::warn_stringcompare)
10049  << isa<ObjCEncodeExpr>(LiteralStringStripped)
10050  << LiteralString->getSourceRange());
10051  }
10052 }
10053 
10055  switch (CK) {
10056  default: {
10057 #ifndef NDEBUG
10058  llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10059  << "\n";
10060 #endif
10061  llvm_unreachable("unhandled cast kind");
10062  }
10063  case CK_UserDefinedConversion:
10064  return ICK_Identity;
10065  case CK_LValueToRValue:
10066  return ICK_Lvalue_To_Rvalue;
10067  case CK_ArrayToPointerDecay:
10068  return ICK_Array_To_Pointer;
10069  case CK_FunctionToPointerDecay:
10070  return ICK_Function_To_Pointer;
10071  case CK_IntegralCast:
10072  return ICK_Integral_Conversion;
10073  case CK_FloatingCast:
10074  return ICK_Floating_Conversion;
10075  case CK_IntegralToFloating:
10076  case CK_FloatingToIntegral:
10077  return ICK_Floating_Integral;
10078  case CK_IntegralComplexCast:
10079  case CK_FloatingComplexCast:
10080  case CK_FloatingComplexToIntegralComplex:
10081  case CK_IntegralComplexToFloatingComplex:
10082  return ICK_Complex_Conversion;
10083  case CK_FloatingComplexToReal:
10084  case CK_FloatingRealToComplex:
10085  case CK_IntegralComplexToReal:
10086  case CK_IntegralRealToComplex:
10087  return ICK_Complex_Real;
10088  }
10089 }
10090 
10092  QualType FromType,
10093  SourceLocation Loc) {
10094  // Check for a narrowing implicit conversion.
10097  SCS.setToType(0, FromType);
10098  SCS.setToType(1, ToType);
10099  if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10100  SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10101 
10102  APValue PreNarrowingValue;
10103  QualType PreNarrowingType;
10104  switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10105  PreNarrowingType,
10106  /*IgnoreFloatToIntegralConversion*/ true)) {
10108  // Implicit conversion to a narrower type, but the expression is
10109  // value-dependent so we can't tell whether it's actually narrowing.
10110  case NK_Not_Narrowing:
10111  return false;
10112 
10113  case NK_Constant_Narrowing:
10114  // Implicit conversion to a narrower type, and the value is not a constant
10115  // expression.
10116  S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10117  << /*Constant*/ 1
10118  << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10119  return true;
10120 
10121  case NK_Variable_Narrowing:
10122  // Implicit conversion to a narrower type, and the value is not a constant
10123  // expression.
10124  case NK_Type_Narrowing:
10125  S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10126  << /*Constant*/ 0 << FromType << ToType;
10127  // TODO: It's not a constant expression, but what if the user intended it
10128  // to be? Can we produce notes to help them figure out why it isn't?
10129  return true;
10130  }
10131  llvm_unreachable("unhandled case in switch");
10132 }
10133 
10135  ExprResult &LHS,
10136  ExprResult &RHS,
10137  SourceLocation Loc) {
10138  using CCT = ComparisonCategoryType;
10139 
10140  QualType LHSType = LHS.get()->getType();
10141  QualType RHSType = RHS.get()->getType();
10142  // Dig out the original argument type and expression before implicit casts
10143  // were applied. These are the types/expressions we need to check the
10144  // [expr.spaceship] requirements against.
10145  ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10146  ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10147  QualType LHSStrippedType = LHSStripped.get()->getType();
10148  QualType RHSStrippedType = RHSStripped.get()->getType();
10149 
10150  // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10151  // other is not, the program is ill-formed.
10152  if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10153  S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10154  return QualType();
10155  }
10156 
10157  int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10158  RHSStrippedType->isEnumeralType();
10159  if (NumEnumArgs == 1) {
10160  bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10161  QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10162  if (OtherTy->hasFloatingRepresentation()) {
10163  S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10164  return QualType();
10165  }
10166  }
10167  if (NumEnumArgs == 2) {
10168  // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10169  // type E, the operator yields the result of converting the operands
10170  // to the underlying type of E and applying <=> to the converted operands.
10171  if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10172  S.InvalidOperands(Loc, LHS, RHS);
10173  return QualType();
10174  }
10175  QualType IntType =
10176  LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10177  assert(IntType->isArithmeticType());
10178 
10179  // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10180  // promote the boolean type, and all other promotable integer types, to
10181  // avoid this.
10182  if (IntType->isPromotableIntegerType())
10183  IntType = S.Context.getPromotedIntegerType(IntType);
10184 
10185  LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10186  RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10187  LHSType = RHSType = IntType;
10188  }
10189 
10190  // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10191  // usual arithmetic conversions are applied to the operands.
10193  if (LHS.isInvalid() || RHS.isInvalid())
10194  return QualType();
10195  if (Type.isNull())
10196  return S.InvalidOperands(Loc, LHS, RHS);
10197  assert(Type->isArithmeticType() || Type->isEnumeralType());
10198 
10199  bool HasNarrowing = checkThreeWayNarrowingConversion(
10200  S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10201  HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10202  RHS.get()->getBeginLoc());
10203  if (HasNarrowing)
10204  return QualType();
10205 
10206  assert(!Type.isNull() && "composite type for <=> has not been set");
10207 
10208  auto TypeKind = [&]() {
10209  if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10210  if (CT->getElementType()->hasFloatingRepresentation())
10211  return CCT::WeakEquality;
10212  return CCT::StrongEquality;
10213  }
10214  if (Type->isIntegralOrEnumerationType())
10215  return CCT::StrongOrdering;
10216  if (Type->hasFloatingRepresentation())
10217  return CCT::PartialOrdering;
10218  llvm_unreachable("other types are unimplemented");
10219  }();
10220 
10221  return S.CheckComparisonCategoryType(TypeKind, Loc);
10222 }
10223 
10225  ExprResult &RHS,
10226  SourceLocation Loc,
10227  BinaryOperatorKind Opc) {
10228  if (Opc == BO_Cmp)
10229  return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10230 
10231  // C99 6.5.8p3 / C99 6.5.9p4
10233  if (LHS.isInvalid() || RHS.isInvalid())
10234  return QualType();
10235  if (Type.isNull())
10236  return S.InvalidOperands(Loc, LHS, RHS);
10237  assert(Type->isArithmeticType() || Type->isEnumeralType());
10238 
10239  checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10240 
10242  return S.InvalidOperands(Loc, LHS, RHS);
10243 
10244  // Check for comparisons of floating point operands using != and ==.
10246  S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10247 
10248  // The result of comparisons is 'bool' in C++, 'int' in C.
10249  return S.Context.getLogicalOperationType();
10250 }
10251 
10252 // C99 6.5.8, C++ [expr.rel]
10254  SourceLocation Loc,
10255  BinaryOperatorKind Opc) {
10256  bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10257  bool IsThreeWay = Opc == BO_Cmp;
10258  auto IsAnyPointerType = [](ExprResult E) {
10259  QualType Ty = E.get()->getType();
10260  return Ty->isPointerType() || Ty->isMemberPointerType();
10261  };
10262 
10263  // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10264  // type, array-to-pointer, ..., conversions are performed on both operands to
10265  // bring them to their composite type.
10266  // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10267  // any type-related checks.
10268  if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10269  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10270  if (LHS.isInvalid())
10271  return QualType();
10272  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10273  if (RHS.isInvalid())
10274  return QualType();
10275  } else {
10276  LHS = DefaultLvalueConversion(LHS.get());
10277  if (LHS.isInvalid())
10278  return QualType();
10279  RHS = DefaultLvalueConversion(RHS.get());
10280  if (RHS.isInvalid())
10281  return QualType();
10282  }
10283 
10284  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10285 
10286  // Handle vector comparisons separately.
10287  if (LHS.get()->getType()->isVectorType() ||
10288  RHS.get()->getType()->isVectorType())
10289  return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10290 
10291  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10292  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10293 
10294  QualType LHSType = LHS.get()->getType();
10295  QualType RHSType = RHS.get()->getType();
10296  if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10297  (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10298  return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10299 
10300  const Expr::NullPointerConstantKind LHSNullKind =
10301  LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10302  const Expr::NullPointerConstantKind RHSNullKind =
10303  RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10304  bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10305  bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10306 
10307  auto computeResultTy = [&]() {
10308  if (Opc != BO_Cmp)
10309  return Context.getLogicalOperationType();
10310  assert(getLangOpts().CPlusPlus);
10311  assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10312 
10313  QualType CompositeTy = LHS.get()->getType();
10314  assert(!CompositeTy->isReferenceType());
10315 
10316  auto buildResultTy = [&](ComparisonCategoryType Kind) {
10317  return CheckComparisonCategoryType(Kind, Loc);
10318  };
10319 
10320  // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10321  // pointer type, a pointer-to-member type, or std::nullptr_t, the
10322  // result is of type std::strong_equality
10323  if (CompositeTy->isFunctionPointerType() ||
10324  CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10325  // FIXME: consider making the function pointer case produce
10326  // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10327  // and direction polls
10328  return buildResultTy(ComparisonCategoryType::StrongEquality);
10329 
10330  // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10331  // pointer type, p <=> q is of type std::strong_ordering.
10332  if (CompositeTy->isPointerType()) {
10333  // P0946R0: Comparisons between a null pointer constant and an object
10334  // pointer result in std::strong_equality
10335  if (LHSIsNull != RHSIsNull)
10336  return buildResultTy(ComparisonCategoryType::StrongEquality);
10337  return buildResultTy(ComparisonCategoryType::StrongOrdering);
10338  }
10339  // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10340  // TODO: Extend support for operator<=> to ObjC types.
10341  return InvalidOperands(Loc, LHS, RHS);
10342  };
10343 
10344 
10345  if (!IsRelational && LHSIsNull != RHSIsNull) {
10346  bool IsEquality = Opc == BO_EQ;
10347  if (RHSIsNull)
10348  DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10349  RHS.get()->getSourceRange());
10350  else
10351  DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10352  LHS.get()->getSourceRange());
10353  }
10354 
10355  if ((LHSType->isIntegerType() && !LHSIsNull) ||
10356  (RHSType->isIntegerType() && !RHSIsNull)) {
10357  // Skip normal pointer conversion checks in this case; we have better
10358  // diagnostics for this below.
10359  } else if (getLangOpts().CPlusPlus) {
10360  // Equality comparison of a function pointer to a void pointer is invalid,
10361  // but we allow it as an extension.
10362  // FIXME: If we really want to allow this, should it be part of composite
10363  // pointer type computation so it works in conditionals too?
10364  if (!IsRelational &&
10365  ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10366  (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10367  // This is a gcc extension compatibility comparison.
10368  // In a SFINAE context, we treat this as a hard error to maintain
10369  // conformance with the C++ standard.
10371  *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10372 
10373  if (isSFINAEContext())
10374  return QualType();
10375 
10376  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10377  return computeResultTy();
10378  }
10379 
10380  // C++ [expr.eq]p2:
10381  // If at least one operand is a pointer [...] bring them to their
10382  // composite pointer type.
10383  // C++ [expr.spaceship]p6
10384  // If at least one of the operands is of pointer type, [...] bring them
10385  // to their composite pointer type.
10386  // C++ [expr.rel]p2:
10387  // If both operands are pointers, [...] bring them to their composite
10388  // pointer type.
10389  if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10390  (IsRelational ? 2 : 1) &&
10391  (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10392  RHSType->isObjCObjectPointerType()))) {
10393  if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10394  return QualType();
10395  return computeResultTy();
10396  }
10397  } else if (LHSType->isPointerType() &&
10398  RHSType->isPointerType()) { // C99 6.5.8p2
10399  // All of the following pointer-related warnings are GCC extensions, except
10400  // when handling null pointer constants.
10401  QualType LCanPointeeTy =
10402  LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10403  QualType RCanPointeeTy =
10404  RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10405 
10406  // C99 6.5.9p2 and C99 6.5.8p2
10407  if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10408  RCanPointeeTy.getUnqualifiedType())) {
10409  // Valid unless a relational comparison of function pointers
10410  if (IsRelational && LCanPointeeTy->isFunctionType()) {
10411  Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10412  << LHSType << RHSType << LHS.get()->getSourceRange()
10413  << RHS.get()->getSourceRange();
10414  }
10415  } else if (!IsRelational &&
10416  (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10417  // Valid unless comparison between non-null pointer and function pointer
10418  if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10419  && !LHSIsNull && !RHSIsNull)
10420  diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10421  /*isError*/false);
10422  } else {
10423  // Invalid
10424  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10425  }
10426  if (LCanPointeeTy != RCanPointeeTy) {
10427  // Treat NULL constant as a special case in OpenCL.
10428  if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10429  const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10430  if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10431  Diag(Loc,
10432  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10433  << LHSType << RHSType << 0 /* comparison */
10434  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10435  }
10436  }
10437  LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10438  LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10439  CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10440  : CK_BitCast;
10441  if (LHSIsNull && !RHSIsNull)
10442  LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10443  else
10444  RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10445  }
10446  return computeResultTy();
10447  }
10448 
10449  if (getLangOpts().CPlusPlus) {
10450  // C++ [expr.eq]p4:
10451  // Two operands of type std::nullptr_t or one operand of type
10452  // std::nullptr_t and the other a null pointer constant compare equal.
10453  if (!IsRelational && LHSIsNull && RHSIsNull) {
10454  if (LHSType->isNullPtrType()) {
10455  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10456  return computeResultTy();
10457  }
10458  if (RHSType->isNullPtrType()) {
10459  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10460  return computeResultTy();
10461  }
10462  }
10463 
10464  // Comparison of Objective-C pointers and block pointers against nullptr_t.
10465  // These aren't covered by the composite pointer type rules.
10466  if (!IsRelational && RHSType->isNullPtrType() &&
10467  (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10468  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10469  return computeResultTy();
10470  }
10471  if (!IsRelational && LHSType->isNullPtrType() &&
10472  (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10473  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10474  return computeResultTy();
10475  }
10476 
10477  if (IsRelational &&
10478  ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10479  (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10480  // HACK: Relational comparison of nullptr_t against a pointer type is
10481  // invalid per DR583, but we allow it within std::less<> and friends,
10482  // since otherwise common uses of it break.
10483  // FIXME: Consider removing this hack once LWG fixes std::less<> and
10484  // friends to have std::nullptr_t overload candidates.
10485  DeclContext *DC = CurContext;
10486  if (isa<FunctionDecl>(DC))
10487  DC = DC->getParent();
10488  if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10489  if (CTSD->isInStdNamespace() &&
10490  llvm::StringSwitch<bool>(CTSD->getName())
10491  .Cases("less", "less_equal", "greater", "greater_equal", true)
10492  .Default(false)) {
10493  if (RHSType->isNullPtrType())
10494  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10495  else
10496  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10497  return computeResultTy();
10498  }
10499  }
10500  }
10501 
10502  // C++ [expr.eq]p2:
10503  // If at least one operand is a pointer to member, [...] bring them to
10504  // their composite pointer type.
10505  if (!IsRelational &&
10506  (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10507  if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10508  return QualType();
10509  else
10510  return computeResultTy();
10511  }
10512  }
10513 
10514  // Handle block pointer types.
10515  if (!IsRelational && LHSType->isBlockPointerType() &&
10516  RHSType->isBlockPointerType()) {
10517  QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10518  QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10519 
10520  if (!LHSIsNull && !RHSIsNull &&
10521  !Context.typesAreCompatible(lpointee, rpointee)) {
10522  Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10523  << LHSType << RHSType << LHS.get()->getSourceRange()
10524  << RHS.get()->getSourceRange();
10525  }
10526  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10527  return computeResultTy();
10528  }
10529 
10530  // Allow block pointers to be compared with null pointer constants.
10531  if (!IsRelational
10532  && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10533  || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10534  if (!LHSIsNull && !RHSIsNull) {
10535  if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10536  ->getPointeeType()->isVoidType())
10537  || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10538  ->getPointeeType()->isVoidType())))
10539  Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10540  << LHSType << RHSType << LHS.get()->getSourceRange()
10541  << RHS.get()->getSourceRange();
10542  }
10543  if (LHSIsNull && !RHSIsNull)
10544  LHS = ImpCastExprToType(LHS.get(), RHSType,
10545  RHSType->isPointerType() ? CK_BitCast
10546  : CK_AnyPointerToBlockPointerCast);
10547  else
10548  RHS = ImpCastExprToType(RHS.get(), LHSType,
10549  LHSType->isPointerType() ? CK_BitCast
10550  : CK_AnyPointerToBlockPointerCast);
10551  return computeResultTy();
10552  }
10553 
10554  if (LHSType->isObjCObjectPointerType() ||
10555  RHSType->isObjCObjectPointerType()) {
10556  const PointerType *LPT = LHSType->getAs<PointerType>();
10557  const PointerType *RPT = RHSType->getAs<PointerType>();
10558  if (LPT || RPT) {
10559  bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10560  bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10561 
10562  if (!LPtrToVoid && !RPtrToVoid &&
10563  !Context.typesAreCompatible(LHSType, RHSType)) {
10564  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10565  /*isError*/false);
10566  }
10567  if (LHSIsNull && !RHSIsNull) {
10568  Expr *E = LHS.get();
10569  if (getLangOpts().ObjCAutoRefCount)
10570  CheckObjCConversion(SourceRange(), RHSType, E,
10571  CCK_ImplicitConversion);
10572  LHS = ImpCastExprToType(E, RHSType,
10573  RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10574  }
10575  else {
10576  Expr *E = RHS.get();
10577  if (getLangOpts().ObjCAutoRefCount)
10578  CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10579  /*Diagnose=*/true,
10580  /*DiagnoseCFAudited=*/false, Opc);
10581  RHS = ImpCastExprToType(E, LHSType,
10582  LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10583  }
10584  return computeResultTy();
10585  }
10586  if (LHSType->isObjCObjectPointerType() &&
10587  RHSType->isObjCObjectPointerType()) {
10588  if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10589  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10590  /*isError*/false);
10591  if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10592  diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10593 
10594  if (LHSIsNull && !RHSIsNull)
10595  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10596  else
10597  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10598  return computeResultTy();
10599  }
10600 
10601  if (!IsRelational && LHSType->isBlockPointerType() &&
10602  RHSType->isBlockCompatibleObjCPointerType(Context)) {
10603  LHS = ImpCastExprToType(LHS.get(), RHSType,
10604  CK_BlockPointerToObjCPointerCast);
10605  return computeResultTy();
10606  } else if (!IsRelational &&
10607  LHSType->isBlockCompatibleObjCPointerType(Context) &&
10608  RHSType->isBlockPointerType()) {
10609  RHS = ImpCastExprToType(RHS.get(), LHSType,
10610  CK_BlockPointerToObjCPointerCast);
10611  return computeResultTy();
10612  }
10613  }
10614  if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10615  (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10616  unsigned DiagID = 0;
10617  bool isError = false;
10618  if (LangOpts.DebuggerSupport) {
10619  // Under a debugger, allow the comparison of pointers to integers,
10620  // since users tend to want to compare addresses.
10621  } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10622  (RHSIsNull && RHSType->isIntegerType())) {
10623  if (IsRelational) {
10624  isError = getLangOpts().CPlusPlus;
10625  DiagID =
10626  isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10627  : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10628  }
10629  } else if (getLangOpts().CPlusPlus) {
10630  DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10631  isError = true;
10632  } else if (IsRelational)
10633  DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10634  else
10635  DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10636 
10637  if (DiagID) {
10638  Diag(Loc, DiagID)
10639  << LHSType << RHSType << LHS.get()->getSourceRange()
10640  << RHS.get()->getSourceRange();
10641  if (isError)
10642  return QualType();
10643  }
10644 
10645  if (LHSType->isIntegerType())
10646  LHS = ImpCastExprToType(LHS.get(), RHSType,
10647  LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10648  else
10649  RHS = ImpCastExprToType(RHS.get(), LHSType,
10650  RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10651  return computeResultTy();
10652  }
10653 
10654  // Handle block pointers.
10655  if (!IsRelational && RHSIsNull
10656  && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10657  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10658  return computeResultTy();
10659  }
10660  if (!IsRelational && LHSIsNull
10661  && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10662  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10663  return computeResultTy();
10664  }
10665 
10666  if (getLangOpts().OpenCLVersion >= 200) {
10667  if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10668  return computeResultTy();
10669  }
10670 
10671  if (LHSType->isQueueT() && RHSType->isQueueT()) {
10672  return computeResultTy();
10673  }
10674 
10675  if (LHSIsNull && RHSType->isQueueT()) {
10676  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10677  return computeResultTy();
10678  }
10679 
10680  if (LHSType->isQueueT() && RHSIsNull) {
10681  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10682  return computeResultTy();
10683  }
10684  }
10685 
10686  return InvalidOperands(Loc, LHS, RHS);
10687 }
10688 
10689 // Return a signed ext_vector_type that is of identical size and number of
10690 // elements. For floating point vectors, return an integer type of identical
10691 // size and number of elements. In the non ext_vector_type case, search from
10692 // the largest type to the smallest type to avoid cases where long long == long,
10693 // where long gets picked over long long.
10695  const VectorType *VTy = V->getAs<VectorType>();
10696  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10697 
10698  if (isa<ExtVectorType>(VTy)) {
10699  if (TypeSize == Context.getTypeSize(Context.CharTy))
10700  return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10701  else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10702  return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10703  else if (TypeSize == Context.getTypeSize(Context.IntTy))
10704  return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10705  else if (TypeSize == Context.getTypeSize(Context.LongTy))
10706  return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10707  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10708  "Unhandled vector element size in vector compare");
10709  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10710  }
10711 
10712  if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10713  return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10715  else if (TypeSize == Context.getTypeSize(Context.LongTy))
10716  return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10718  else if (TypeSize == Context.getTypeSize(Context.IntTy))
10719  return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10721  else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10722  return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10724  assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10725  "Unhandled vector element size in vector compare");
10726  return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10728 }
10729 
10730 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10731 /// operates on extended vector types. Instead of producing an IntTy result,
10732 /// like a scalar comparison, a vector comparison produces a vector of integer
10733 /// types.
10735  SourceLocation Loc,
10736  BinaryOperatorKind Opc) {
10737  // Check to make sure we're operating on vectors of the same type and width,
10738  // Allowing one side to be a scalar of element type.
10739  QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10740  /*AllowBothBool*/true,
10741  /*AllowBoolConversions*/getLangOpts().ZVector);
10742  if (vType.isNull())
10743  return vType;
10744 
10745  QualType LHSType = LHS.get()->getType();
10746 
10747  // If AltiVec, the comparison results in a numeric type, i.e.
10748  // bool for C++, int for C
10749  if (getLangOpts().AltiVec &&
10751  return Context.getLogicalOperationType();
10752 
10753  // For non-floating point types, check for self-comparisons of the form
10754  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
10755  // often indicate logic errors in the program.
10756  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10757 
10758  // Check for comparisons of floating point operands using != and ==.
10759  if (BinaryOperator::isEqualityOp(Opc) &&
10760  LHSType->hasFloatingRepresentation()) {
10761  assert(RHS.get()->getType()->hasFloatingRepresentation());
10762  CheckFloatComparison(Loc, LHS.get(), RHS.get());
10763  }
10764 
10765  // Return a signed type for the vector.
10766  return GetSignedVectorType(vType);
10767 }
10768 
10770  SourceLocation Loc) {
10771  // Ensure that either both operands are of the same vector type, or
10772  // one operand is of a vector type and the other is of its element type.
10773  QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10774  /*AllowBothBool*/true,
10775  /*AllowBoolConversions*/false);
10776  if (vType.isNull())
10777  return InvalidOperands(Loc, LHS, RHS);
10778  if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10779  vType->hasFloatingRepresentation())
10780  return InvalidOperands(Loc, LHS, RHS);
10781  // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10782  // usage of the logical operators && and || with vectors in C. This
10783  // check could be notionally dropped.
10784  if (!getLangOpts().CPlusPlus &&
10785  !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10786  return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10787 
10788  return GetSignedVectorType(LHS.get()->getType());
10789 }
10790 
10792  SourceLocation Loc,
10793  BinaryOperatorKind Opc) {
10794  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10795 
10796  bool IsCompAssign =
10797  Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10798 
10799  if (LHS.get()->getType()->isVectorType() ||
10800  RHS.get()->getType()->isVectorType()) {
10801  if (LHS.get()->getType()->hasIntegerRepresentation() &&
10802  RHS.get()->getType()->hasIntegerRepresentation())
10803  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10804  /*AllowBothBool*/true,
10805  /*AllowBoolConversions*/getLangOpts().ZVector);
10806  return InvalidOperands(Loc, LHS, RHS);
10807  }
10808 
10809  if (Opc == BO_And)
10810  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10811 
10812  ExprResult LHSResult = LHS, RHSResult = RHS;
10813  QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10814  IsCompAssign);
10815  if (LHSResult.isInvalid() || RHSResult.isInvalid())
10816  return QualType();
10817  LHS = LHSResult.get();
10818  RHS = RHSResult.get();
10819 
10820  if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10821  return compType;
10822  return InvalidOperands(Loc, LHS, RHS);
10823 }
10824 
10825 // C99 6.5.[13,14]
10827  SourceLocation Loc,
10828  BinaryOperatorKind Opc) {
10829  // Check vector operands differently.
10830  if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10831  return CheckVectorLogicalOperands(LHS, RHS, Loc);
10832 
10833  // Diagnose cases where the user write a logical and/or but probably meant a
10834  // bitwise one. We do this when the LHS is a non-bool integer and the RHS
10835  // is a constant.
10836  if (LHS.get()->getType()->isIntegerType() &&
10837  !LHS.get()->getType()->isBooleanType() &&
10838  RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10839  // Don't warn in macros or template instantiations.
10840  !Loc.isMacroID() && !inTemplateInstantiation()) {
10841  // If the RHS can be constant folded, and if it constant folds to something
10842  // that isn't 0 or 1 (which indicate a potential logical operation that
10843  // happened to fold to true/false) then warn.
10844  // Parens on the RHS are ignored.
10845  Expr::EvalResult EVResult;
10846  if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
10847  llvm::APSInt Result = EVResult.Val.getInt();
10848  if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10849  !RHS.get()->getExprLoc().isMacroID()) ||
10850  (Result != 0 && Result != 1)) {
10851  Diag(Loc, diag::warn_logical_instead_of_bitwise)
10852  << RHS.get()->getSourceRange()
10853  << (Opc == BO_LAnd ? "&&" : "||");
10854  // Suggest replacing the logical operator with the bitwise version
10855  Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10856  << (Opc == BO_LAnd ? "&" : "|")
10858  Loc, getLocForEndOfToken(Loc)),
10859  Opc == BO_LAnd ? "&" : "|");
10860  if (Opc == BO_LAnd)
10861  // Suggest replacing "Foo() && kNonZero" with "Foo()"
10862  Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10864  SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
10865  RHS.get()->getEndLoc()));
10866  }
10867  }
10868  }
10869 
10870  if (!Context.getLangOpts().CPlusPlus) {
10871  // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10872  // not operate on the built-in scalar and vector float types.
10873  if (Context.getLangOpts().OpenCL &&
10874  Context.getLangOpts().OpenCLVersion < 120) {
10875  if (LHS.get()->getType()->isFloatingType() ||
10876  RHS.get()->getType()->isFloatingType())
10877  return InvalidOperands(Loc, LHS, RHS);
10878  }
10879 
10880  LHS = UsualUnaryConversions(LHS.get());
10881  if (LHS.isInvalid())
10882  return QualType();
10883 
10884  RHS = UsualUnaryConversions(RHS.get());
10885  if (RHS.isInvalid())
10886  return QualType();
10887 
10888  if (!LHS.get()->getType()->isScalarType() ||
10889  !RHS.get()->getType()->isScalarType())
10890  return InvalidOperands(Loc, LHS, RHS);
10891 
10892  return Context.IntTy;
10893  }
10894 
10895  // The following is safe because we only use this method for
10896  // non-overloadable operands.
10897 
10898  // C++ [expr.log.and]p1
10899  // C++ [expr.log.or]p1
10900  // The operands are both contextually converted to type bool.
10901  ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10902  if (LHSRes.isInvalid())
10903  return InvalidOperands(Loc, LHS, RHS);
10904  LHS = LHSRes;
10905 
10906  ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10907  if (RHSRes.isInvalid())
10908  return InvalidOperands(Loc, LHS, RHS);
10909  RHS = RHSRes;
10910 
10911  // C++ [expr.log.and]p2
10912  // C++ [expr.log.or]p2
10913  // The result is a bool.
10914  return Context.BoolTy;
10915 }
10916 
10917 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10918  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10919  if (!ME) return false;
10920  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10921  ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10923  if (!Base) return false;
10924  return Base->getMethodDecl() != nullptr;
10925 }
10926 
10927 /// Is the given expression (which must be 'const') a reference to a
10928 /// variable which was originally non-const, but which has become
10929 /// 'const' due to being captured within a block?
10932  assert(E->isLValue() && E->getType().isConstQualified());
10933  E = E->IgnoreParens();
10934 
10935  // Must be a reference to a declaration from an enclosing scope.
10936  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10937  if (!DRE) return NCCK_None;
10938  if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10939 
10940  // The declaration must be a variable which is not declared 'const'.
10941  VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10942  if (!var) return NCCK_None;
10943  if (var->getType().isConstQualified()) return NCCK_None;
10944  assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10945 
10946  // Decide whether the first capture was for a block or a lambda.
10947  DeclContext *DC = S.CurContext, *Prev = nullptr;
10948  // Decide whether the first capture was for a block or a lambda.
10949  while (DC) {
10950  // For init-capture, it is possible that the variable belongs to the
10951  // template pattern of the current context.
10952  if (auto *FD = dyn_cast<FunctionDecl>(DC))
10953  if (var->isInitCapture() &&
10954  FD->getTemplateInstantiationPattern() == var->getDeclContext())
10955  break;
10956  if (DC == var->getDeclContext())
10957  break;
10958  Prev = DC;
10959  DC = DC->getParent();
10960  }
10961  // Unless we have an init-capture, we've gone one step too far.
10962  if (!var->isInitCapture())
10963  DC = Prev;
10964  return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10965 }
10966 
10967 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10968  Ty = Ty.getNonReferenceType();
10969  if (IsDereference && Ty->isPointerType())
10970  Ty = Ty->getPointeeType();
10971  return !Ty.isConstQualified();
10972 }
10973 
10974 // Update err_typecheck_assign_const and note_typecheck_assign_const
10975 // when this enum is changed.
10976 enum {
10982  ConstUnknown, // Keep as last element
10983 };
10984 
10985 /// Emit the "read-only variable not assignable" error and print notes to give
10986 /// more information about why the variable is not assignable, such as pointing
10987 /// to the declaration of a const variable, showing that a method is const, or
10988 /// that the function is returning a const reference.
10989 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10990  SourceLocation Loc) {
10991  SourceRange ExprRange = E->getSourceRange();
10992 
10993  // Only emit one error on the first const found. All other consts will emit
10994  // a note to the error.
10995  bool DiagnosticEmitted = false;
10996 
10997  // Track if the current expression is the result of a dereference, and if the
10998  // next checked expression is the result of a dereference.
10999  bool IsDereference = false;
11000  bool NextIsDereference = false;
11001 
11002  // Loop to process MemberExpr chains.
11003  while (true) {
11004  IsDereference = NextIsDereference;
11005 
11006  E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11007  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11008  NextIsDereference = ME->isArrow();
11009  const ValueDecl *VD = ME->getMemberDecl();
11010  if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11011  // Mutable fields can be modified even if the class is const.
11012  if (Field->isMutable()) {
11013  assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11014  break;
11015  }
11016 
11017  if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11018  if (!DiagnosticEmitted) {
11019  S.Diag(Loc, diag::err_typecheck_assign_const)
11020  << ExprRange << ConstMember << false /*static*/ << Field
11021  << Field->getType();
11022  DiagnosticEmitted = true;
11023  }
11024  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11025  << ConstMember << false /*static*/ << Field << Field->getType()
11026  << Field->getSourceRange();
11027  }
11028  E = ME->getBase();
11029  continue;
11030  } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11031  if (VDecl->getType().isConstQualified()) {
11032  if (!DiagnosticEmitted) {
11033  S.Diag(Loc, diag::err_typecheck_assign_const)
11034  << ExprRange << ConstMember << true /*static*/ << VDecl
11035  << VDecl->getType();
11036  DiagnosticEmitted = true;
11037  }
11038  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11039  << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11040  << VDecl->getSourceRange();
11041  }
11042  // Static fields do not inherit constness from parents.
11043  break;
11044  }
11045  break; // End MemberExpr
11046  } else if (const ArraySubscriptExpr *ASE =
11047  dyn_cast<ArraySubscriptExpr>(E)) {
11048  E = ASE->getBase()->IgnoreParenImpCasts();
11049  continue;
11050  } else if (const ExtVectorElementExpr *EVE =
11051  dyn_cast<ExtVectorElementExpr>(E)) {
11052  E = EVE->getBase()->IgnoreParenImpCasts();
11053  continue;
11054  }
11055  break;
11056  }
11057 
11058  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11059  // Function calls
11060  const FunctionDecl *FD = CE->getDirectCallee();
11061  if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11062  if (!DiagnosticEmitted) {
11063  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11064  << ConstFunction << FD;
11065  DiagnosticEmitted = true;
11066  }
11068  diag::note_typecheck_assign_const)
11069  << ConstFunction << FD << FD->getReturnType()
11070  << FD->getReturnTypeSourceRange();
11071  }
11072  } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11073  // Point to variable declaration.
11074  if (const ValueDecl *VD = DRE->getDecl()) {
11075  if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11076  if (!DiagnosticEmitted) {
11077  S.Diag(Loc, diag::err_typecheck_assign_const)
11078  << ExprRange << ConstVariable << VD << VD->getType();
11079  DiagnosticEmitted = true;
11080  }
11081  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11082  << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11083  }
11084  }
11085  } else if (isa<CXXThisExpr>(E)) {
11086  if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11087  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11088  if (MD->isConst()) {
11089  if (!DiagnosticEmitted) {
11090  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11091  << ConstMethod << MD;
11092  DiagnosticEmitted = true;
11093  }
11094  S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11095  << ConstMethod << MD << MD->getSourceRange();
11096  }
11097  }
11098  }
11099  }
11100 
11101  if (DiagnosticEmitted)
11102  return;
11103 
11104  // Can't determine a more specific message, so display the generic error.
11105  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11106 }
11107 
11112 };
11113 
11114 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11115  const RecordType *Ty,
11116  SourceLocation Loc, SourceRange Range,
11117  OriginalExprKind OEK,
11118  bool &DiagnosticEmitted) {
11119  std::vector<const RecordType *> RecordTypeList;
11120  RecordTypeList.push_back(Ty);
11121  unsigned NextToCheckIndex = 0;
11122  // We walk the record hierarchy breadth-first to ensure that we print
11123  // diagnostics in field nesting order.
11124  while (RecordTypeList.size() > NextToCheckIndex) {
11125  bool IsNested = NextToCheckIndex > 0;
11126  for (const FieldDecl *Field :
11127  RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11128  // First, check every field for constness.
11129  QualType FieldTy = Field->getType();
11130  if (FieldTy.isConstQualified()) {
11131  if (!DiagnosticEmitted) {
11132  S.Diag(Loc, diag::err_typecheck_assign_const)
11133  << Range << NestedConstMember << OEK << VD
11134  << IsNested << Field;
11135  DiagnosticEmitted = true;
11136  }
11137  S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11138  << NestedConstMember << IsNested << Field
11139  << FieldTy << Field->getSourceRange();
11140  }
11141 
11142  // Then we append it to the list to check next in order.
11143  FieldTy = FieldTy.getCanonicalType();
11144  if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11145  if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11146  RecordTypeList.push_back(FieldRecTy);
11147  }
11148  }
11149  ++NextToCheckIndex;
11150  }
11151 }
11152 
11153 /// Emit an error for the case where a record we are trying to assign to has a
11154 /// const-qualified field somewhere in its hierarchy.
11155 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11156  SourceLocation Loc) {
11157  QualType Ty = E->getType();
11158  assert(Ty->isRecordType() && "lvalue was not record?");
11159  SourceRange Range = E->getSourceRange();
11160  const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11161  bool DiagEmitted = false;
11162 
11163  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11164  DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11165  Range, OEK_Member, DiagEmitted);
11166  else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11167  DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11168  Range, OEK_Variable, DiagEmitted);
11169  else
11170  DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11171  Range, OEK_LValue, DiagEmitted);
11172  if (!DiagEmitted)
11173  DiagnoseConstAssignment(S, E, Loc);
11174 }
11175 
11176 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
11177 /// emit an error and return true. If so, return false.
11179  assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11180 
11182 
11183  SourceLocation OrigLoc = Loc;
11185  &Loc);
11186  if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11188  if (IsLV == Expr::MLV_Valid)
11189  return false;
11190 
11191  unsigned DiagID = 0;
11192  bool NeedType = false;
11193  switch (IsLV) { // C99 6.5.16p2
11195  // Use a specialized diagnostic when we're assigning to an object
11196  // from an enclosing function or block.
11198  if (NCCK == NCCK_Block)
11199  DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11200  else
11201  DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11202  break;
11203  }
11204 
11205  // In ARC, use some specialized diagnostics for occasions where we
11206  // infer 'const'. These are always pseudo-strong variables.
11207  if (S.getLangOpts().ObjCAutoRefCount) {
11208  DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11209  if (declRef && isa<VarDecl>(declRef->getDecl())) {
11210  VarDecl *var = cast<VarDecl>(declRef->getDecl());
11211 
11212  // Use the normal diagnostic if it's pseudo-__strong but the
11213  // user actually wrote 'const'.
11214  if (var->isARCPseudoStrong() &&
11215  (!var->getTypeSourceInfo() ||
11216  !var->getTypeSourceInfo()->getType().isConstQualified())) {
11217  // There are three pseudo-strong cases:
11218  // - self
11219  ObjCMethodDecl *method = S.getCurMethodDecl();
11220  if (method && var == method->getSelfDecl()) {
11221  DiagID = method->isClassMethod()
11222  ? diag::err_typecheck_arc_assign_self_class_method
11223  : diag::err_typecheck_arc_assign_self;
11224 
11225  // - Objective-C externally_retained attribute.
11226  } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11227  isa<ParmVarDecl>(var)) {
11228  DiagID = diag::err_typecheck_arc_assign_externally_retained;
11229 
11230  // - fast enumeration variables
11231  } else {
11232  DiagID = diag::err_typecheck_arr_assign_enumeration;
11233  }
11234 
11235  SourceRange Assign;
11236  if (Loc != OrigLoc)
11237  Assign = SourceRange(OrigLoc, OrigLoc);
11238  S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11239  // We need to preserve the AST regardless, so migration tool
11240  // can do its job.
11241  return false;
11242  }
11243  }
11244  }
11245 
11246  // If none of the special cases above are triggered, then this is a
11247  // simple const assignment.
11248  if (DiagID == 0) {
11249  DiagnoseConstAssignment(S, E, Loc);
11250  return true;
11251  }
11252 
11253  break;
11255  DiagnoseConstAssignment(S, E, Loc);
11256  return true;
11258  DiagnoseRecursiveConstFields(S, E, Loc);
11259  return true;
11260  case Expr::MLV_ArrayType:
11262  DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11263  NeedType = true;
11264  break;
11266  DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11267  NeedType = true;
11268  break;
11269  case Expr::MLV_LValueCast:
11270  DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11271  break;
11272  case Expr::MLV_Valid:
11273  llvm_unreachable("did not take early return for MLV_Valid");
11277  DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11278  break;
11281  return S.RequireCompleteType(Loc, E->getType(),
11282  diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11284  DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11285  break;
11287  llvm_unreachable("readonly properties should be processed differently");
11289  DiagID = diag::err_readonly_message_assignment;
11290  break;
11292  DiagID = diag::err_no_subobject_property_setting;
11293  break;
11294  }
11295 
11296  SourceRange Assign;
11297  if (Loc != OrigLoc)
11298  Assign = SourceRange(OrigLoc, OrigLoc);
11299  if (NeedType)
11300  S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11301  else
11302  S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11303  return true;
11304 }
11305 
11306 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11307  SourceLocation Loc,
11308  Sema &Sema) {
11309  if (Sema.inTemplateInstantiation())
11310  return;
11311  if (Sema.isUnevaluatedContext())
11312  return;
11313  if (Loc.isInvalid() || Loc.isMacroID())
11314  return;
11315  if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11316  return;
11317 
11318  // C / C++ fields
11319  MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11320  MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11321  if (ML && MR) {
11322  if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11323  return;
11324  const ValueDecl *LHSDecl =
11325  cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11326  const ValueDecl *RHSDecl =
11327  cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11328  if (LHSDecl != RHSDecl)
11329  return;
11330  if (LHSDecl->getType().isVolatileQualified())
11331  return;
11332  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11333  if (RefTy->getPointeeType().isVolatileQualified())
11334  return;
11335 
11336  Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11337  }
11338 
11339  // Objective-C instance variables
11340  ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11341  ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11342  if (OL && OR && OL->getDecl() == OR->getDecl()) {
11343  DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11344  DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11345  if (RL && RR && RL->getDecl() == RR->getDecl())
11346  Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11347  }
11348 }
11349 
11350 // C99 6.5.16.1
11352  SourceLocation Loc,
11353  QualType CompoundType) {
11354  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11355 
11356  // Verify that LHS is a modifiable lvalue, and emit error if not.
11357  if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11358  return QualType();
11359 
11360  QualType LHSType = LHSExpr->getType();
11361  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11362  CompoundType;
11363  // OpenCL v1.2 s6.1.1.1 p2:
11364  // The half data type can only be used to declare a pointer to a buffer that
11365  // contains half values
11366  if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11367  LHSType->isHalfType()) {
11368  Diag(Loc, diag::err_opencl_half_load_store) << 1
11369  << LHSType.getUnqualifiedType();
11370  return QualType();
11371  }
11372 
11373  AssignConvertType ConvTy;
11374  if (CompoundType.isNull()) {
11375  Expr *RHSCheck = RHS.get();
11376 
11377  CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11378 
11379  QualType LHSTy(LHSType);
11380  ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11381  if (RHS.isInvalid())
11382  return QualType();
11383  // Special case of NSObject attributes on c-style pointer types.
11384  if (ConvTy == IncompatiblePointer &&
11385  ((Context.isObjCNSObjectType(LHSType) &&
11386  RHSType->isObjCObjectPointerType()) ||
11387  (Context.isObjCNSObjectType(RHSType) &&
11388  LHSType->isObjCObjectPointerType())))
11389  ConvTy = Compatible;
11390 
11391  if (ConvTy == Compatible &&
11392  LHSType->isObjCObjectType())
11393  Diag(Loc, diag::err_objc_object_assignment)
11394  << LHSType;
11395 
11396  // If the RHS is a unary plus or minus, check to see if they = and + are
11397  // right next to each other. If so, the user may have typo'd "x =+ 4"
11398  // instead of "x += 4".
11399  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11400  RHSCheck = ICE->getSubExpr();
11401  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11402  if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11403  Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11404  // Only if the two operators are exactly adjacent.
11405  Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11406  // And there is a space or other character before the subexpr of the
11407  // unary +/-. We don't want to warn on "x=-1".
11408  Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11409  UO->getSubExpr()->getBeginLoc().isFileID()) {
11410  Diag(Loc, diag::warn_not_compound_assign)
11411  << (UO->getOpcode() == UO_Plus ? "+" : "-")
11412  << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11413  }
11414  }
11415 
11416  if (ConvTy == Compatible) {
11417  if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11418  // Warn about retain cycles where a block captures the LHS, but
11419  // not if the LHS is a simple variable into which the block is
11420  // being stored...unless that variable can be captured by reference!
11421  const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11422  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11423  if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11424  checkRetainCycles(LHSExpr, RHS.get());
11425  }
11426 
11427  if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11428  LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11429  // It is safe to assign a weak reference into a strong variable.
11430  // Although this code can still have problems:
11431  // id x = self.weakProp;
11432  // id y = self.weakProp;
11433  // we do not warn to warn spuriously when 'x' and 'y' are on separate
11434  // paths through the function. This should be revisited if
11435  // -Wrepeated-use-of-weak is made flow-sensitive.
11436  // For ObjCWeak only, we do not warn if the assign is to a non-weak
11437  // variable, which will be valid for the current autorelease scope.
11438  if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11439  RHS.get()->getBeginLoc()))
11440  getCurFunction()->markSafeWeakUse(RHS.get());
11441 
11442  } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11443  checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11444  }
11445  }
11446  } else {
11447  // Compound assignment "x += y"
11448  ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11449  }
11450 
11451  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11452  RHS.get(), AA_Assigning))
11453  return QualType();
11454 
11455  CheckForNullPointerDereference(*this, LHSExpr);
11456 
11457  // C99 6.5.16p3: The type of an assignment expression is the type of the
11458  // left operand unless the left operand has qualified type, in which case
11459  // it is the unqualified version of the type of the left operand.
11460  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11461  // is converted to the type of the assignment expression (above).
11462  // C++ 5.17p1: the type of the assignment expression is that of its left
11463  // operand.
11464  return (getLangOpts().CPlusPlus
11465  ? LHSType : LHSType.getUnqualifiedType());
11466 }
11467 
11468 // Only ignore explicit casts to void.
11469 static bool IgnoreCommaOperand(const Expr *E) {
11470  E = E->IgnoreParens();
11471 
11472  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11473  if (CE->getCastKind() == CK_ToVoid) {
11474  return true;
11475  }
11476 
11477  // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11478  if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11479  CE->getSubExpr()->getType()->isDependentType()) {
11480  return true;
11481  }
11482  }
11483 
11484  return false;
11485 }
11486 
11487 // Look for instances where it is likely the comma operator is confused with
11488 // another operator. There is a whitelist of acceptable expressions for the
11489 // left hand side of the comma operator, otherwise emit a warning.
11491  // No warnings in macros
11492  if (Loc.isMacroID())
11493  return;
11494 
11495  // Don't warn in template instantiations.
11496  if (inTemplateInstantiation())
11497  return;
11498 
11499  // Scope isn't fine-grained enough to whitelist the specific cases, so
11500  // instead, skip more than needed, then call back into here with the
11501  // CommaVisitor in SemaStmt.cpp.
11502  // The whitelisted locations are the initialization and increment portions
11503  // of a for loop. The additional checks are on the condition of
11504  // if statements, do/while loops, and for loops.
11505  // Differences in scope flags for C89 mode requires the extra logic.
11506  const unsigned ForIncrementFlags =
11507  getLangOpts().C99 || getLangOpts().CPlusPlus
11510  const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11511  const unsigned ScopeFlags = getCurScope()->getFlags();
11512  if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11513  (ScopeFlags & ForInitFlags) == ForInitFlags)
11514  return;
11515 
11516  // If there are multiple comma operators used together, get the RHS of the
11517  // of the comma operator as the LHS.
11518  while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11519  if (BO->getOpcode() != BO_Comma)
11520  break;
11521  LHS = BO->getRHS();
11522  }
11523 
11524  // Only allow some expressions on LHS to not warn.
11525  if (IgnoreCommaOperand(LHS))
11526  return;
11527 
11528  Diag(Loc, diag::warn_comma_operator);
11529  Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11530  << LHS->getSourceRange()
11532  LangOpts.CPlusPlus ? "static_cast<void>("
11533  : "(void)(")
11534  << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11535  ")");
11536 }
11537 
11538 // C99 6.5.17
11540  SourceLocation Loc) {
11541  LHS = S.CheckPlaceholderExpr(LHS.get());
11542  RHS = S.CheckPlaceholderExpr(RHS.get());
11543  if (LHS.isInvalid() || RHS.isInvalid())
11544  return QualType();
11545 
11546  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11547  // operands, but not unary promotions.
11548  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11549 
11550  // So we treat the LHS as a ignored value, and in C++ we allow the
11551  // containing site to determine what should be done with the RHS.
11552  LHS = S.IgnoredValueConversions(LHS.get());
11553  if (LHS.isInvalid())
11554  return QualType();
11555 
11556  S.DiagnoseUnusedExprResult(LHS.get());
11557 
11558  if (!S.getLangOpts().CPlusPlus) {
11560  if (RHS.isInvalid())
11561  return QualType();
11562  if (!RHS.get()->getType()->isVoidType())
11563  S.RequireCompleteType(Loc, RHS.get()->getType(),
11564  diag::err_incomplete_type);
11565  }
11566 
11567  if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11568  S.DiagnoseCommaOperator(LHS.get(), Loc);
11569 
11570  return RHS.get()->getType();
11571 }
11572 
11573 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11574 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11576  ExprValueKind &VK,
11577  ExprObjectKind &OK,
11578  SourceLocation OpLoc,
11579  bool IsInc, bool IsPrefix) {
11580  if (Op->isTypeDependent())
11581  return S.Context.DependentTy;
11582 
11583  QualType ResType = Op->getType();
11584  // Atomic types can be used for increment / decrement where the non-atomic
11585  // versions can, so ignore the _Atomic() specifier for the purpose of
11586  // checking.
11587  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11588  ResType = ResAtomicType->getValueType();
11589 
11590  assert(!ResType.isNull() && "no type for increment/decrement expression");
11591 
11592  if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11593  // Decrement of bool is not allowed.
11594  if (!IsInc) {
11595  S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11596  return QualType();
11597  }
11598  // Increment of bool sets it to true, but is deprecated.
11599  S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11600  : diag::warn_increment_bool)
11601  << Op->getSourceRange();
11602  } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11603  // Error on enum increments and decrements in C++ mode
11604  S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11605  return QualType();
11606  } else if (ResType->isRealType()) {
11607  // OK!
11608  } else if (ResType->isPointerType()) {
11609  // C99 6.5.2.4p2, 6.5.6p2
11610  if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11611  return QualType();
11612  } else if (ResType->isObjCObjectPointerType()) {
11613  // On modern runtimes, ObjC pointer arithmetic is forbidden.
11614  // Otherwise, we just need a complete type.
11615  if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11616  checkArithmeticOnObjCPointer(S, OpLoc, Op))
11617  return QualType();
11618  } else if (ResType->isAnyComplexType()) {
11619  // C99 does not support ++/-- on complex types, we allow as an extension.
11620  S.Diag(OpLoc, diag::ext_integer_increment_complex)
11621  << ResType << Op->getSourceRange();
11622  } else if (ResType->isPlaceholderType()) {
11623  ExprResult PR = S.CheckPlaceholderExpr(Op);
11624  if (PR.isInvalid()) return QualType();
11625  return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11626  IsInc, IsPrefix);
11627  } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11628  // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11629  } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11630  (ResType->getAs<VectorType>()->getVectorKind() !=
11632  // The z vector extensions allow ++ and -- for non-bool vectors.
11633  } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11634  ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11635  // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11636  } else {
11637  S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11638  << ResType << int(IsInc) << Op->getSourceRange();
11639  return QualType();
11640  }
11641  // At this point, we know we have a real, complex or pointer type.
11642  // Now make sure the operand is a modifiable lvalue.
11643  if (CheckForModifiableLvalue(Op, OpLoc, S))
11644  return QualType();
11645  // In C++, a prefix increment is the same type as the operand. Otherwise
11646  // (in C or with postfix), the increment is the unqualified type of the
11647  // operand.
11648  if (IsPrefix && S.getLangOpts().CPlusPlus) {
11649  VK = VK_LValue;
11650  OK = Op->getObjectKind();
11651  return ResType;
11652  } else {
11653  VK = VK_RValue;
11654  return ResType.getUnqualifiedType();
11655  }
11656 }
11657 
11658 
11659 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11660 /// This routine allows us to typecheck complex/recursive expressions
11661 /// where the declaration is needed for type checking. We only need to
11662 /// handle cases when the expression references a function designator
11663 /// or is an lvalue. Here are some examples:
11664 /// - &(x) => x
11665 /// - &*****f => f for f a function designator.
11666 /// - &s.xx => s
11667 /// - &s.zz[1].yy -> s, if zz is an array
11668 /// - *(x + 1) -> x, if x is an array
11669 /// - &"123"[2] -> 0
11670 /// - & __real__ x -> x
11672  switch (E->getStmtClass()) {
11673  case Stmt::DeclRefExprClass:
11674  return cast<DeclRefExpr>(E)->getDecl();
11675  case Stmt::MemberExprClass:
11676  // If this is an arrow operator, the address is an offset from
11677  // the base's value, so the object the base refers to is
11678  // irrelevant.
11679  if (cast<MemberExpr>(E)->isArrow())
11680  return nullptr;
11681  // Otherwise, the expression refers to a part of the base
11682  return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11683  case Stmt::ArraySubscriptExprClass: {
11684  // FIXME: This code shouldn't be necessary! We should catch the implicit
11685  // promotion of register arrays earlier.
11686  Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11687  if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11688  if (ICE->getSubExpr()->getType()->isArrayType())
11689  return getPrimaryDecl(ICE->getSubExpr());
11690  }
11691  return nullptr;
11692  }
11693  case Stmt::UnaryOperatorClass: {
11694  UnaryOperator *UO = cast<UnaryOperator>(E);
11695 
11696  switch(UO->getOpcode()) {
11697  case UO_Real:
11698  case UO_Imag:
11699  case UO_Extension:
11700  return getPrimaryDecl(UO->getSubExpr());
11701  default:
11702  return nullptr;
11703  }
11704  }
11705  case Stmt::ParenExprClass:
11706  return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11707  case Stmt::ImplicitCastExprClass:
11708  // If the result of an implicit cast is an l-value, we care about
11709  // the sub-expression; otherwise, the result here doesn't matter.
11710  return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11711  default:
11712  return nullptr;
11713  }
11714 }
11715 
11716 namespace {
11717  enum {
11718  AO_Bit_Field = 0,
11719  AO_Vector_Element = 1,
11720  AO_Property_Expansion = 2,
11721  AO_Register_Variable = 3,
11722  AO_No_Error = 4
11723  };
11724 }
11725 /// Diagnose invalid operand for address of operations.
11726 ///
11727 /// \param Type The type of operand which cannot have its address taken.
11729  Expr *E, unsigned Type) {
11730  S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11731 }
11732 
11733 /// CheckAddressOfOperand - The operand of & must be either a function
11734 /// designator or an lvalue designating an object. If it is an lvalue, the
11735 /// object cannot be declared with storage class register or be a bit field.
11736 /// Note: The usual conversions are *not* applied to the operand of the &
11737 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11738 /// In C++, the operand might be an overloaded function name, in which case
11739 /// we allow the '&' but retain the overloaded-function type.
11741  if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11742  if (PTy->getKind() == BuiltinType::Overload) {
11743  Expr *E = OrigOp.get()->IgnoreParens();
11744  if (!isa<OverloadExpr>(E)) {
11745  assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11746  Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11747  << OrigOp.get()->getSourceRange();
11748  return QualType();
11749  }
11750 
11751  OverloadExpr *Ovl = cast<OverloadExpr>(E);
11752  if (isa<UnresolvedMemberExpr>(Ovl))
11753  if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11754  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11755  << OrigOp.get()->getSourceRange();
11756  return QualType();
11757  }
11758 
11759  return Context.OverloadTy;
11760  }
11761 
11762  if (PTy->getKind() == BuiltinType::UnknownAny)
11763  return Context.UnknownAnyTy;
11764 
11765  if (PTy->getKind() == BuiltinType::BoundMember) {
11766  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11767  << OrigOp.get()->getSourceRange();
11768  return QualType();
11769  }
11770 
11771  OrigOp = CheckPlaceholderExpr(OrigOp.get());
11772  if (OrigOp.isInvalid()) return QualType();
11773  }
11774 
11775  if (OrigOp.get()->isTypeDependent())
11776  return Context.DependentTy;
11777 
11778  assert(!OrigOp.get()->getType()->isPlaceholderType());
11779 
11780  // Make sure to ignore parentheses in subsequent checks
11781  Expr *op = OrigOp.get()->IgnoreParens();
11782 
11783  // In OpenCL captures for blocks called as lambda functions
11784  // are located in the private address space. Blocks used in
11785  // enqueue_kernel can be located in a different address space
11786  // depending on a vendor implementation. Thus preventing
11787  // taking an address of the capture to avoid invalid AS casts.
11788  if (LangOpts.OpenCL) {
11789  auto* VarRef = dyn_cast<DeclRefExpr>(op);
11790  if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11791  Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11792  return QualType();
11793  }
11794  }
11795 
11796  if (getLangOpts().C99) {
11797  // Implement C99-only parts of addressof rules.
11798  if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11799  if (uOp->getOpcode() == UO_Deref)
11800  // Per C99 6.5.3.2, the address of a deref always returns a valid result
11801  // (assuming the deref expression is valid).
11802  return uOp->getSubExpr()->getType();
11803  }
11804  // Technically, there should be a check for array subscript
11805  // expressions here, but the result of one is always an lvalue anyway.
11806  }
11807  ValueDecl *dcl = getPrimaryDecl(op);
11808 
11809  if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11810  if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11811  op->getBeginLoc()))
11812  return QualType();
11813 
11814  Expr::LValueClassification lval = op->ClassifyLValue(Context);
11815  unsigned AddressOfError = AO_No_Error;
11816 
11817  if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11818  bool sfinae = (bool)isSFINAEContext();
11819  Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11820  : diag::ext_typecheck_addrof_temporary)
11821  << op->getType() << op->getSourceRange();
11822  if (sfinae)
11823  return QualType();
11824  // Materialize the temporary as an lvalue so that we can take its address.
11825  OrigOp = op =
11826  CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11827  } else if (isa<ObjCSelectorExpr>(op)) {
11828  return Context.getPointerType(op->getType());
11829  } else if (lval == Expr::LV_MemberFunction) {
11830  // If it's an instance method, make a member pointer.
11831  // The expression must have exactly the form &A::foo.
11832 
11833  // If the underlying expression isn't a decl ref, give up.
11834  if (!isa<DeclRefExpr>(op)) {
11835  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11836  << OrigOp.get()->getSourceRange();
11837  return QualType();
11838  }
11839  DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11840  CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11841 
11842  // The id-expression was parenthesized.
11843  if (OrigOp.get() != DRE) {
11844  Diag(OpLoc, diag::err_parens_pointer_member_function)
11845  << OrigOp.get()->getSourceRange();
11846 
11847  // The method was named without a qualifier.
11848  } else if (!DRE->getQualifier()) {
11849  if (MD->getParent()->getName().empty())
11850  Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11851  << op->getSourceRange();
11852  else {
11853  SmallString<32> Str;
11854  StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11855  Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11856  << op->getSourceRange()
11858  }
11859  }
11860 
11861  // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11862  if (isa<CXXDestructorDecl>(MD))
11863  Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11864 
11865  QualType MPTy = Context.getMemberPointerType(
11866  op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11867  // Under the MS ABI, lock down the inheritance model now.
11868  if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11869  (void)isCompleteType(OpLoc, MPTy);
11870  return MPTy;
11871  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11872  // C99 6.5.3.2p1
11873  // The operand must be either an l-value or a function designator
11874  if (!op->getType()->isFunctionType()) {
11875  // Use a special diagnostic for loads from property references.
11876  if (isa<PseudoObjectExpr>(op)) {
11877  AddressOfError = AO_Property_Expansion;
11878  } else {
11879  Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11880  << op->getType() << op->getSourceRange();
11881  return QualType();
11882  }
11883  }
11884  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11885  // The operand cannot be a bit-field
11886  AddressOfError = AO_Bit_Field;
11887  } else if (op->getObjectKind() == OK_VectorComponent) {
11888  // The operand cannot be an element of a vector
11889  AddressOfError = AO_Vector_Element;
11890  } else if (dcl) { // C99 6.5.3.2p1
11891  // We have an lvalue with a decl. Make sure the decl is not declared
11892  // with the register storage-class specifier.
11893  if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11894  // in C++ it is not error to take address of a register
11895  // variable (c++03 7.1.1P3)
11896  if (vd->getStorageClass() == SC_Register &&
11897  !getLangOpts().CPlusPlus) {
11898  AddressOfError = AO_Register_Variable;
11899  }
11900  } else if (isa<MSPropertyDecl>(dcl)) {
11901  AddressOfError = AO_Property_Expansion;
11902  } else if (isa<FunctionTemplateDecl>(dcl)) {
11903  return Context.OverloadTy;
11904  } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11905  // Okay: we can take the address of a field.
11906  // Could be a pointer to member, though, if there is an explicit
11907  // scope qualifier for the class.
11908  if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11909  DeclContext *Ctx = dcl->getDeclContext();
11910  if (Ctx && Ctx->isRecord()) {
11911  if (dcl->getType()->isReferenceType()) {
11912  Diag(OpLoc,
11913  diag::err_cannot_form_pointer_to_member_of_reference_type)
11914  << dcl->getDeclName() << dcl->getType();
11915  return QualType();
11916  }
11917 
11918  while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11919  Ctx = Ctx->getParent();
11920 
11921  QualType MPTy = Context.getMemberPointerType(
11922  op->getType(),
11923  Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11924  // Under the MS ABI, lock down the inheritance model now.
11925  if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11926  (void)isCompleteType(OpLoc, MPTy);
11927  return MPTy;
11928  }
11929  }
11930  } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11931  !isa<BindingDecl>(dcl))
11932  llvm_unreachable("Unknown/unexpected decl type");
11933  }
11934 
11935  if (AddressOfError != AO_No_Error) {
11936  diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11937  return QualType();
11938  }
11939 
11940  if (lval == Expr::LV_IncompleteVoidType) {
11941  // Taking the address of a void variable is technically illegal, but we
11942  // allow it in cases which are otherwise valid.
11943  // Example: "extern void x; void* y = &x;".
11944  Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11945  }
11946 
11947  // If the operand has type "type", the result has type "pointer to type".
11948  if (op->getType()->isObjCObjectType())
11949  return Context.getObjCObjectPointerType(op->getType());
11950 
11951  CheckAddressOfPackedMember(op);
11952 
11953  return Context.getPointerType(op->getType());
11954 }
11955 
11956 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11957  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11958  if (!DRE)
11959  return;
11960  const Decl *D = DRE->getDecl();
11961  if (!D)
11962  return;
11963  const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11964  if (!Param)
11965  return;
11966  if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11967  if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11968  return;
11969  if (FunctionScopeInfo *FD = S.getCurFunction())
11970  if (!FD->ModifiedNonNullParams.count(Param))
11971  FD->ModifiedNonNullParams.insert(Param);
11972 }
11973 
11974 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11976  SourceLocation OpLoc) {
11977  if (Op->isTypeDependent())
11978  return S.Context.DependentTy;
11979 
11980  ExprResult ConvResult = S.UsualUnaryConversions(Op);
11981  if (ConvResult.isInvalid())
11982  return QualType();
11983  Op = ConvResult.get();
11984  QualType OpTy = Op->getType();
11985  QualType Result;
11986 
11987  if (isa<CXXReinterpretCastExpr>(Op)) {
11988  QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11989  S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11990  Op->getSourceRange());
11991  }
11992 
11993  if (const PointerType *PT = OpTy->getAs<PointerType>())
11994  {
11995  Result = PT->getPointeeType();
11996  }
11997  else if (const ObjCObjectPointerType *OPT =
11998  OpTy->getAs<ObjCObjectPointerType>())
11999  Result = OPT->getPointeeType();
12000  else {
12001  ExprResult PR = S.CheckPlaceholderExpr(Op);
12002  if (PR.isInvalid()) return QualType();
12003  if (PR.get() != Op)
12004  return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12005  }
12006 
12007  if (Result.isNull()) {
12008  S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12009  << OpTy << Op->getSourceRange();
12010  return QualType();
12011  }
12012 
12013  // Note that per both C89 and C99, indirection is always legal, even if Result
12014  // is an incomplete type or void. It would be possible to warn about
12015  // dereferencing a void pointer, but it's completely well-defined, and such a
12016  // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12017  // for pointers to 'void' but is fine for any other pointer type:
12018  //
12019  // C++ [expr.unary.op]p1:
12020  // [...] the expression to which [the unary * operator] is applied shall
12021  // be a pointer to an object type, or a pointer to a function type
12022  if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12023  S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12024  << OpTy << Op->getSourceRange();
12025 
12026  // Dereferences are usually l-values...
12027  VK = VK_LValue;
12028 
12029  // ...except that certain expressions are never l-values in C.
12030  if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12031  VK = VK_RValue;
12032 
12033  return Result;
12034 }
12035 
12036 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12037  BinaryOperatorKind Opc;
12038  switch (Kind) {
12039  default: llvm_unreachable("Unknown binop!");
12040  case tok::periodstar: Opc = BO_PtrMemD; break;
12041  case tok::arrowstar: Opc = BO_PtrMemI; break;
12042  case tok::star: Opc = BO_Mul; break;
12043  case tok::slash: Opc = BO_Div; break;
12044  case tok::percent: Opc = BO_Rem; break;
12045  case tok::plus: Opc = BO_Add; break;
12046  case tok::minus: Opc = BO_Sub; break;
12047  case tok::lessless: Opc = BO_Shl; break;
12048  case tok::greatergreater: Opc = BO_Shr; break;
12049  case tok::lessequal: Opc = BO_LE; break;
12050  case tok::less: Opc = BO_LT; break;
12051  case tok::greaterequal: Opc = BO_GE; break;
12052  case tok::greater: Opc = BO_GT; break;
12053  case tok::exclaimequal: Opc = BO_NE; break;
12054  case tok::equalequal: Opc = BO_EQ; break;
12055  case tok::spaceship: Opc = BO_Cmp; break;
12056  case tok::amp: Opc = BO_And; break;
12057  case tok::caret: Opc = BO_Xor; break;
12058  case tok::pipe: Opc = BO_Or; break;
12059  case tok::ampamp: Opc = BO_LAnd; break;
12060  case tok::pipepipe: Opc = BO_LOr; break;
12061  case tok::equal: Opc = BO_Assign; break;
12062  case tok::starequal: Opc = BO_MulAssign; break;
12063  case tok::slashequal: Opc = BO_DivAssign; break;
12064  case tok::percentequal: Opc = BO_RemAssign; break;
12065  case tok::plusequal: Opc = BO_AddAssign; break;
12066  case tok::minusequal: Opc = BO_SubAssign; break;
12067  case tok::lesslessequal: Opc = BO_ShlAssign; break;
12068  case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
12069  case tok::ampequal: Opc = BO_AndAssign; break;
12070  case tok::caretequal: Opc = BO_XorAssign; break;
12071  case tok::pipeequal: Opc = BO_OrAssign; break;
12072  case tok::comma: Opc = BO_Comma; break;
12073  }
12074  return Opc;
12075 }
12076 
12078  tok::TokenKind Kind) {
12079  UnaryOperatorKind Opc;
12080  switch (Kind) {
12081  default: llvm_unreachable("Unknown unary op!");
12082  case tok::plusplus: Opc = UO_PreInc; break;
12083  case tok::minusminus: Opc = UO_PreDec; break;
12084  case tok::amp: Opc = UO_AddrOf; break;
12085  case tok::star: Opc = UO_Deref; break;
12086  case tok::plus: Opc = UO_Plus; break;
12087  case tok::minus: Opc = UO_Minus; break;
12088  case tok::tilde: Opc = UO_Not; break;
12089  case tok::exclaim: Opc = UO_LNot; break;
12090  case tok::kw___real: Opc = UO_Real; break;
12091  case tok::kw___imag: Opc = UO_Imag; break;
12092  case tok::kw___extension__: Opc = UO_Extension; break;
12093  }
12094  return Opc;
12095 }
12096 
12097 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12098 /// This warning suppressed in the event of macro expansions.
12099 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12100  SourceLocation OpLoc, bool IsBuiltin) {
12101  if (S.inTemplateInstantiation())
12102  return;
12103  if (S.isUnevaluatedContext())
12104  return;
12105  if (OpLoc.isInvalid() || OpLoc.isMacroID())
12106  return;
12107  LHSExpr = LHSExpr->IgnoreParenImpCasts();
12108  RHSExpr = RHSExpr->IgnoreParenImpCasts();
12109  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12110  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12111  if (!LHSDeclRef || !RHSDeclRef ||
12112  LHSDeclRef->getLocation().isMacroID() ||
12113  RHSDeclRef->getLocation().isMacroID())
12114  return;
12115  const ValueDecl *LHSDecl =
12116  cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12117  const ValueDecl *RHSDecl =
12118  cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12119  if (LHSDecl != RHSDecl)
12120  return;
12121  if (LHSDecl->getType().isVolatileQualified())
12122  return;
12123  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12124  if (RefTy->getPointeeType().isVolatileQualified())
12125  return;
12126 
12127  S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12128  : diag::warn_self_assignment_overloaded)
12129  << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12130  << RHSExpr->getSourceRange();
12131 }
12132 
12133 /// Check if a bitwise-& is performed on an Objective-C pointer. This
12134 /// is usually indicative of introspection within the Objective-C pointer.
12136  SourceLocation OpLoc) {
12137  if (!S.getLangOpts().ObjC)
12138  return;
12139 
12140  const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12141  const Expr *LHS = L.get();
12142  const Expr *RHS = R.get();
12143 
12145  ObjCPointerExpr = LHS;
12146  OtherExpr = RHS;
12147  }
12148  else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12149  ObjCPointerExpr = RHS;
12150  OtherExpr = LHS;
12151  }
12152 
12153  // This warning is deliberately made very specific to reduce false
12154  // positives with logic that uses '&' for hashing. This logic mainly
12155  // looks for code trying to introspect into tagged pointers, which
12156  // code should generally never do.
12157  if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12158  unsigned Diag = diag::warn_objc_pointer_masking;
12159  // Determine if we are introspecting the result of performSelectorXXX.
12160  const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12161  // Special case messages to -performSelector and friends, which
12162  // can return non-pointer values boxed in a pointer value.
12163  // Some clients may wish to silence warnings in this subcase.
12164  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12165  Selector S = ME->getSelector();
12166  StringRef SelArg0 = S.getNameForSlot(0);
12167  if (SelArg0.startswith("performSelector"))
12168  Diag = diag::warn_objc_pointer_masking_performSelector;
12169  }
12170 
12171  S.Diag(OpLoc, Diag)
12172  << ObjCPointerExpr->getSourceRange();
12173  }
12174 }
12175 
12177  if (!E)
12178  return nullptr;
12179  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12180  return DRE->getDecl();
12181  if (auto *ME = dyn_cast<MemberExpr>(E))
12182  return ME->getMemberDecl();
12183  if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12184  return IRE->getDecl();
12185  return nullptr;
12186 }
12187 
12188 // This helper function promotes a binary operator's operands (which are of a
12189 // half vector type) to a vector of floats and then truncates the result to
12190 // a vector of either half or short.
12192  BinaryOperatorKind Opc, QualType ResultTy,
12194  bool IsCompAssign, SourceLocation OpLoc,
12195  FPOptions FPFeatures) {
12196  auto &Context = S.getASTContext();
12197  assert((isVector(ResultTy, Context.HalfTy) ||
12198  isVector(ResultTy, Context.ShortTy)) &&
12199  "Result must be a vector of half or short");
12200  assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12201  isVector(RHS.get()->getType(), Context.HalfTy) &&
12202  "both operands expected to be a half vector");
12203 
12204  RHS = convertVector(RHS.get(), Context.FloatTy, S);
12205  QualType BinOpResTy = RHS.get()->getType();
12206 
12207  // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12208  // change BinOpResTy to a vector of ints.
12209  if (isVector(ResultTy, Context.ShortTy))
12210  BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12211 
12212  if (IsCompAssign)
12213  return new (Context) CompoundAssignOperator(
12214  LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12215  OpLoc, FPFeatures);
12216 
12217  LHS = convertVector(LHS.get(), Context.FloatTy, S);
12218  auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12219  VK, OK, OpLoc, FPFeatures);
12220  return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12221 }
12222 
12223 static std::pair<ExprResult, ExprResult>
12225  Expr *RHSExpr) {
12226  ExprResult LHS = LHSExpr, RHS = RHSExpr;
12227  if (!S.getLangOpts().CPlusPlus) {
12228  // C cannot handle TypoExpr nodes on either side of a binop because it
12229  // doesn't handle dependent types properly, so make sure any TypoExprs have
12230  // been dealt with before checking the operands.
12231  LHS = S.CorrectDelayedTyposInExpr(LHS);
12232  RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12233  if (Opc != BO_Assign)
12234  return ExprResult(E);
12235  // Avoid correcting the RHS to the same Expr as the LHS.
12236  Decl *D = getDeclFromExpr(E);
12237  return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12238  });
12239  }
12240  return std::make_pair(LHS, RHS);
12241 }
12242 
12243 /// Returns true if conversion between vectors of halfs and vectors of floats
12244 /// is needed.
12245 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12246  QualType SrcType) {
12247  return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12249  isVector(SrcType, Ctx.HalfTy);
12250 }
12251 
12252 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12253 /// operator @p Opc at location @c TokLoc. This routine only supports
12254 /// built-in operations; ActOnBinOp handles overloaded operators.
12256  BinaryOperatorKind Opc,
12257  Expr *LHSExpr, Expr *RHSExpr) {
12258  if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12259  // The syntax only allows initializer lists on the RHS of assignment,
12260  // so we don't need to worry about accepting invalid code for
12261  // non-assignment operators.
12262  // C++11 5.17p9:
12263  // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12264  // of x = {} is x = T().
12266  RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12267  InitializedEntity Entity =
12269  InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12270  ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12271  if (Init.isInvalid())
12272  return Init;
12273  RHSExpr = Init.get();
12274  }
12275 
12276  ExprResult LHS = LHSExpr, RHS = RHSExpr;
12277  QualType ResultTy; // Result type of the binary operator.
12278  // The following two variables are used for compound assignment operators
12279  QualType CompLHSTy; // Type of LHS after promotions for computation
12280  QualType CompResultTy; // Type of computation result
12281  ExprValueKind VK = VK_RValue;
12283  bool ConvertHalfVec = false;
12284 
12285  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12286  if (!LHS.isUsable() || !RHS.isUsable())
12287  return ExprError();
12288 
12289  if (getLangOpts().OpenCL) {
12290  QualType LHSTy = LHSExpr->getType();
12291  QualType RHSTy = RHSExpr->getType();
12292  // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12293  // the ATOMIC_VAR_INIT macro.
12294  if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12295  SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12296  if (BO_Assign == Opc)
12297  Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12298  else
12299  ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12300  return ExprError();
12301  }
12302 
12303  // OpenCL special types - image, sampler, pipe, and blocks are to be used
12304  // only with a builtin functions and therefore should be disallowed here.
12305  if (LHSTy->isImageType() || RHSTy->isImageType() ||
12306  LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12307  LHSTy->isPipeType() || RHSTy->isPipeType() ||
12308  LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12309  ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12310  return ExprError();
12311  }
12312  }
12313 
12314  switch (Opc) {
12315  case BO_Assign:
12316  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12317  if (getLangOpts().CPlusPlus &&
12318  LHS.get()->getObjectKind() != OK_ObjCProperty) {
12319  VK = LHS.get()->getValueKind();
12320  OK = LHS.get()->getObjectKind();
12321  }
12322  if (!ResultTy.isNull()) {
12323  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12324  DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12325  }
12326  RecordModifiableNonNullParam(*this, LHS.get());
12327  break;
12328  case BO_PtrMemD:
12329  case BO_PtrMemI:
12330  ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12331  Opc == BO_PtrMemI);
12332  break;
12333  case BO_Mul:
12334  case BO_Div:
12335  ConvertHalfVec = true;
12336  ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12337  Opc == BO_Div);
12338  break;
12339  case BO_Rem:
12340  ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12341  break;
12342  case BO_Add:
12343  ConvertHalfVec = true;
12344  ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12345  break;
12346  case BO_Sub:
12347  ConvertHalfVec = true;
12348  ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12349  break;
12350  case BO_Shl:
12351  case BO_Shr:
12352  ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12353  break;
12354  case BO_LE:
12355  case BO_LT:
12356  case BO_GE:
12357  case BO_GT:
12358  ConvertHalfVec = true;
12359  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12360  break;
12361  case BO_EQ:
12362  case BO_NE:
12363  ConvertHalfVec = true;
12364  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12365  break;
12366  case BO_Cmp:
12367  ConvertHalfVec = true;
12368  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12369  assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12370  break;
12371  case BO_And:
12372  checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12373  LLVM_FALLTHROUGH;
12374  case BO_Xor:
12375  case BO_Or:
12376  ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12377  break;
12378  case BO_LAnd:
12379  case BO_LOr:
12380  ConvertHalfVec = true;
12381  ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12382  break;
12383  case BO_MulAssign:
12384  case BO_DivAssign:
12385  ConvertHalfVec = true;
12386  CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12387  Opc == BO_DivAssign);
12388  CompLHSTy = CompResultTy;
12389  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12390  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12391  break;
12392  case BO_RemAssign:
12393  CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12394  CompLHSTy = CompResultTy;
12395  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12396  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12397  break;
12398  case BO_AddAssign:
12399  ConvertHalfVec = true;
12400  CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12401  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12402  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12403  break;
12404  case BO_SubAssign:
12405  ConvertHalfVec = true;
12406  CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12407  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12408  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12409  break;
12410  case BO_ShlAssign:
12411  case BO_ShrAssign:
12412  CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12413  CompLHSTy = CompResultTy;
12414  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12415  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12416  break;
12417  case BO_AndAssign:
12418  case BO_OrAssign: // fallthrough
12419  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12420  LLVM_FALLTHROUGH;
12421  case BO_XorAssign:
12422  CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12423  CompLHSTy = CompResultTy;
12424  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12425  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12426  break;
12427  case BO_Comma:
12428  ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12429  if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12430  VK = RHS.get()->getValueKind();
12431  OK = RHS.get()->getObjectKind();
12432  }
12433  break;
12434  }
12435  if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12436  return ExprError();
12437 
12438  // Some of the binary operations require promoting operands of half vector to
12439  // float vectors and truncating the result back to half vector. For now, we do
12440  // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12441  // arm64).
12442  assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12443  isVector(LHS.get()->getType(), Context.HalfTy) &&
12444  "both sides are half vectors or neither sides are");
12445  ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12446  LHS.get()->getType());
12447 
12448  // Check for array bounds violations for both sides of the BinaryOperator
12449  CheckArrayAccess(LHS.get());
12450  CheckArrayAccess(RHS.get());
12451 
12452  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12453  NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12454  &Context.Idents.get("object_setClass"),
12455  SourceLocation(), LookupOrdinaryName);
12456  if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12457  SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12458  Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12459  << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12460  "object_setClass(")
12461  << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12462  ",")
12463  << FixItHint::CreateInsertion(RHSLocEnd, ")");
12464  }
12465  else
12466  Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12467  }
12468  else if (const ObjCIvarRefExpr *OIRE =
12469  dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12470  DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12471 
12472  // Opc is not a compound assignment if CompResultTy is null.
12473  if (CompResultTy.isNull()) {
12474  if (ConvertHalfVec)
12475  return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12476  OpLoc, FPFeatures);
12477  return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12478  OK, OpLoc, FPFeatures);
12479  }
12480 
12481  // Handle compound assignments.
12482  if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12483  OK_ObjCProperty) {
12484  VK = VK_LValue;
12485  OK = LHS.get()->getObjectKind();
12486  }
12487 
12488  if (ConvertHalfVec)
12489  return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12490  OpLoc, FPFeatures);
12491 
12492  return new (Context) CompoundAssignOperator(
12493  LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12494  OpLoc, FPFeatures);
12495 }
12496 
12497 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12498 /// operators are mixed in a way that suggests that the programmer forgot that
12499 /// comparison operators have higher precedence. The most typical example of
12500 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12502  SourceLocation OpLoc, Expr *LHSExpr,
12503  Expr *RHSExpr) {
12504  BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12505  BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12506 
12507  // Check that one of the sides is a comparison operator and the other isn't.
12508  bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12509  bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12510  if (isLeftComp == isRightComp)
12511  return;
12512 
12513  // Bitwise operations are sometimes used as eager logical ops.
12514  // Don't diagnose this.
12515  bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12516  bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12517  if (isLeftBitwise || isRightBitwise)
12518  return;
12519 
12520  SourceRange DiagRange = isLeftComp
12521  ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12522  : SourceRange(OpLoc, RHSExpr->getEndLoc());
12523  StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12524  SourceRange ParensRange =
12525  isLeftComp
12526  ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12527  : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12528 
12529  Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12530  << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12531  SuggestParentheses(Self, OpLoc,
12532  Self.PDiag(diag::note_precedence_silence) << OpStr,
12533  (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12534  SuggestParentheses(Self, OpLoc,
12535  Self.PDiag(diag::note_precedence_bitwise_first)
12537  ParensRange);
12538 }
12539 
12540 /// It accepts a '&&' expr that is inside a '||' one.
12541 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12542 /// in parentheses.
12543 static void
12545  BinaryOperator *Bop) {
12546  assert(Bop->getOpcode() == BO_LAnd);
12547  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12548  << Bop->getSourceRange() << OpLoc;
12549  SuggestParentheses(Self, Bop->getOperatorLoc(),
12550  Self.PDiag(diag::note_precedence_silence)
12551  << Bop->getOpcodeStr(),
12552  Bop->getSourceRange());
12553 }
12554 
12555 /// Returns true if the given expression can be evaluated as a constant
12556 /// 'true'.
12557 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12558  bool Res;
12559  return !E->isValueDependent() &&
12560  E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12561 }
12562 
12563 /// Returns true if the given expression can be evaluated as a constant
12564 /// 'false'.
12565 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12566  bool Res;
12567  return !E->isValueDependent() &&
12568  E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12569 }
12570 
12571 /// Look for '&&' in the left hand of a '||' expr.
12573  Expr *LHSExpr, Expr *RHSExpr) {
12574  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12575  if (Bop->getOpcode() == BO_LAnd) {
12576  // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12577  if (EvaluatesAsFalse(S, RHSExpr))
12578  return;
12579  // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12580  if (!EvaluatesAsTrue(S, Bop->getLHS()))
12581  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12582  } else if (Bop->getOpcode() == BO_LOr) {
12583  if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12584  // If it's "a || b && 1 || c" we didn't warn earlier for
12585  // "a || b && 1", but warn now.
12586  if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12587  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12588  }
12589  }
12590  }
12591 }
12592 
12593 /// Look for '&&' in the right hand of a '||' expr.
12595  Expr *LHSExpr, Expr *RHSExpr) {
12596  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12597  if (Bop->getOpcode() == BO_LAnd) {
12598  // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12599  if (EvaluatesAsFalse(S, LHSExpr))
12600  return;
12601  // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12602  if (!EvaluatesAsTrue(S, Bop->getRHS()))
12603  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12604  }
12605  }
12606 }
12607 
12608 /// Look for bitwise op in the left or right hand of a bitwise op with
12609 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12610 /// the '&' expression in parentheses.
12612  SourceLocation OpLoc, Expr *SubExpr) {
12613  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12614  if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12615  S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12616  << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12617  << Bop->getSourceRange() << OpLoc;
12618  SuggestParentheses(S, Bop->getOperatorLoc(),
12619  S.PDiag(diag::note_precedence_silence)
12620  << Bop->getOpcodeStr(),
12621  Bop->getSourceRange());
12622  }
12623  }
12624 }
12625 
12627  Expr *SubExpr, StringRef Shift) {
12628  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12629  if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12630  StringRef Op = Bop->getOpcodeStr();
12631  S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12632  << Bop->getSourceRange() << OpLoc << Shift << Op;
12633  SuggestParentheses(S, Bop->getOperatorLoc(),
12634  S.PDiag(diag::note_precedence_silence) << Op,
12635  Bop->getSourceRange());
12636  }
12637  }
12638 }
12639 
12641  Expr *LHSExpr, Expr *RHSExpr) {
12642  CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12643  if (!OCE)
12644  return;
12645 
12646  FunctionDecl *FD = OCE->getDirectCallee();
12647  if (!FD || !FD->isOverloadedOperator())
12648  return;
12649 
12651  if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12652  return;
12653 
12654  S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12655  << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12656  << (Kind == OO_LessLess);
12658  S.PDiag(diag::note_precedence_silence)
12659  << (Kind == OO_LessLess ? "<<" : ">>"),
12660  OCE->getSourceRange());
12662  S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12663  SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12664 }
12665 
12666 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12667 /// precedence.
12669  SourceLocation OpLoc, Expr *LHSExpr,
12670  Expr *RHSExpr){
12671  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12672  if (BinaryOperator::isBitwiseOp(Opc))
12673  DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12674 
12675  // Diagnose "arg1 & arg2 | arg3"
12676  if ((Opc == BO_Or || Opc == BO_Xor) &&
12677  !OpLoc.isMacroID()/* Don't warn in macros. */) {
12678  DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12679  DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12680  }
12681 
12682  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12683  // We don't warn for 'assert(a || b && "bad")' since this is safe.
12684  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12685  DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12686  DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12687  }
12688 
12689  if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12690  || Opc == BO_Shr) {
12691  StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12692  DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12693  DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12694  }
12695 
12696  // Warn on overloaded shift operators and comparisons, such as:
12697  // cout << 5 == 4;
12699  DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12700 }
12701 
12702 // Binary Operators. 'Tok' is the token for the operator.
12704  tok::TokenKind Kind,
12705  Expr *LHSExpr, Expr *RHSExpr) {
12706  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12707  assert(LHSExpr && "ActOnBinOp(): missing left expression");
12708  assert(RHSExpr && "ActOnBinOp(): missing right expression");
12709 
12710  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12711  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12712 
12713  return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12714 }
12715 
12716 /// Build an overloaded binary operator expression in the given scope.
12718  BinaryOperatorKind Opc,
12719  Expr *LHS, Expr *RHS) {
12720  switch (Opc) {
12721  case BO_Assign:
12722  case BO_DivAssign:
12723  case BO_RemAssign:
12724  case BO_SubAssign:
12725  case BO_AndAssign:
12726  case BO_OrAssign:
12727  case BO_XorAssign:
12728  DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12729  CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12730  break;
12731  default:
12732  break;
12733  }
12734 
12735  // Find all of the overloaded operators visible from this
12736  // point. We perform both an operator-name lookup from the local
12737  // scope and an argument-dependent lookup based on the types of
12738  // the arguments.
12739  UnresolvedSet<16> Functions;
12740  OverloadedOperatorKind OverOp
12742  if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12743  S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12744  RHS->getType(), Functions);
12745 
12746  // Build the (potentially-overloaded, potentially-dependent)
12747  // binary operation.
12748  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12749 }
12750 
12752  BinaryOperatorKind Opc,
12753  Expr *LHSExpr, Expr *RHSExpr) {
12754  ExprResult LHS, RHS;
12755  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12756  if (!LHS.isUsable() || !RHS.isUsable())
12757  return ExprError();
12758  LHSExpr = LHS.get();
12759  RHSExpr = RHS.get();
12760 
12761  // We want to end up calling one of checkPseudoObjectAssignment
12762  // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12763  // both expressions are overloadable or either is type-dependent),
12764  // or CreateBuiltinBinOp (in any other case). We also want to get
12765  // any placeholder types out of the way.
12766 
12767  // Handle pseudo-objects in the LHS.
12768  if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12769  // Assignments with a pseudo-object l-value need special analysis.
12770  if (pty->getKind() == BuiltinType::PseudoObject &&
12772  return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12773 
12774  // Don't resolve overloads if the other type is overloadable.
12775  if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12776  // We can't actually test that if we still have a placeholder,
12777  // though. Fortunately, none of the exceptions we see in that
12778  // code below are valid when the LHS is an overload set. Note
12779  // that an overload set can be dependently-typed, but it never
12780  // instantiates to having an overloadable type.
12781  ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12782  if (resolvedRHS.isInvalid()) return ExprError();
12783  RHSExpr = resolvedRHS.get();
12784 
12785  if (RHSExpr->isTypeDependent() ||
12786  RHSExpr->getType()->isOverloadableType())
12787  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12788  }
12789 
12790  // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12791  // template, diagnose the missing 'template' keyword instead of diagnosing
12792  // an invalid use of a bound member function.
12793  //
12794  // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12795  // to C++1z [over.over]/1.4, but we already checked for that case above.
12796  if (Opc == BO_LT && inTemplateInstantiation() &&
12797  (pty->getKind() == BuiltinType::BoundMember ||
12798  pty->getKind() == BuiltinType::Overload)) {
12799  auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12800  if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12801  std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12802  return isa<FunctionTemplateDecl>(ND);
12803  })) {
12804  Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12805  : OE->getNameLoc(),
12806  diag::err_template_kw_missing)
12807  << OE->getName().getAsString() << "";
12808  return ExprError();
12809  }
12810  }
12811 
12812  ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12813  if (LHS.isInvalid()) return ExprError();
12814  LHSExpr = LHS.get();
12815  }
12816 
12817  // Handle pseudo-objects in the RHS.
12818  if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12819  // An overload in the RHS can potentially be resolved by the type
12820  // being assigned to.
12821  if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12822  if (getLangOpts().CPlusPlus &&
12823  (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12824  LHSExpr->getType()->isOverloadableType()))
12825  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12826 
12827  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12828  }
12829 
12830  // Don't resolve overloads if the other type is overloadable.
12831  if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12832  LHSExpr->getType()->isOverloadableType())
12833  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12834 
12835  ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12836  if (!resolvedRHS.isUsable()) return ExprError();
12837  RHSExpr = resolvedRHS.get();
12838  }
12839 
12840  if (getLangOpts().CPlusPlus) {
12841  // If either expression is type-dependent, always build an
12842  // overloaded op.
12843  if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12844  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12845 
12846  // Otherwise, build an overloaded op if either expression has an
12847  // overloadable type.
12848  if (LHSExpr->getType()->isOverloadableType() ||
12849  RHSExpr->getType()->isOverloadableType())
12850  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12851  }
12852 
12853  // Build a built-in binary operation.
12854  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12855 }
12856 
12858  if (T.isNull() || T->isDependentType())
12859  return false;
12860 
12861  if (!T->isPromotableIntegerType())
12862  return true;
12863 
12864  return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12865 }
12866 
12868  UnaryOperatorKind Opc,
12869  Expr *InputExpr) {
12870  ExprResult Input = InputExpr;
12871  ExprValueKind VK = VK_RValue;
12873  QualType resultType;
12874  bool CanOverflow = false;
12875 
12876  bool ConvertHalfVec = false;
12877  if (getLangOpts().OpenCL) {
12878  QualType Ty = InputExpr->getType();
12879  // The only legal unary operation for atomics is '&'.
12880  if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12881  // OpenCL special types - image, sampler, pipe, and blocks are to be used
12882  // only with a builtin functions and therefore should be disallowed here.
12883  (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12884  || Ty->isBlockPointerType())) {
12885  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12886  << InputExpr->getType()
12887  << Input.get()->getSourceRange());
12888  }
12889  }
12890  switch (Opc) {
12891  case UO_PreInc:
12892  case UO_PreDec:
12893  case UO_PostInc:
12894  case UO_PostDec:
12895  resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12896  OpLoc,
12897  Opc == UO_PreInc ||
12898  Opc == UO_PostInc,
12899  Opc == UO_PreInc ||
12900  Opc == UO_PreDec);
12901  CanOverflow = isOverflowingIntegerType(Context, resultType);
12902  break;
12903  case UO_AddrOf:
12904  resultType = CheckAddressOfOperand(Input, OpLoc);
12905  CheckAddressOfNoDeref(InputExpr);
12906  RecordModifiableNonNullParam(*this, InputExpr);
12907  break;
12908  case UO_Deref: {
12909  Input = DefaultFunctionArrayLvalueConversion(Input.get());
12910  if (Input.isInvalid()) return ExprError();
12911  resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12912  break;
12913  }
12914  case UO_Plus:
12915  case UO_Minus:
12916  CanOverflow = Opc == UO_Minus &&
12917  isOverflowingIntegerType(Context, Input.get()->getType());
12918  Input = UsualUnaryConversions(Input.get());
12919  if (Input.isInvalid()) return ExprError();
12920  // Unary plus and minus require promoting an operand of half vector to a
12921  // float vector and truncating the result back to a half vector. For now, we
12922  // do this only when HalfArgsAndReturns is set (that is, when the target is
12923  // arm or arm64).
12924  ConvertHalfVec =
12925  needsConversionOfHalfVec(true, Context, Input.get()->getType());
12926 
12927  // If the operand is a half vector, promote it to a float vector.
12928  if (ConvertHalfVec)
12929  Input = convertVector(Input.get(), Context.FloatTy, *this);
12930  resultType = Input.get()->getType();
12931  if (resultType->isDependentType())
12932  break;
12933  if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12934  break;
12935  else if (resultType->isVectorType() &&
12936  // The z vector extensions don't allow + or - with bool vectors.
12937  (!Context.getLangOpts().ZVector ||
12938  resultType->getAs<VectorType>()->getVectorKind() !=
12940  break;
12941  else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12942  Opc == UO_Plus &&
12943  resultType->isPointerType())
12944  break;
12945 
12946  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12947  << resultType << Input.get()->getSourceRange());
12948 
12949  case UO_Not: // bitwise complement
12950  Input = UsualUnaryConversions(Input.get());
12951  if (Input.isInvalid())
12952  return ExprError();
12953  resultType = Input.get()->getType();
12954 
12955  if (resultType->isDependentType())
12956  break;
12957  // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12958  if (resultType->isComplexType() || resultType->isComplexIntegerType())
12959  // C99 does not support '~' for complex conjugation.
12960  Diag(OpLoc, diag::ext_integer_complement_complex)
12961  << resultType << Input.get()->getSourceRange();
12962  else if (resultType->hasIntegerRepresentation())
12963  break;
12964  else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12965  // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12966  // on vector float types.
12967  QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12968  if (!T->isIntegerType())
12969  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12970  << resultType << Input.get()->getSourceRange());
12971  } else {
12972  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12973  << resultType << Input.get()->getSourceRange());
12974  }
12975  break;
12976 
12977  case UO_LNot: // logical negation
12978  // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12979  Input = DefaultFunctionArrayLvalueConversion(Input.get());
12980  if (Input.isInvalid()) return ExprError();
12981  resultType = Input.get()->getType();
12982 
12983  // Though we still have to promote half FP to float...
12984  if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12985  Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12986  resultType = Context.FloatTy;
12987  }
12988 
12989  if (resultType->isDependentType())
12990  break;
12991  if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12992  // C99 6.5.3.3p1: ok, fallthrough;
12993  if (Context.getLangOpts().CPlusPlus) {
12994  // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12995  // operand contextually converted to bool.
12996  Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12997  ScalarTypeToBooleanCastKind(resultType));
12998  } else if (Context.getLangOpts().OpenCL &&
12999  Context.getLangOpts().OpenCLVersion < 120) {
13000  // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13001  // operate on scalar float types.
13002  if (!resultType->isIntegerType() && !resultType->isPointerType())
13003  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13004  << resultType << Input.get()->getSourceRange());
13005  }
13006  } else if (resultType->isExtVectorType()) {
13007  if (Context.getLangOpts().OpenCL &&
13008  Context.getLangOpts().OpenCLVersion < 120) {
13009  // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13010  // operate on vector float types.
13011  QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13012  if (!T->isIntegerType())
13013  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13014  << resultType << Input.get()->getSourceRange());
13015  }
13016  // Vector logical not returns the signed variant of the operand type.
13017  resultType = GetSignedVectorType(resultType);
13018  break;
13019  } else {
13020  // FIXME: GCC's vector extension permits the usage of '!' with a vector
13021  // type in C++. We should allow that here too.
13022  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13023  << resultType << Input.get()->getSourceRange());
13024  }
13025 
13026  // LNot always has type int. C99 6.5.3.3p5.
13027  // In C++, it's bool. C++ 5.3.1p8
13028  resultType = Context.getLogicalOperationType();
13029  break;
13030  case UO_Real:
13031  case UO_Imag:
13032  resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13033  // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13034  // complex l-values to ordinary l-values and all other values to r-values.
13035  if (Input.isInvalid()) return ExprError();
13036  if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13037  if (Input.get()->getValueKind() != VK_RValue &&
13038  Input.get()->getObjectKind() == OK_Ordinary)
13039  VK = Input.get()->getValueKind();
13040  } else if (!getLangOpts().CPlusPlus) {
13041  // In C, a volatile scalar is read by __imag. In C++, it is not.
13042  Input = DefaultLvalueConversion(Input.get());
13043  }
13044  break;
13045  case UO_Extension:
13046  resultType = Input.get()->getType();
13047  VK = Input.get()->getValueKind();
13048  OK = Input.get()->getObjectKind();
13049  break;
13050  case UO_Coawait:
13051  // It's unnecessary to represent the pass-through operator co_await in the
13052  // AST; just return the input expression instead.
13053  assert(!Input.get()->getType()->isDependentType() &&
13054  "the co_await expression must be non-dependant before "
13055  "building operator co_await");
13056  return Input;
13057  }
13058  if (resultType.isNull() || Input.isInvalid())
13059  return ExprError();
13060 
13061  // Check for array bounds violations in the operand of the UnaryOperator,
13062  // except for the '*' and '&' operators that have to be handled specially
13063  // by CheckArrayAccess (as there are special cases like &array[arraysize]
13064  // that are explicitly defined as valid by the standard).
13065  if (Opc != UO_AddrOf && Opc != UO_Deref)
13066  CheckArrayAccess(Input.get());
13067 
13068  auto *UO = new (Context)
13069  UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13070 
13071  if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13072  !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13073  ExprEvalContexts.back().PossibleDerefs.insert(UO);
13074 
13075  // Convert the result back to a half vector.
13076  if (ConvertHalfVec)
13077  return convertVector(UO, Context.HalfTy, *this);
13078  return UO;
13079 }
13080 
13081 /// Determine whether the given expression is a qualified member
13082 /// access expression, of a form that could be turned into a pointer to member
13083 /// with the address-of operator.
13085  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13086  if (!DRE->getQualifier())
13087  return false;
13088 
13089  ValueDecl *VD = DRE->getDecl();
13090  if (!VD->isCXXClassMember())
13091  return false;
13092 
13093  if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13094  return true;
13095  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13096  return Method->isInstance();
13097 
13098  return false;
13099  }
13100 
13101  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13102  if (!ULE->getQualifier())
13103  return false;
13104 
13105  for (NamedDecl *D : ULE->decls()) {
13106  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13107  if (Method->isInstance())
13108  return true;
13109  } else {
13110  // Overload set does not contain methods.
13111  break;
13112  }
13113  }
13114 
13115  return false;
13116  }
13117 
13118  return false;
13119 }
13120 
13122  UnaryOperatorKind Opc, Expr *Input) {
13123  // First things first: handle placeholders so that the
13124  // overloaded-operator check considers the right type.
13125  if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13126  // Increment and decrement of pseudo-object references.
13127  if (pty->getKind() == BuiltinType::PseudoObject &&
13129  return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13130 
13131  // extension is always a builtin operator.
13132  if (Opc == UO_Extension)
13133  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13134 
13135  // & gets special logic for several kinds of placeholder.
13136  // The builtin code knows what to do.
13137  if (Opc == UO_AddrOf &&
13138  (pty->getKind() == BuiltinType::Overload ||
13139  pty->getKind() == BuiltinType::UnknownAny ||
13140  pty->getKind() == BuiltinType::BoundMember))
13141  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13142 
13143  // Anything else needs to be handled now.
13144  ExprResult Result = CheckPlaceholderExpr(Input);
13145  if (Result.isInvalid()) return ExprError();
13146  Input = Result.get();
13147  }
13148 
13149  if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13151  !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13152  // Find all of the overloaded operators visible from this
13153  // point. We perform both an operator-name lookup from the local
13154  // scope and an argument-dependent lookup based on the types of
13155  // the arguments.
13156  UnresolvedSet<16> Functions;
13158  if (S && OverOp != OO_None)
13159  LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13160  Functions);
13161 
13162  return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13163  }
13164 
13165  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13166 }
13167 
13168 // Unary Operators. 'Tok' is the token for the operator.
13170  tok::TokenKind Op, Expr *Input) {
13171  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13172 }
13173 
13174 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13176  LabelDecl *TheDecl) {
13177  TheDecl->markUsed(Context);
13178  // Create the AST node. The address of a label always has type 'void*'.
13179  return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13180  Context.getPointerType(Context.VoidTy));
13181 }
13182 
13183 /// Given the last statement in a statement-expression, check whether
13184 /// the result is a producing expression (like a call to an
13185 /// ns_returns_retained function) and, if so, rebuild it to hoist the
13186 /// release out of the full-expression. Otherwise, return null.
13187 /// Cannot fail.
13189  // Should always be wrapped with one of these.
13190  ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
13191  if (!cleanups) return nullptr;
13192 
13193  ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
13194  if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
13195  return nullptr;
13196 
13197  // Splice out the cast. This shouldn't modify any interesting
13198  // features of the statement.
13199  Expr *producer = cast->getSubExpr();
13200  assert(producer->getType() == cast->getType());
13201  assert(producer->getValueKind() == cast->getValueKind());
13202  cleanups->setSubExpr(producer);
13203  return cleanups;
13204 }
13205 
13207  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13208 }
13209 
13211  // Note that function is also called by TreeTransform when leaving a
13212  // StmtExpr scope without rebuilding anything.
13213 
13214  DiscardCleanupsInEvaluationContext();
13215  PopExpressionEvaluationContext();
13216 }
13217 
13218 ExprResult
13220  SourceLocation RPLoc) { // "({..})"
13221  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13222  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13223 
13224  if (hasAnyUnrecoverableErrorsInThisFunction())
13225  DiscardCleanupsInEvaluationContext();
13226  assert(!Cleanup.exprNeedsCleanups() &&
13227  "cleanups within StmtExpr not correctly bound!");
13228  PopExpressionEvaluationContext();
13229 
13230  // FIXME: there are a variety of strange constraints to enforce here, for
13231  // example, it is not possible to goto into a stmt expression apparently.
13232  // More semantic analysis is needed.
13233 
13234  // If there are sub-stmts in the compound stmt, take the type of the last one
13235  // as the type of the stmtexpr.
13236  QualType Ty = Context.VoidTy;
13237  bool StmtExprMayBindToTemp = false;
13238  if (!Compound->body_empty()) {
13239  Stmt *LastStmt = Compound->body_back();
13240  LabelStmt *LastLabelStmt = nullptr;
13241  // If LastStmt is a label, skip down through into the body.
13242  while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
13243  LastLabelStmt = Label;
13244  LastStmt = Label->getSubStmt();
13245  }
13246 
13247  if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
13248  // Do function/array conversion on the last expression, but not
13249  // lvalue-to-rvalue. However, initialize an unqualified type.
13250  ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
13251  if (LastExpr.isInvalid())
13252  return ExprError();
13253  Ty = LastExpr.get()->getType().getUnqualifiedType();
13254 
13255  if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
13256  // In ARC, if the final expression ends in a consume, splice
13257  // the consume out and bind it later. In the alternate case
13258  // (when dealing with a retainable type), the result
13259  // initialization will create a produce. In both cases the
13260  // result will be +1, and we'll need to balance that out with
13261  // a bind.
13262  if (Expr *rebuiltLastStmt
13263  = maybeRebuildARCConsumingStmt(LastExpr.get())) {
13264  LastExpr = rebuiltLastStmt;
13265  } else {
13266  LastExpr = PerformCopyInitialization(
13268  SourceLocation(), LastExpr);
13269  }
13270 
13271  if (LastExpr.isInvalid())
13272  return ExprError();
13273  if (LastExpr.get() != nullptr) {
13274  if (!LastLabelStmt)
13275  Compound->setLastStmt(LastExpr.get());
13276  else
13277  LastLabelStmt->setSubStmt(LastExpr.get());
13278  StmtExprMayBindToTemp = true;
13279  }
13280  }
13281  }
13282  }
13283 
13284  // FIXME: Check that expression type is complete/non-abstract; statement
13285  // expressions are not lvalues.
13286  Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13287  if (StmtExprMayBindToTemp)
13288  return MaybeBindToTemporary(ResStmtExpr);
13289  return ResStmtExpr;
13290 }
13291 
13293  TypeSourceInfo *TInfo,
13294  ArrayRef<OffsetOfComponent> Components,
13295  SourceLocation RParenLoc) {
13296  QualType ArgTy = TInfo->getType();
13297  bool Dependent = ArgTy->isDependentType();
13298  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13299 
13300  // We must have at least one component that refers to the type, and the first
13301  // one is known to be a field designator. Verify that the ArgTy represents
13302  // a struct/union/class.
13303  if (!Dependent && !ArgTy->isRecordType())
13304  return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13305  << ArgTy << TypeRange);
13306 
13307  // Type must be complete per C99 7.17p3 because a declaring a variable
13308  // with an incomplete type would be ill-formed.
13309  if (!Dependent
13310  && RequireCompleteType(BuiltinLoc, ArgTy,
13311  diag::err_offsetof_incomplete_type, TypeRange))
13312  return ExprError();
13313 
13314  bool DidWarnAboutNonPOD = false;
13315  QualType CurrentType = ArgTy;
13317  SmallVector<Expr*, 4> Exprs;
13318  for (const OffsetOfComponent &OC : Components) {
13319  if (OC.isBrackets) {
13320  // Offset of an array sub-field. TODO: Should we allow vector elements?
13321  if (!CurrentType->isDependentType()) {
13322  const ArrayType *AT = Context.getAsArrayType(CurrentType);
13323  if(!AT)
13324  return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13325  << CurrentType);
13326  CurrentType = AT->getElementType();
13327  } else
13328  CurrentType = Context.DependentTy;
13329 
13330  ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13331  if (IdxRval.isInvalid())
13332  return ExprError();
13333  Expr *Idx = IdxRval.get();
13334 
13335  // The expression must be an integral expression.
13336  // FIXME: An integral constant expression?
13337  if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13338  !Idx->getType()->isIntegerType())
13339  return ExprError(
13340  Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13341  << Idx->getSourceRange());
13342 
13343  // Record this array index.
13344  Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13345  Exprs.push_back(Idx);
13346  continue;
13347  }
13348 
13349  // Offset of a field.
13350  if (CurrentType->isDependentType()) {
13351  // We have the offset of a field, but we can't look into the dependent
13352  // type. Just record the identifier of the field.
13353  Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13354  CurrentType = Context.DependentTy;
13355  continue;
13356  }
13357 
13358  // We need to have a complete type to look into.
13359  if (RequireCompleteType(OC.LocStart, CurrentType,
13360  diag::err_offsetof_incomplete_type))
13361  return ExprError();
13362 
13363  // Look for the designated field.
13364  const RecordType *RC = CurrentType->getAs<RecordType>();
13365  if (!RC)
13366  return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13367  << CurrentType);
13368  RecordDecl *RD = RC->getDecl();
13369 
13370  // C++ [lib.support.types]p5:
13371  // The macro offsetof accepts a restricted set of type arguments in this
13372  // International Standard. type shall be a POD structure or a POD union
13373  // (clause 9).
13374  // C++11 [support.types]p4:
13375  // If type is not a standard-layout class (Clause 9), the results are
13376  // undefined.
13377  if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13378  bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13379  unsigned DiagID =
13380  LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13381  : diag::ext_offsetof_non_pod_type;
13382 
13383  if (!IsSafe && !DidWarnAboutNonPOD &&
13384  DiagRuntimeBehavior(BuiltinLoc, nullptr,
13385  PDiag(DiagID)
13386  << SourceRange(Components[0].LocStart, OC.LocEnd)
13387  << CurrentType))
13388  DidWarnAboutNonPOD = true;
13389  }
13390 
13391  // Look for the field.
13392  LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13393  LookupQualifiedName(R, RD);
13394  FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13395  IndirectFieldDecl *IndirectMemberDecl = nullptr;
13396  if (!MemberDecl) {
13397  if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13398  MemberDecl = IndirectMemberDecl->getAnonField();
13399  }
13400 
13401  if (!MemberDecl)
13402  return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13403  << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13404  OC.LocEnd));
13405 
13406  // C99 7.17p3:
13407  // (If the specified member is a bit-field, the behavior is undefined.)
13408  //
13409  // We diagnose this as an error.
13410  if (MemberDecl->isBitField()) {
13411  Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13412  << MemberDecl->getDeclName()
13413  << SourceRange(BuiltinLoc, RParenLoc);
13414  Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13415  return ExprError();
13416  }
13417 
13418  RecordDecl *Parent = MemberDecl->getParent();
13419  if (IndirectMemberDecl)
13420  Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13421 
13422  // If the member was found in a base class, introduce OffsetOfNodes for
13423  // the base class indirections.
13424  CXXBasePaths Paths;
13425  if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13426  Paths)) {
13427  if (Paths.getDetectedVirtual()) {
13428  Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13429  << MemberDecl->getDeclName()
13430  << SourceRange(BuiltinLoc, RParenLoc);
13431  return ExprError();
13432  }
13433 
13434  CXXBasePath &Path = Paths.front();
13435  for (const CXXBasePathElement &B : Path)
13436  Comps.push_back(OffsetOfNode(B.Base));
13437  }
13438 
13439  if (IndirectMemberDecl) {
13440  for (auto *FI : IndirectMemberDecl->chain()) {
13441  assert(isa<FieldDecl>(FI));
13442  Comps.push_back(OffsetOfNode(OC.LocStart,
13443  cast<FieldDecl>(FI), OC.LocEnd));
13444  }
13445  } else
13446  Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13447 
13448  CurrentType = MemberDecl->getType().getNonReferenceType();
13449  }
13450 
13451  return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13452  Comps, Exprs, RParenLoc);
13453 }
13454 
13456  SourceLocation BuiltinLoc,
13458  ParsedType ParsedArgTy,
13459  ArrayRef<OffsetOfComponent> Components,
13460  SourceLocation RParenLoc) {
13461 
13462  TypeSourceInfo *ArgTInfo;
13463  QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13464  if (ArgTy.isNull())
13465  return ExprError();
13466 
13467  if (!ArgTInfo)
13468  ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13469 
13470  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13471 }
13472 
13473 
13475  Expr *CondExpr,
13476  Expr *LHSExpr, Expr *RHSExpr,
13477  SourceLocation RPLoc) {
13478  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13479 
13480  ExprValueKind VK = VK_RValue;
13482  QualType resType;
13483  bool ValueDependent = false;
13484  bool CondIsTrue = false;
13485  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13486  resType = Context.DependentTy;
13487  ValueDependent = true;
13488  } else {
13489  // The conditional expression is required to be a constant expression.
13490  llvm::APSInt condEval(32);
13491  ExprResult CondICE
13492  = VerifyIntegerConstantExpression(CondExpr, &condEval,
13493  diag::err_typecheck_choose_expr_requires_constant, false);
13494  if (CondICE.isInvalid())
13495  return ExprError();
13496  CondExpr = CondICE.get();
13497  CondIsTrue = condEval.getZExtValue();
13498 
13499  // If the condition is > zero, then the AST type is the same as the LHSExpr.
13500  Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13501 
13502  resType = ActiveExpr->getType();
13503  ValueDependent = ActiveExpr->isValueDependent();
13504  VK = ActiveExpr->getValueKind();
13505  OK = ActiveExpr->getObjectKind();
13506  }
13507 
13508  return new (Context)
13509  ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13510  CondIsTrue, resType->isDependentType(), ValueDependent);
13511 }
13512 
13513 //===----------------------------------------------------------------------===//
13514 // Clang Extensions.
13515 //===----------------------------------------------------------------------===//
13516 
13517 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13518 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13519  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13520 
13521  if (LangOpts.CPlusPlus) {
13522  Decl *ManglingContextDecl;
13523  if (MangleNumberingContext *MCtx =
13524  getCurrentMangleNumberContext(Block->getDeclContext(),
13525  ManglingContextDecl)) {
13526  unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13527  Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13528  }
13529  }
13530 
13531  PushBlockScope(CurScope, Block);
13532  CurContext->addDecl(Block);
13533  if (CurScope)
13534  PushDeclContext(CurScope, Block);
13535  else
13536  CurContext = Block;
13537 
13538  getCurBlock()->HasImplicitReturnType = true;
13539 
13540  // Enter a new evaluation context to insulate the block from any
13541  // cleanups from the enclosing full-expression.
13542  PushExpressionEvaluationContext(
13543  ExpressionEvaluationContext::PotentiallyEvaluated);
13544 }
13545 
13547  Scope *CurScope) {
13548  assert(ParamInfo.getIdentifier() == nullptr &&
13549  "block-id should have no identifier!");
13550  assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13551  BlockScopeInfo *CurBlock = getCurBlock();
13552 
13553  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13554  QualType T = Sig->getType();
13555 
13556  // FIXME: We should allow unexpanded parameter packs here, but that would,
13557  // in turn, make the block expression contain unexpanded parameter packs.
13558  if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13559  // Drop the parameters.
13561  EPI.HasTrailingReturn = false;
13562  EPI.TypeQuals.addConst();
13563  T = Context.getFunctionType(Context.DependentTy, None, EPI);
13564  Sig = Context.getTrivialTypeSourceInfo(T);
13565  }
13566 
13567  // GetTypeForDeclarator always produces a function type for a block
13568  // literal signature. Furthermore, it is always a FunctionProtoType
13569  // unless the function was written with a typedef.
13570  assert(T->isFunctionType() &&
13571  "GetTypeForDeclarator made a non-function block signature");
13572 
13573  // Look for an explicit signature in that function type.
13574  FunctionProtoTypeLoc ExplicitSignature;
13575 
13576  if ((ExplicitSignature =
13578 
13579  // Check whether that explicit signature was synthesized by
13580  // GetTypeForDeclarator. If so, don't save that as part of the
13581  // written signature.
13582  if (ExplicitSignature.getLocalRangeBegin() ==
13583  ExplicitSignature.getLocalRangeEnd()) {
13584  // This would be much cheaper if we stored TypeLocs instead of
13585  // TypeSourceInfos.
13586  TypeLoc Result = ExplicitSignature.getReturnLoc();
13587  unsigned Size = Result.getFullDataSize();
13588  Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13589  Sig->getTypeLoc().initializeFullCopy(Result, Size);
13590 
13591  ExplicitSignature = FunctionProtoTypeLoc();
13592  }
13593  }
13594 
13595  CurBlock->TheDecl->setSignatureAsWritten(Sig);
13596  CurBlock->FunctionType = T;
13597 
13598  const FunctionType *Fn = T->getAs<FunctionType>();
13599  QualType RetTy = Fn->getReturnType();
13600  bool isVariadic =
13601  (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13602 
13603  CurBlock->TheDecl->setIsVariadic(isVariadic);
13604 
13605  // Context.DependentTy is used as a placeholder for a missing block
13606  // return type. TODO: what should we do with declarators like:
13607  // ^ * { ... }
13608  // If the answer is "apply template argument deduction"....
13609  if (RetTy != Context.DependentTy) {
13610  CurBlock->ReturnType = RetTy;
13611  CurBlock->TheDecl->setBlockMissingReturnType(false);
13612  CurBlock->HasImplicitReturnType = false;
13613  }
13614 
13615  // Push block parameters from the declarator if we had them.
13617  if (ExplicitSignature) {
13618  for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13619  ParmVarDecl *Param = ExplicitSignature.getParam(I);
13620  if (Param->getIdentifier() == nullptr &&
13621  !Param->isImplicit() &&
13622  !Param->isInvalidDecl() &&
13623  !getLangOpts().CPlusPlus)
13624  Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13625  Params.push_back(Param);
13626  }
13627 
13628  // Fake up parameter variables if we have a typedef, like
13629  // ^ fntype { ... }
13630  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13631  for (const auto &I : Fn->param_types()) {
13632  ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13633  CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13634  Params.push_back(Param);
13635  }
13636  }
13637 
13638  // Set the parameters on the block decl.
13639  if (!Params.empty()) {
13640  CurBlock->TheDecl->setParams(Params);
13641  CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13642  /*CheckParameterNames=*/false);
13643  }
13644 
13645  // Finally we can process decl attributes.
13646  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13647 
13648  // Put the parameter variables in scope.
13649  for (auto AI : CurBlock->TheDecl->parameters()) {
13650  AI->setOwningFunction(CurBlock->TheDecl);
13651 
13652  // If this has an identifier, add it to the scope stack.
13653  if (AI->getIdentifier()) {
13654  CheckShadow(CurBlock->TheScope, AI);
13655 
13656  PushOnScopeChains(AI, CurBlock->TheScope);
13657  }
13658  }
13659 }
13660 
13661 /// ActOnBlockError - If there is an error parsing a block, this callback
13662 /// is invoked to pop the information about the block from the action impl.
13663 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13664  // Leave the expression-evaluation context.
13665  DiscardCleanupsInEvaluationContext();
13666  PopExpressionEvaluationContext();
13667 
13668  // Pop off CurBlock, handle nested blocks.
13669  PopDeclContext();
13670  PopFunctionScopeInfo();
13671 }
13672 
13673 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13674 /// literal was successfully completed. ^(int x){...}
13676  Stmt *Body, Scope *CurScope) {
13677  // If blocks are disabled, emit an error.
13678  if (!LangOpts.Blocks)
13679  Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13680 
13681  // Leave the expression-evaluation context.
13682  if (hasAnyUnrecoverableErrorsInThisFunction())
13683  DiscardCleanupsInEvaluationContext();
13684  assert(!Cleanup.exprNeedsCleanups() &&
13685  "cleanups within block not correctly bound!");
13686  PopExpressionEvaluationContext();
13687 
13688  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13689  BlockDecl *BD = BSI->TheDecl;
13690 
13691  if (BSI->HasImplicitReturnType)
13692  deduceClosureReturnType(*BSI);
13693 
13694  PopDeclContext();
13695 
13696  QualType RetTy = Context.VoidTy;
13697  if (!BSI->ReturnType.isNull())
13698  RetTy = BSI->ReturnType;
13699 
13700  bool NoReturn = BD->hasAttr<NoReturnAttr>();
13701  QualType BlockTy;
13702 
13703  // Set the captured variables on the block.
13704  // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13706  for (Capture &Cap : BSI->Captures) {
13707  if (Cap.isThisCapture())
13708  continue;
13709  BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13710  Cap.isNested(), Cap.getInitExpr());
13711  Captures.push_back(NewCap);
13712  }
13713  BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13714 
13715  // If the user wrote a function type in some form, try to use that.
13716  if (!BSI->FunctionType.isNull()) {
13717  const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13718 
13719  FunctionType::ExtInfo Ext = FTy->getExtInfo();
13720  if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13721 
13722  // Turn protoless block types into nullary block types.
13723  if (isa<FunctionNoProtoType>(FTy)) {
13725  EPI.ExtInfo = Ext;
13726  BlockTy = Context.getFunctionType(RetTy, None, EPI);
13727 
13728  // Otherwise, if we don't need to change anything about the function type,
13729  // preserve its sugar structure.
13730  } else if (FTy->getReturnType() == RetTy &&
13731  (!NoReturn || FTy->getNoReturnAttr())) {
13732  BlockTy = BSI->FunctionType;
13733 
13734  // Otherwise, make the minimal modifications to the function type.
13735  } else {
13736  const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13738  EPI.TypeQuals = Qualifiers();
13739  EPI.ExtInfo = Ext;
13740  BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13741  }
13742 
13743  // If we don't have a function type, just build one from nothing.
13744  } else {
13746  EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13747  BlockTy = Context.getFunctionType(RetTy, None, EPI);
13748  }
13749 
13750  DiagnoseUnusedParameters(BD->parameters());
13751  BlockTy = Context.getBlockPointerType(BlockTy);
13752 
13753  // If needed, diagnose invalid gotos and switches in the block.
13754  if (getCurFunction()->NeedsScopeChecking() &&
13755  !PP.isCodeCompletionEnabled())
13756  DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13757 
13758  BD->setBody(cast<CompoundStmt>(Body));
13759 
13760  if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13761  DiagnoseUnguardedAvailabilityViolations(BD);
13762 
13763  // Try to apply the named return value optimization. We have to check again
13764  // if we can do this, though, because blocks keep return statements around
13765  // to deduce an implicit return type.
13766  if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13767  !BD->isDependentContext())
13768  computeNRVO(Body, BSI);
13769 
13770  BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13771  AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13772  PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13773 
13774  // If the block isn't obviously global, i.e. it captures anything at
13775  // all, then we need to do a few things in the surrounding context:
13776  if (Result->getBlockDecl()->hasCaptures()) {
13777  // First, this expression has a new cleanup object.
13778  ExprCleanupObjects.push_back(Result->getBlockDecl());
13779  Cleanup.setExprNeedsCleanups(true);
13780 
13781  // It also gets a branch-protected scope if any of the captured
13782  // variables needs destruction.
13783  for (const auto &CI : Result->getBlockDecl()->captures()) {
13784  const VarDecl *var = CI.getVariable();
13785  if (var->getType().isDestructedType() != QualType::DK_none) {
13786  setFunctionHasBranchProtectedScope();
13787  break;
13788  }
13789  }
13790  }
13791 
13792  if (getCurFunction())
13793  getCurFunction()->addBlock(BD);
13794 
13795  return Result;
13796 }
13797 
13799  SourceLocation RPLoc) {
13800  TypeSourceInfo *TInfo;
13801  GetTypeFromParser(Ty, &TInfo);
13802  return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13803 }
13804 
13806  Expr *E, TypeSourceInfo *TInfo,
13807  SourceLocation RPLoc) {
13808  Expr *OrigExpr = E;
13809  bool IsMS = false;
13810 
13811  // CUDA device code does not support varargs.
13812  if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13813  if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13814  CUDAFunctionTarget T = IdentifyCUDATarget(F);
13815  if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13816  return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13817  }
13818  }
13819 
13820  // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13821  // as Microsoft ABI on an actual Microsoft platform, where
13822  // __builtin_ms_va_list and __builtin_va_list are the same.)
13823  if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13825  QualType MSVaListType = Context.getBuiltinMSVaListType();
13826  if (Context.hasSameType(MSVaListType, E->getType())) {
13827  if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13828  return ExprError();
13829  IsMS = true;
13830  }
13831  }
13832 
13833  // Get the va_list type
13834  QualType VaListType = Context.getBuiltinVaListType();
13835  if (!IsMS) {
13836  if (VaListType->isArrayType()) {
13837  // Deal with implicit array decay; for example, on x86-64,
13838  // va_list is an array, but it's supposed to decay to
13839  // a pointer for va_arg.
13840  VaListType = Context.getArrayDecayedType(VaListType);
13841  // Make sure the input expression also decays appropriately.
13842  ExprResult Result = UsualUnaryConversions(E);
13843  if (Result.isInvalid())
13844  return ExprError();
13845  E = Result.get();
13846  } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13847  // If va_list is a record type and we are compiling in C++ mode,
13848  // check the argument using reference binding.
13850  Context, Context.getLValueReferenceType(VaListType), false);
13851  ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13852  if (Init.isInvalid())
13853  return ExprError();
13854  E = Init.getAs<Expr>();
13855  } else {
13856  // Otherwise, the va_list argument must be an l-value because
13857  // it is modified by va_arg.
13858  if (!E->isTypeDependent() &&
13859  CheckForModifiableLvalue(E, BuiltinLoc, *this))
13860  return ExprError();
13861  }
13862  }
13863 
13864  if (!IsMS && !E->isTypeDependent() &&
13865  !Context.hasSameType(VaListType, E->getType()))
13866  return ExprError(
13867  Diag(E->getBeginLoc(),
13868  diag::err_first_argument_to_va_arg_not_of_type_va_list)
13869  << OrigExpr->getType() << E->getSourceRange());
13870 
13871  if (!TInfo->getType()->isDependentType()) {
13872  if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13873  diag::err_second_parameter_to_va_arg_incomplete,
13874  TInfo->getTypeLoc()))
13875  return ExprError();
13876 
13877  if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13878  TInfo->getType(),
13879  diag::err_second_parameter_to_va_arg_abstract,
13880  TInfo->getTypeLoc()))
13881  return ExprError();
13882 
13883  if (!TInfo->getType().isPODType(Context)) {
13884  Diag(TInfo->getTypeLoc().getBeginLoc(),
13885  TInfo->getType()->isObjCLifetimeType()
13886  ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13887  : diag::warn_second_parameter_to_va_arg_not_pod)
13888  << TInfo->getType()
13889  << TInfo->getTypeLoc().getSourceRange();
13890  }
13891 
13892  // Check for va_arg where arguments of the given type will be promoted
13893  // (i.e. this va_arg is guaranteed to have undefined behavior).
13894  QualType PromoteType;
13895  if (TInfo->getType()->isPromotableIntegerType()) {
13896  PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13897  if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13898  PromoteType = QualType();
13899  }
13900  if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13901  PromoteType = Context.DoubleTy;
13902  if (!PromoteType.isNull())
13903  DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13904  PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13905  << TInfo->getType()
13906  << PromoteType
13907  << TInfo->getTypeLoc().getSourceRange());
13908  }
13909 
13910  QualType T = TInfo->getType().getNonLValueExprType(Context);
13911  return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13912 }
13913 
13915  // The type of __null will be int or long, depending on the size of
13916  // pointers on the target.
13917  QualType Ty;
13918  unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13919  if (pw == Context.getTargetInfo().getIntWidth())
13920  Ty = Context.IntTy;
13921  else if (pw == Context.getTargetInfo().getLongWidth())
13922  Ty = Context.LongTy;
13923  else if (pw == Context.getTargetInfo().getLongLongWidth())
13924  Ty = Context.LongLongTy;
13925  else {
13926  llvm_unreachable("I don't know size of pointer!");
13927  }
13928 
13929  return new (Context) GNUNullExpr(Ty, TokenLoc);
13930 }
13931 
13933  bool Diagnose) {
13934  if (!getLangOpts().ObjC)
13935  return false;
13936 
13937  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13938  if (!PT)
13939  return false;
13940 
13941  if (!PT->isObjCIdType()) {
13942  // Check if the destination is the 'NSString' interface.
13943  const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13944  if (!ID || !ID->getIdentifier()->isStr("NSString"))
13945  return false;
13946  }
13947 
13948  // Ignore any parens, implicit casts (should only be
13949  // array-to-pointer decays), and not-so-opaque values. The last is
13950  // important for making this trigger for property assignments.
13951  Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13952  if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13953  if (OV->getSourceExpr())
13954  SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13955 
13956  StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13957  if (!SL || !SL->isAscii())
13958  return false;
13959  if (Diagnose) {
13960  Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
13961  << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
13962  Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
13963  }
13964  return true;
13965 }
13966 
13968  const Expr *SrcExpr) {
13969  if (!DstType->isFunctionPointerType() ||
13970  !SrcExpr->getType()->isFunctionType())
13971  return false;
13972 
13973  auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13974  if (!DRE)
13975  return false;
13976 
13977  auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13978  if (!FD)
13979  return false;
13980 
13981  return !S.checkAddressOfFunctionIsAvailable(FD,
13982  /*Complain=*/true,
13983  SrcExpr->getBeginLoc());
13984 }
13985 
13987  SourceLocation Loc,
13988  QualType DstType, QualType SrcType,
13989  Expr *SrcExpr, AssignmentAction Action,
13990  bool *Complained) {
13991  if (Complained)
13992  *Complained = false;
13993 
13994  // Decode the result (notice that AST's are still created for extensions).
13995  bool CheckInferredResultType = false;
13996  bool isInvalid = false;
13997  unsigned DiagKind = 0;
13998  FixItHint Hint;
13999  ConversionFixItGenerator ConvHints;
14000  bool MayHaveConvFixit = false;
14001  bool MayHaveFunctionDiff = false;
14002  const ObjCInterfaceDecl *IFace = nullptr;
14003  const ObjCProtocolDecl *PDecl = nullptr;
14004 
14005  switch (ConvTy) {
14006  case Compatible:
14007  DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14008  return false;
14009 
14010  case PointerToInt:
14011  DiagKind = diag::ext_typecheck_convert_pointer_int;
14012  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14013  MayHaveConvFixit = true;
14014  break;
14015  case IntToPointer:
14016  DiagKind = diag::ext_typecheck_convert_int_pointer;
14017  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14018  MayHaveConvFixit = true;
14019  break;
14020  case IncompatiblePointer:
14021  if (Action == AA_Passing_CFAudited)
14022  DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14023  else if (SrcType->isFunctionPointerType() &&
14024  DstType->isFunctionPointerType())
14025  DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14026  else
14027  DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14028 
14029  CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14030  SrcType->isObjCObjectPointerType();
14031  if (Hint.isNull() && !CheckInferredResultType) {
14032  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14033  }
14034  else if (CheckInferredResultType) {
14035  SrcType = SrcType.getUnqualifiedType();
14036  DstType = DstType.getUnqualifiedType();
14037  }
14038  MayHaveConvFixit = true;
14039  break;
14040  case IncompatiblePointerSign:
14041  DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14042  break;
14043  case FunctionVoidPointer:
14044  DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14045  break;
14046  case IncompatiblePointerDiscardsQualifiers: {
14047  // Perform array-to-pointer decay if necessary.
14048  if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14049 
14050  Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14051  Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14052  if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14053  DiagKind = diag::err_typecheck_incompatible_address_space;
14054  break;
14055 
14056  } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14057  DiagKind = diag::err_typecheck_incompatible_ownership;
14058  break;
14059  }
14060 
14061  llvm_unreachable("unknown error case for discarding qualifiers!");
14062  // fallthrough
14063  }
14064  case CompatiblePointerDiscardsQualifiers:
14065  // If the qualifiers lost were because we were applying the
14066  // (deprecated) C++ conversion from a string literal to a char*
14067  // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
14068  // Ideally, this check would be performed in
14069  // checkPointerTypesForAssignment. However, that would require a
14070  // bit of refactoring (so that the second argument is an
14071  // expression, rather than a type), which should be done as part
14072  // of a larger effort to fix checkPointerTypesForAssignment for
14073  // C++ semantics.
14074  if (getLangOpts().CPlusPlus &&
14075  IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14076  return false;
14077  DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14078  break;
14079  case IncompatibleNestedPointerQualifiers:
14080  DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14081  break;
14082  case IntToBlockPointer:
14083  DiagKind = diag::err_int_to_block_pointer;
14084  break;
14085  case IncompatibleBlockPointer:
14086  DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14087  break;
14088  case IncompatibleObjCQualifiedId: {
14089  if (SrcType->isObjCQualifiedIdType()) {
14090  const ObjCObjectPointerType *srcOPT =
14091  SrcType->getAs<ObjCObjectPointerType>();
14092  for (auto *srcProto : srcOPT->quals()) {
14093  PDecl = srcProto;
14094  break;
14095  }
14096  if (const ObjCInterfaceType *IFaceT =
14098  IFace = IFaceT->getDecl();
14099  }
14100  else if (DstType->isObjCQualifiedIdType()) {
14101  const ObjCObjectPointerType *dstOPT =
14102  DstType->getAs<ObjCObjectPointerType>();
14103  for (auto *dstProto : dstOPT->quals()) {
14104  PDecl = dstProto;
14105  break;
14106  }
14107  if (const ObjCInterfaceType *IFaceT =
14109  IFace = IFaceT->getDecl();
14110  }
14111  DiagKind = diag::warn_incompatible_qualified_id;
14112  break;
14113  }
14114  case IncompatibleVectors:
14115  DiagKind = diag::warn_incompatible_vectors;
14116  break;
14117  case IncompatibleObjCWeakRef:
14118  DiagKind = diag::err_arc_weak_unavailable_assign;
14119  break;
14120  case Incompatible:
14121  if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14122  if (Complained)
14123  *Complained = true;
14124  return true;
14125  }
14126 
14127  DiagKind = diag::err_typecheck_convert_incompatible;
14128  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14129  MayHaveConvFixit = true;
14130  isInvalid = true;
14131  MayHaveFunctionDiff = true;
14132  break;
14133  }
14134 
14135  QualType FirstType, SecondType;
14136  switch (Action) {
14137  case AA_Assigning:
14138  case AA_Initializing:
14139  // The destination type comes first.
14140  FirstType = DstType;
14141  SecondType = SrcType;
14142  break;
14143 
14144  case AA_Returning:
14145  case AA_Passing:
14146  case AA_Passing_CFAudited:
14147  case AA_Converting:
14148  case AA_Sending:
14149  case AA_Casting:
14150  // The source type comes first.
14151  FirstType = SrcType;
14152  SecondType = DstType;
14153  break;
14154  }
14155 
14156  PartialDiagnostic FDiag = PDiag(DiagKind);
14157  if (Action == AA_Passing_CFAudited)
14158  FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14159  else
14160  FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14161 
14162  // If we can fix the conversion, suggest the FixIts.
14163  assert(ConvHints.isNull() || Hint.isNull());
14164  if (!ConvHints.isNull()) {
14165  for (FixItHint &H : ConvHints.Hints)
14166  FDiag << H;
14167  } else {
14168  FDiag << Hint;
14169  }
14170  if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14171 
14172  if (MayHaveFunctionDiff)
14173  HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14174 
14175  Diag(Loc, FDiag);
14176  if (DiagKind == diag::warn_incompatible_qualified_id &&
14177  PDecl && IFace && !IFace->hasDefinition())
14178  Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14179  << IFace << PDecl;
14180 
14181  if (SecondType == Context.OverloadTy)
14182  NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14183  FirstType, /*TakingAddress=*/true);
14184 
14185  if (CheckInferredResultType)
14186  EmitRelatedResultTypeNote(SrcExpr);
14187 
14188  if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14189  EmitRelatedResultTypeNoteForReturn(DstType);
14190 
14191  if (Complained)
14192  *Complained = true;
14193  return isInvalid;
14194 }
14195 
14197  llvm::APSInt *Result) {
14198  class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14199  public:
14200  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14201  S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14202  }
14203  } Diagnoser;
14204 
14205  return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14206 }
14207 
14209  llvm::APSInt *Result,
14210  unsigned DiagID,
14211  bool AllowFold) {
14212  class IDDiagnoser : public VerifyICEDiagnoser {
14213  unsigned DiagID;
14214 
14215  public:
14216  IDDiagnoser(unsigned DiagID)
14217  : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14218 
14219  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14220  S.Diag(Loc, DiagID) << SR;
14221  }
14222  } Diagnoser(DiagID);
14223 
14224  return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14225 }
14226 
14228  SourceRange SR) {
14229  S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14230 }
14231 
14232 ExprResult
14234  VerifyICEDiagnoser &Diagnoser,
14235  bool AllowFold) {
14236  SourceLocation DiagLoc = E->getBeginLoc();
14237 
14238  if (getLangOpts().CPlusPlus11) {
14239  // C++11 [expr.const]p5:
14240  // If an expression of literal class type is used in a context where an
14241  // integral constant expression is required, then that class type shall
14242  // have a single non-explicit conversion function to an integral or
14243  // unscoped enumeration type
14244  ExprResult Converted;
14245  class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14246  public:
14247  CXX11ConvertDiagnoser(bool Silent)
14248  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14249  Silent, true) {}
14250 
14251  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14252  QualType T) override {
14253  return S.Diag(Loc, diag::err_ice_not_integral) << T;
14254  }
14255 
14256  SemaDiagnosticBuilder diagnoseIncomplete(
14257  Sema &S, SourceLocation Loc, QualType T) override {
14258  return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14259  }
14260 
14261  SemaDiagnosticBuilder diagnoseExplicitConv(
14262  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14263  return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14264  }
14265 
14266  SemaDiagnosticBuilder noteExplicitConv(
14267  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14268  return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14269  << ConvTy->isEnumeralType() << ConvTy;
14270  }
14271 
14272  SemaDiagnosticBuilder diagnoseAmbiguous(
14273  Sema &S, SourceLocation Loc, QualType T) override {
14274  return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14275  }
14276 
14277  SemaDiagnosticBuilder noteAmbiguous(
14278  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14279  return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14280  << ConvTy->isEnumeralType() << ConvTy;
14281  }
14282 
14283  SemaDiagnosticBuilder diagnoseConversion(
14284  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14285  llvm_unreachable("conversion functions are permitted");
14286  }
14287  } ConvertDiagnoser(Diagnoser.Suppress);
14288 
14289  Converted = PerformContextualImplicitConversion(DiagLoc, E,
14290  ConvertDiagnoser);
14291  if (Converted.isInvalid())
14292  return Converted;
14293  E = Converted.get();
14295  return ExprError();
14296  } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14297  // An ICE must be of integral or unscoped enumeration type.
14298  if (!Diagnoser.Suppress)
14299  Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14300  return ExprError();
14301  }
14302 
14303  if (!isa<ConstantExpr>(E))
14304  E = ConstantExpr::Create(Context, E);
14305 
14306  // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14307  // in the non-ICE case.
14308  if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14309  if (Result)
14310  *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14311  return E;
14312  }
14313 
14314  Expr::EvalResult EvalResult;
14316  EvalResult.Diag = &Notes;
14317 
14318  // Try to evaluate the expression, and produce diagnostics explaining why it's
14319  // not a constant expression as a side-effect.
14320  bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14321  EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14322 
14323  // In C++11, we can rely on diagnostics being produced for any expression
14324  // which is not a constant expression. If no diagnostics were produced, then
14325  // this is a constant expression.
14326  if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14327  if (Result)
14328  *Result = EvalResult.Val.getInt();
14329  return E;
14330  }
14331 
14332  // If our only note is the usual "invalid subexpression" note, just point
14333  // the caret at its location rather than producing an essentially
14334  // redundant note.
14335  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14336  diag::note_invalid_subexpr_in_const_expr) {
14337  DiagLoc = Notes[0].first;
14338  Notes.clear();
14339  }
14340 
14341  if (!Folded || !AllowFold) {
14342  if (!Diagnoser.Suppress) {
14343  Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14344  for (const PartialDiagnosticAt &Note : Notes)
14345  Diag(Note.first, Note.second);
14346  }
14347 
14348  return ExprError();
14349  }
14350 
14351  Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14352  for (const PartialDiagnosticAt &Note : Notes)
14353  Diag(Note.first, Note.second);
14354 
14355  if (Result)
14356  *Result = EvalResult.Val.getInt();
14357  return E;
14358 }
14359 
14360 namespace {
14361  // Handle the case where we conclude a expression which we speculatively
14362  // considered to be unevaluated is actually evaluated.
14363  class TransformToPE : public TreeTransform<TransformToPE> {
14364  typedef TreeTransform<TransformToPE> BaseTransform;
14365 
14366  public:
14367  TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14368 
14369  // Make sure we redo semantic analysis
14370  bool AlwaysRebuild() { return true; }
14371 
14372  // Make sure we handle LabelStmts correctly.
14373  // FIXME: This does the right thing, but maybe we need a more general
14374  // fix to TreeTransform?
14375  StmtResult TransformLabelStmt(LabelStmt *S) {
14376  S->getDecl()->setStmt(nullptr);
14377  return BaseTransform::TransformLabelStmt(S);
14378  }
14379 
14380  // We need to special-case DeclRefExprs referring to FieldDecls which
14381  // are not part of a member pointer formation; normal TreeTransforming
14382  // doesn't catch this case because of the way we represent them in the AST.
14383  // FIXME: This is a bit ugly; is it really the best way to handle this
14384  // case?
14385  //
14386  // Error on DeclRefExprs referring to FieldDecls.
14387  ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14388  if (isa<FieldDecl>(E->getDecl()) &&
14389  !SemaRef.isUnevaluatedContext())
14390  return SemaRef.Diag(E->getLocation(),
14391  diag::err_invalid_non_static_member_use)
14392  << E->getDecl() << E->getSourceRange();
14393 
14394  return BaseTransform::TransformDeclRefExpr(E);
14395  }
14396 
14397  // Exception: filter out member pointer formation
14398  ExprResult TransformUnaryOperator(UnaryOperator *E) {
14399  if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14400  return E;
14401 
14402  return BaseTransform::TransformUnaryOperator(E);
14403  }
14404 
14405  ExprResult TransformLambdaExpr(LambdaExpr *E) {
14406  // Lambdas never need to be transformed.
14407  return E;
14408  }
14409  };
14410 }
14411 
14413  assert(isUnevaluatedContext() &&
14414  "Should only transform unevaluated expressions");
14415  ExprEvalContexts.back().Context =
14416  ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14417  if (isUnevaluatedContext())
14418  return E;
14419  return TransformToPE(*this).TransformExpr(E);
14420 }
14421 
14422 void
14424  ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14426  ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14427  LambdaContextDecl, ExprContext);
14428  Cleanup.reset();
14429  if (!MaybeODRUseExprs.empty())
14430  std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14431 }
14432 
14433 void
14437  Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14438  PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14439 }
14440 
14441 namespace {
14442 
14443 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14444  PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14445  if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14446  if (E->getOpcode() == UO_Deref)
14447  return CheckPossibleDeref(S, E->getSubExpr());
14448  } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14449  return CheckPossibleDeref(S, E->getBase());
14450  } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14451  return CheckPossibleDeref(S, E->getBase());
14452  } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14453  QualType Inner;
14454  QualType Ty = E->getType();
14455  if (const auto *Ptr = Ty->getAs<PointerType>())
14456  Inner = Ptr->getPointeeType();
14457  else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14458  Inner = Arr->getElementType();
14459  else
14460  return nullptr;
14461 
14462  if (Inner->hasAttr(attr::NoDeref))
14463  return E;
14464  }
14465  return nullptr;
14466 }
14467 
14468 } // namespace
14469 
14471  for (const Expr *E : Rec.PossibleDerefs) {
14472  const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14473  if (DeclRef) {
14474  const ValueDecl *Decl = DeclRef->getDecl();
14475  Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14476  << Decl->getName() << E->getSourceRange();
14477  Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14478  } else {
14479  Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14480  << E->getSourceRange();
14481  }
14482  }
14483  Rec.PossibleDerefs.clear();
14484 }
14485 
14487  ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14488  unsigned NumTypos = Rec.NumTypos;
14489 
14490  if (!Rec.Lambdas.empty()) {
14492  if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14493  (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14494  unsigned D;
14495  if (Rec.isUnevaluated()) {
14496  // C++11 [expr.prim.lambda]p2:
14497  // A lambda-expression shall not appear in an unevaluated operand
14498  // (Clause 5).
14499  D = diag::err_lambda_unevaluated_operand;
14500  } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14501  // C++1y [expr.const]p2:
14502  // A conditional-expression e is a core constant expression unless the
14503  // evaluation of e, following the rules of the abstract machine, would
14504  // evaluate [...] a lambda-expression.
14505  D = diag::err_lambda_in_constant_expression;
14506  } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14507  // C++17 [expr.prim.lamda]p2:
14508  // A lambda-expression shall not appear [...] in a template-argument.
14509  D = diag::err_lambda_in_invalid_context;
14510  } else
14511  llvm_unreachable("Couldn't infer lambda error message.");
14512 
14513  for (const auto *L : Rec.Lambdas)
14514  Diag(L->getBeginLoc(), D);
14515  } else {
14516  // Mark the capture expressions odr-used. This was deferred
14517  // during lambda expression creation.
14518  for (auto *Lambda : Rec.Lambdas) {
14519  for (auto *C : Lambda->capture_inits())
14520  MarkDeclarationsReferencedInExpr(C);
14521  }
14522  }
14523  }
14524 
14525  WarnOnPendingNoDerefs(Rec);
14526 
14527  // When are coming out of an unevaluated context, clear out any
14528  // temporaries that we may have created as part of the evaluation of
14529  // the expression in that context: they aren't relevant because they
14530  // will never be constructed.
14531  if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14532  ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14533  ExprCleanupObjects.end());
14534  Cleanup = Rec.ParentCleanup;
14535  CleanupVarDeclMarking();
14536  std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14537  // Otherwise, merge the contexts together.
14538  } else {
14539  Cleanup.mergeFrom(Rec.ParentCleanup);
14540  MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14541  Rec.SavedMaybeODRUseExprs.end());
14542  }
14543 
14544  // Pop the current expression evaluation context off the stack.
14545  ExprEvalContexts.pop_back();
14546 
14547  // The global expression evaluation context record is never popped.
14548  ExprEvalContexts.back().NumTypos += NumTypos;
14549 }
14550 
14552  ExprCleanupObjects.erase(
14553  ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14554  ExprCleanupObjects.end());
14555  Cleanup.reset();
14556  MaybeODRUseExprs.clear();
14557 }
14558 
14560  ExprResult Result = CheckPlaceholderExpr(E);
14561  if (Result.isInvalid())
14562  return ExprError();
14563  E = Result.get();
14564  if (!E->getType()->isVariablyModifiedType())
14565  return E;
14566  return TransformToPotentiallyEvaluated(E);
14567 }
14568 
14569 /// Are we within a context in which some evaluation could be performed (be it
14570 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14571 /// captured by C++'s idea of an "unevaluated context".
14572 static bool isEvaluatableContext(Sema &SemaRef) {
14573  switch (SemaRef.ExprEvalContexts.back().Context) {
14576  // Expressions in this context are never evaluated.
14577  return false;
14578 
14583  // Expressions in this context could be evaluated.
14584  return true;
14585 
14587  // Referenced declarations will only be used if the construct in the
14588  // containing expression is used, at which point we'll be given another
14589  // turn to mark them.
14590  return false;
14591  }
14592  llvm_unreachable("Invalid context");
14593 }
14594 
14595 /// Are we within a context in which references to resolved functions or to
14596 /// variables result in odr-use?
14597 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14598  // An expression in a template is not really an expression until it's been
14599  // instantiated, so it doesn't trigger odr-use.
14600  if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14601  return false;
14602 
14603  switch (SemaRef.ExprEvalContexts.back().Context) {
14608  return false;
14609 
14612  return true;
14613 
14615  return false;
14616  }
14617  llvm_unreachable("Invalid context");
14618 }
14619 
14621  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14622  return Func->isConstexpr() &&
14623  (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14624 }
14625 
14626 /// Mark a function referenced, and check whether it is odr-used
14627 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14629  bool MightBeOdrUse) {
14630  assert(Func && "No function?");
14631 
14632  Func->setReferenced();
14633 
14634  // C++11 [basic.def.odr]p3:
14635  // A function whose name appears as a potentially-evaluated expression is
14636  // odr-used if it is the unique lookup result or the selected member of a
14637  // set of overloaded functions [...].
14638  //
14639  // We (incorrectly) mark overload resolution as an unevaluated context, so we
14640  // can just check that here.
14641  bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14642 
14643  // Determine whether we require a function definition to exist, per
14644  // C++11 [temp.inst]p3:
14645  // Unless a function template specialization has been explicitly
14646  // instantiated or explicitly specialized, the function template
14647  // specialization is implicitly instantiated when the specialization is
14648  // referenced in a context that requires a function definition to exist.
14649  //
14650  // That is either when this is an odr-use, or when a usage of a constexpr
14651  // function occurs within an evaluatable context.
14652  bool NeedDefinition =
14653  OdrUse || (isEvaluatableContext(*this) &&
14655 
14656  // C++14 [temp.expl.spec]p6:
14657  // If a template [...] is explicitly specialized then that specialization
14658  // shall be declared before the first use of that specialization that would
14659  // cause an implicit instantiation to take place, in every translation unit
14660  // in which such a use occurs
14661  if (NeedDefinition &&
14663  Func->getMemberSpecializationInfo()))
14664  checkSpecializationVisibility(Loc, Func);
14665 
14666  // C++14 [except.spec]p17:
14667  // An exception-specification is considered to be needed when:
14668  // - the function is odr-used or, if it appears in an unevaluated operand,
14669  // would be odr-used if the expression were potentially-evaluated;
14670  //
14671  // Note, we do this even if MightBeOdrUse is false. That indicates that the
14672  // function is a pure virtual function we're calling, and in that case the
14673  // function was selected by overload resolution and we need to resolve its
14674  // exception specification for a different reason.
14675  const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14677  ResolveExceptionSpec(Loc, FPT);
14678 
14679  // If we don't need to mark the function as used, and we don't need to
14680  // try to provide a definition, there's nothing more to do.
14681  if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14682  (!NeedDefinition || Func->getBody()))
14683  return;
14684 
14685  // Note that this declaration has been used.
14686  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14687  Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14688  if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14689  if (Constructor->isDefaultConstructor()) {
14690  if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14691  return;
14692  DefineImplicitDefaultConstructor(Loc, Constructor);
14693  } else if (Constructor->isCopyConstructor()) {
14694  DefineImplicitCopyConstructor(Loc, Constructor);
14695  } else if (Constructor->isMoveConstructor()) {
14696  DefineImplicitMoveConstructor(Loc, Constructor);
14697  }
14698  } else if (Constructor->getInheritedConstructor()) {
14699  DefineInheritingConstructor(Loc, Constructor);
14700  }
14701  } else if (CXXDestructorDecl *Destructor =
14702  dyn_cast<CXXDestructorDecl>(Func)) {
14703  Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14704  if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14705  if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14706  return;
14707  DefineImplicitDestructor(Loc, Destructor);
14708  }
14709  if (Destructor->isVirtual() && getLangOpts().AppleKext)
14710  MarkVTableUsed(Loc, Destructor->getParent());
14711  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14712  if (MethodDecl->isOverloadedOperator() &&
14713  MethodDecl->getOverloadedOperator() == OO_Equal) {
14714  MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14715  if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14716  if (MethodDecl->isCopyAssignmentOperator())
14717  DefineImplicitCopyAssignment(Loc, MethodDecl);
14718  else if (MethodDecl->isMoveAssignmentOperator())
14719  DefineImplicitMoveAssignment(Loc, MethodDecl);
14720  }
14721  } else if (isa<CXXConversionDecl>(MethodDecl) &&
14722  MethodDecl->getParent()->isLambda()) {
14723  CXXConversionDecl *Conversion =
14724  cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14725  if (Conversion->isLambdaToBlockPointerConversion())
14726  DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14727  else
14728  DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14729  } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14730  MarkVTableUsed(Loc, MethodDecl->getParent());
14731  }
14732 
14733  // Recursive functions should be marked when used from another function.
14734  // FIXME: Is this really right?
14735  if (CurContext == Func) return;
14736 
14737  // Implicit instantiation of function templates and member functions of
14738  // class templates.
14739  if (Func->isImplicitlyInstantiable()) {
14741  SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14742  bool FirstInstantiation = PointOfInstantiation.isInvalid();
14743  if (FirstInstantiation) {
14744  PointOfInstantiation = Loc;
14745  Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14746  } else if (TSK != TSK_ImplicitInstantiation) {
14747  // Use the point of use as the point of instantiation, instead of the
14748  // point of explicit instantiation (which we track as the actual point of
14749  // instantiation). This gives better backtraces in diagnostics.
14750  PointOfInstantiation = Loc;
14751  }
14752 
14753  if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14754  Func->isConstexpr()) {
14755  if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14756  cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14757  CodeSynthesisContexts.size())
14758  PendingLocalImplicitInstantiations.push_back(
14759  std::make_pair(Func, PointOfInstantiation));
14760  else if (Func->isConstexpr())
14761  // Do not defer instantiations of constexpr functions, to avoid the
14762  // expression evaluator needing to call back into Sema if it sees a
14763  // call to such a function.
14764  InstantiateFunctionDefinition(PointOfInstantiation, Func);
14765  else {
14766  Func->setInstantiationIsPending(true);
14767  PendingInstantiations.push_back(std::make_pair(Func,
14768  PointOfInstantiation));
14769  // Notify the consumer that a function was implicitly instantiated.
14770  Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14771  }
14772  }
14773  } else {
14774  // Walk redefinitions, as some of them may be instantiable.
14775  for (auto i : Func->redecls()) {
14776  if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14777  MarkFunctionReferenced(Loc, i, OdrUse);
14778  }
14779  }
14780 
14781  if (!OdrUse) return;
14782 
14783  // Keep track of used but undefined functions.
14784  if (!Func->isDefined()) {
14785  if (mightHaveNonExternalLinkage(Func))
14786  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14787  else if (Func->getMostRecentDecl()->isInlined() &&
14788  !LangOpts.GNUInline &&
14789  !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14790  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14791  else if (isExternalWithNoLinkageType(Func))
14792  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14793  }
14794 
14795  Func->markUsed(Context);
14796 }
14797 
14798 static void
14800  ValueDecl *var, DeclContext *DC) {
14801  DeclContext *VarDC = var->getDeclContext();
14802 
14803  // If the parameter still belongs to the translation unit, then
14804  // we're actually just using one parameter in the declaration of
14805  // the next.
14806  if (isa<ParmVarDecl>(var) &&
14807  isa<TranslationUnitDecl>(VarDC))
14808  return;
14809 
14810  // For C code, don't diagnose about capture if we're not actually in code
14811  // right now; it's impossible to write a non-constant expression outside of
14812  // function context, so we'll get other (more useful) diagnostics later.
14813  //
14814  // For C++, things get a bit more nasty... it would be nice to suppress this
14815  // diagnostic for certain cases like using a local variable in an array bound
14816  // for a member of a local class, but the correct predicate is not obvious.
14817  if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14818  return;
14819 
14820  unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14821  unsigned ContextKind = 3; // unknown
14822  if (isa<CXXMethodDecl>(VarDC) &&
14823  cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14824  ContextKind = 2;
14825  } else if (isa<FunctionDecl>(VarDC)) {
14826  ContextKind = 0;
14827  } else if (isa<BlockDecl>(VarDC)) {
14828  ContextKind = 1;
14829  }
14830 
14831  S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14832  << var << ValueKind << ContextKind << VarDC;
14833  S.Diag(var->getLocation(), diag::note_entity_declared_at)
14834  << var;
14835 
14836  // FIXME: Add additional diagnostic info about class etc. which prevents
14837  // capture.
14838 }
14839 
14840 
14842  bool &SubCapturesAreNested,
14843  QualType &CaptureType,
14844  QualType &DeclRefType) {
14845  // Check whether we've already captured it.
14846  if (CSI->CaptureMap.count(Var)) {
14847  // If we found a capture, any subcaptures are nested.
14848  SubCapturesAreNested = true;
14849 
14850  // Retrieve the capture type for this variable.
14851  CaptureType = CSI->getCapture(Var).getCaptureType();
14852 
14853  // Compute the type of an expression that refers to this variable.
14854  DeclRefType = CaptureType.getNonReferenceType();
14855 
14856  // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14857  // are mutable in the sense that user can change their value - they are
14858  // private instances of the captured declarations.
14859  const Capture &Cap = CSI->getCapture(Var);
14860  if (Cap.isCopyCapture() &&
14861  !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14862  !(isa<CapturedRegionScopeInfo>(CSI) &&
14863  cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14864  DeclRefType.addConst();
14865  return true;
14866  }
14867  return false;
14868 }
14869 
14870 // Only block literals, captured statements, and lambda expressions can
14871 // capture; other scopes don't work.
14873  SourceLocation Loc,
14874  const bool Diagnose, Sema &S) {
14875  if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14877  else if (Var->hasLocalStorage()) {
14878  if (Diagnose)
14879  diagnoseUncapturableValueReference(S, Loc, Var, DC);
14880  }
14881  return nullptr;
14882 }
14883 
14884 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14885 // certain types of variables (unnamed, variably modified types etc.)
14886 // so check for eligibility.
14888  SourceLocation Loc,
14889  const bool Diagnose, Sema &S) {
14890 
14891  bool IsBlock = isa<BlockScopeInfo>(CSI);
14892  bool IsLambda = isa<LambdaScopeInfo>(CSI);
14893 
14894  // Lambdas are not allowed to capture unnamed variables
14895  // (e.g. anonymous unions).
14896  // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14897  // assuming that's the intent.
14898  if (IsLambda && !Var->getDeclName()) {
14899  if (Diagnose) {
14900  S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14901  S.Diag(Var->getLocation(), diag::note_declared_at);
14902  }
14903  return false;
14904  }
14905 
14906  // Prohibit variably-modified types in blocks; they're difficult to deal with.
14907  if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14908  if (Diagnose) {
14909  S.Diag(Loc, diag::err_ref_vm_type);
14910  S.Diag(Var->getLocation(), diag::note_previous_decl)
14911  << Var->getDeclName();
14912  }
14913  return false;
14914  }
14915  // Prohibit structs with flexible array members too.
14916  // We cannot capture what is in the tail end of the struct.
14917  if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14918  if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14919  if (Diagnose) {
14920  if (IsBlock)
14921  S.Diag(Loc, diag::err_ref_flexarray_type);
14922  else
14923  S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14924  << Var->getDeclName();
14925  S.Diag(Var->getLocation(), diag::note_previous_decl)
14926  << Var->getDeclName();
14927  }
14928  return false;
14929  }
14930  }
14931  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14932  // Lambdas and captured statements are not allowed to capture __block
14933  // variables; they don't support the expected semantics.
14934  if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14935  if (Diagnose) {
14936  S.Diag(Loc, diag::err_capture_block_variable)
14937  << Var->getDeclName() << !IsLambda;
14938  S.Diag(Var->getLocation(), diag::note_previous_decl)
14939  << Var->getDeclName();
14940  }
14941  return false;
14942  }
14943  // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14944  if (S.getLangOpts().OpenCL && IsBlock &&
14945  Var->getType()->isBlockPointerType()) {
14946  if (Diagnose)
14947  S.Diag(Loc, diag::err_opencl_block_ref_block);
14948  return false;
14949  }
14950 
14951  return true;
14952 }
14953 
14954 // Returns true if the capture by block was successful.
14955 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14956  SourceLocation Loc,
14957  const bool BuildAndDiagnose,
14958  QualType &CaptureType,
14959  QualType &DeclRefType,
14960  const bool Nested,
14961  Sema &S) {
14962  Expr *CopyExpr = nullptr;
14963  bool ByRef = false;
14964 
14965  // Blocks are not allowed to capture arrays, excepting OpenCL.
14966  // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
14967  // (decayed to pointers).
14968  if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
14969  if (BuildAndDiagnose) {
14970  S.Diag(Loc, diag::err_ref_array_type);
14971  S.Diag(Var->getLocation(), diag::note_previous_decl)
14972  << Var->getDeclName();
14973  }
14974  return false;
14975  }
14976 
14977  // Forbid the block-capture of autoreleasing variables.
14978  if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14979  if (BuildAndDiagnose) {
14980  S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14981  << /*block*/ 0;
14982  S.Diag(Var->getLocation(), diag::note_previous_decl)
14983  << Var->getDeclName();
14984  }
14985  return false;
14986  }
14987 
14988  // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14989  if (const auto *PT = CaptureType->getAs<PointerType>()) {
14990  // This function finds out whether there is an AttributedType of kind
14991  // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
14992  // attr::ObjCOwnership implies __autoreleasing was explicitly specified
14993  // rather than being added implicitly by the compiler.
14994  auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14995  while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14996  if (AttrTy->getAttrKind() == attr::ObjCOwnership)
14997  return true;
14998 
14999  // Peel off AttributedTypes that are not of kind ObjCOwnership.
15000  Ty = AttrTy->getModifiedType();
15001  }
15002 
15003  return false;
15004  };
15005 
15006  QualType PointeeTy = PT->getPointeeType();
15007 
15008  if (PointeeTy->getAs<ObjCObjectPointerType>() &&
15010  !IsObjCOwnershipAttributedType(PointeeTy)) {
15011  if (BuildAndDiagnose) {
15012  SourceLocation VarLoc = Var->getLocation();
15013  S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15014  S.Diag(VarLoc, diag::note_declare_parameter_strong);
15015  }
15016  }
15017  }
15018 
15019  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15020  if (HasBlocksAttr || CaptureType->isReferenceType() ||
15021  (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15022  // Block capture by reference does not change the capture or
15023  // declaration reference types.
15024  ByRef = true;
15025  } else {
15026  // Block capture by copy introduces 'const'.
15027  CaptureType = CaptureType.getNonReferenceType().withConst();
15028  DeclRefType = CaptureType;
15029 
15030  if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
15031  if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
15032  // The capture logic needs the destructor, so make sure we mark it.
15033  // Usually this is unnecessary because most local variables have
15034  // their destructors marked at declaration time, but parameters are
15035  // an exception because it's technically only the call site that
15036  // actually requires the destructor.
15037  if (isa<ParmVarDecl>(Var))
15038  S.FinalizeVarWithDestructor(Var, Record);
15039 
15040  // Enter a new evaluation context to insulate the copy
15041  // full-expression.
15044 
15045  // According to the blocks spec, the capture of a variable from
15046  // the stack requires a const copy constructor. This is not true
15047  // of the copy/move done to move a __block variable to the heap.
15048  Expr *DeclRef = new (S.Context) DeclRefExpr(
15049  S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc);
15050 
15051  ExprResult Result
15054  CaptureType, false),
15055  Loc, DeclRef);
15056 
15057  // Build a full-expression copy expression if initialization
15058  // succeeded and used a non-trivial constructor. Recover from
15059  // errors by pretending that the copy isn't necessary.
15060  if (!Result.isInvalid() &&
15061  !cast<CXXConstructExpr>(Result.get())->getConstructor()
15062  ->isTrivial()) {
15063  Result = S.MaybeCreateExprWithCleanups(Result);
15064  CopyExpr = Result.get();
15065  }
15066  }
15067  }
15068  }
15069 
15070  // Actually capture the variable.
15071  if (BuildAndDiagnose)
15072  BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
15073  SourceLocation(), CaptureType, CopyExpr);
15074 
15075  return true;
15076 
15077 }
15078 
15079 
15080 /// Capture the given variable in the captured region.
15082  VarDecl *Var,
15083  SourceLocation Loc,
15084  const bool BuildAndDiagnose,
15085  QualType &CaptureType,
15086  QualType &DeclRefType,
15087  const bool RefersToCapturedVariable,
15088  Sema &S) {
15089  // By default, capture variables by reference.
15090  bool ByRef = true;
15091  // Using an LValue reference type is consistent with Lambdas (see below).
15092  if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15093  if (S.isOpenMPCapturedDecl(Var)) {
15094  bool HasConst = DeclRefType.isConstQualified();
15095  DeclRefType = DeclRefType.getUnqualifiedType();
15096  // Don't lose diagnostics about assignments to const.
15097  if (HasConst)
15098  DeclRefType.addConst();
15099  }
15100  ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
15101  }
15102 
15103  if (ByRef)
15104  CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15105  else
15106  CaptureType = DeclRefType;
15107 
15108  Expr *CopyExpr = nullptr;
15109  if (BuildAndDiagnose) {
15110  // The current implementation assumes that all variables are captured
15111  // by references. Since there is no capture by copy, no expression
15112  // evaluation will be needed.
15113  RecordDecl *RD = RSI->TheRecordDecl;
15114 
15115  FieldDecl *Field
15116  = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
15117  S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
15118  nullptr, false, ICIS_NoInit);
15119  Field->setImplicit(true);
15120  Field->setAccess(AS_private);
15121  RD->addDecl(Field);
15122  if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
15123  S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
15124 
15125  CopyExpr = new (S.Context) DeclRefExpr(
15126  S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc);
15127  Var->setReferenced(true);
15128  Var->markUsed(S.Context);
15129  }
15130 
15131  // Actually capture the variable.
15132  if (BuildAndDiagnose)
15133  RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
15134  SourceLocation(), CaptureType, CopyExpr);
15135 
15136 
15137  return true;
15138 }
15139 
15140 /// Create a field within the lambda class for the variable
15141 /// being captured.
15143  QualType FieldType, QualType DeclRefType,
15144  SourceLocation Loc,
15145  bool RefersToCapturedVariable) {
15146  CXXRecordDecl *Lambda = LSI->Lambda;
15147 
15148  // Build the non-static data member.
15149  FieldDecl *Field
15150  = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
15151  S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
15152  nullptr, false, ICIS_NoInit);
15153  // If the variable being captured has an invalid type, mark the lambda class
15154  // as invalid as well.
15155  if (!FieldType->isDependentType()) {
15156  if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
15157  Lambda->setInvalidDecl();
15158  Field->setInvalidDecl();
15159  } else {
15160  NamedDecl *Def;
15161  FieldType->isIncompleteType(&Def);
15162  if (Def && Def->isInvalidDecl()) {
15163  Lambda->setInvalidDecl();
15164  Field->setInvalidDecl();
15165  }
15166  }
15167  }
15168  Field->setImplicit(true);
15169  Field->setAccess(AS_private);
15170  Lambda->addDecl(Field);
15171 }
15172 
15173 /// Capture the given variable in the lambda.
15175  VarDecl *Var,
15176  SourceLocation Loc,
15177  const bool BuildAndDiagnose,
15178  QualType &CaptureType,
15179  QualType &DeclRefType,
15180  const bool RefersToCapturedVariable,
15181  const Sema::TryCaptureKind Kind,
15182  SourceLocation EllipsisLoc,
15183  const bool IsTopScope,
15184  Sema &S) {
15185 
15186  // Determine whether we are capturing by reference or by value.
15187  bool ByRef = false;
15188  if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15189  ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15190  } else {
15192  }
15193 
15194  // Compute the type of the field that will capture this variable.
15195  if (ByRef) {
15196  // C++11 [expr.prim.lambda]p15:
15197  // An entity is captured by reference if it is implicitly or
15198  // explicitly captured but not captured by copy. It is
15199  // unspecified whether additional unnamed non-static data
15200  // members are declared in the closure type for entities
15201  // captured by reference.
15202  //
15203  // FIXME: It is not clear whether we want to build an lvalue reference
15204  // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15205  // to do the former, while EDG does the latter. Core issue 1249 will
15206  // clarify, but for now we follow GCC because it's a more permissive and
15207  // easily defensible position.
15208  CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15209  } else {
15210  // C++11 [expr.prim.lambda]p14:
15211  // For each entity captured by copy, an unnamed non-static
15212  // data member is declared in the closure type. The
15213  // declaration order of these members is unspecified. The type
15214  // of such a data member is the type of the corresponding
15215  // captured entity if the entity is not a reference to an
15216  // object, or the referenced type otherwise. [Note: If the
15217  // captured entity is a reference to a function, the
15218  // corresponding data member is also a reference to a
15219  // function. - end note ]
15220  if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15221  if (!RefType->getPointeeType()->isFunctionType())
15222  CaptureType = RefType->getPointeeType();
15223  }
15224 
15225  // Forbid the lambda copy-capture of autoreleasing variables.
15226  if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15227  if (BuildAndDiagnose) {
15228  S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15229  S.Diag(Var->getLocation(), diag::note_previous_decl)
15230  << Var->getDeclName();
15231  }
15232  return false;
15233  }
15234 
15235  // Make sure that by-copy captures are of a complete and non-abstract type.
15236  if (BuildAndDiagnose) {
15237  if (!CaptureType->isDependentType() &&
15238  S.RequireCompleteType(Loc, CaptureType,
15239  diag::err_capture_of_incomplete_type,
15240  Var->getDeclName()))
15241  return false;
15242 
15243  if (S.RequireNonAbstractType(Loc, CaptureType,
15244  diag::err_capture_of_abstract_type))
15245  return false;
15246  }
15247  }
15248 
15249  // Capture this variable in the lambda.
15250  if (BuildAndDiagnose)
15251  addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
15252  RefersToCapturedVariable);
15253 
15254  // Compute the type of a reference to this captured variable.
15255  if (ByRef)
15256  DeclRefType = CaptureType.getNonReferenceType();
15257  else {
15258  // C++ [expr.prim.lambda]p5:
15259  // The closure type for a lambda-expression has a public inline
15260  // function call operator [...]. This function call operator is
15261  // declared const (9.3.1) if and only if the lambda-expression's
15262  // parameter-declaration-clause is not followed by mutable.
15263  DeclRefType = CaptureType.getNonReferenceType();
15264  if (!LSI->Mutable && !CaptureType->isReferenceType())
15265  DeclRefType.addConst();
15266  }
15267 
15268  // Add the capture.
15269  if (BuildAndDiagnose)
15270  LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15271  Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
15272 
15273  return true;
15274 }
15275 
15277  VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15278  SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15279  QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15280  // An init-capture is notionally from the context surrounding its
15281  // declaration, but its parent DC is the lambda class.
15282  DeclContext *VarDC = Var->getDeclContext();
15283  if (Var->isInitCapture())
15284  VarDC = VarDC->getParent();
15285 
15286  DeclContext *DC = CurContext;
15287  const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15288  ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15289  // We need to sync up the Declaration Context with the
15290  // FunctionScopeIndexToStopAt
15291  if (FunctionScopeIndexToStopAt) {
15292  unsigned FSIndex = FunctionScopes.size() - 1;
15293  while (FSIndex != MaxFunctionScopesIndex) {
15295  --FSIndex;
15296  }
15297  }
15298 
15299 
15300  // If the variable is declared in the current context, there is no need to
15301  // capture it.
15302  if (VarDC == DC) return true;
15303 
15304  // Capture global variables if it is required to use private copy of this
15305  // variable.
15306  bool IsGlobal = !Var->hasLocalStorage();
15307  if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
15308  return true;
15309  Var = Var->getCanonicalDecl();
15310 
15311  // Walk up the stack to determine whether we can capture the variable,
15312  // performing the "simple" checks that don't depend on type. We stop when
15313  // we've either hit the declared scope of the variable or find an existing
15314  // capture of that variable. We start from the innermost capturing-entity
15315  // (the DC) and ensure that all intervening capturing-entities
15316  // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15317  // declcontext can either capture the variable or have already captured
15318  // the variable.
15319  CaptureType = Var->getType();
15320  DeclRefType = CaptureType.getNonReferenceType();
15321  bool Nested = false;
15322  bool Explicit = (Kind != TryCapture_Implicit);
15323  unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15324  do {
15325  // Only block literals, captured statements, and lambda expressions can
15326  // capture; other scopes don't work.
15327  DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15328  ExprLoc,
15329  BuildAndDiagnose,
15330  *this);
15331  // We need to check for the parent *first* because, if we *have*
15332  // private-captured a global variable, we need to recursively capture it in
15333  // intermediate blocks, lambdas, etc.
15334  if (!ParentDC) {
15335  if (IsGlobal) {
15336  FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15337  break;
15338  }
15339  return true;
15340  }
15341 
15342  FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
15343  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15344 
15345 
15346  // Check whether we've already captured it.
15347  if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15348  DeclRefType)) {
15349  CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15350  break;
15351  }
15352  // If we are instantiating a generic lambda call operator body,
15353  // we do not want to capture new variables. What was captured
15354  // during either a lambdas transformation or initial parsing
15355  // should be used.
15357  if (BuildAndDiagnose) {
15358  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15360  Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15361  Diag(Var->getLocation(), diag::note_previous_decl)
15362  << Var->getDeclName();
15363  Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15364  } else
15365  diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15366  }
15367  return true;
15368  }
15369  // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15370  // certain types of variables (unnamed, variably modified types etc.)
15371  // so check for eligibility.
15372  if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15373  return true;
15374 
15375  // Try to capture variable-length arrays types.
15376  if (Var->getType()->isVariablyModifiedType()) {
15377  // We're going to walk down into the type and look for VLA
15378  // expressions.
15379  QualType QTy = Var->getType();
15380  if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15381  QTy = PVD->getOriginalType();
15382  captureVariablyModifiedType(Context, QTy, CSI);
15383  }
15384 
15385  if (getLangOpts().OpenMP) {
15386  if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15387  // OpenMP private variables should not be captured in outer scope, so
15388  // just break here. Similarly, global variables that are captured in a
15389  // target region should not be captured outside the scope of the region.
15390  if (RSI->CapRegionKind == CR_OpenMP) {
15391  bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15392  auto IsTargetCap = !IsOpenMPPrivateDecl &&
15393  isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15394  // When we detect target captures we are looking from inside the
15395  // target region, therefore we need to propagate the capture from the
15396  // enclosing region. Therefore, the capture is not initially nested.
15397  if (IsTargetCap)
15398  adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15399 
15400  if (IsTargetCap || IsOpenMPPrivateDecl) {
15401  Nested = !IsTargetCap;
15402  DeclRefType = DeclRefType.getUnqualifiedType();
15403  CaptureType = Context.getLValueReferenceType(DeclRefType);
15404  break;
15405  }
15406  }
15407  }
15408  }
15409  if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15410  // No capture-default, and this is not an explicit capture
15411  // so cannot capture this variable.
15412  if (BuildAndDiagnose) {
15413  Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15414  Diag(Var->getLocation(), diag::note_previous_decl)
15415  << Var->getDeclName();
15416  if (cast<LambdaScopeInfo>(CSI)->Lambda)
15417  Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15418  diag::note_lambda_decl);
15419  // FIXME: If we error out because an outer lambda can not implicitly
15420  // capture a variable that an inner lambda explicitly captures, we
15421  // should have the inner lambda do the explicit capture - because
15422  // it makes for cleaner diagnostics later. This would purely be done
15423  // so that the diagnostic does not misleadingly claim that a variable
15424  // can not be captured by a lambda implicitly even though it is captured
15425  // explicitly. Suggestion:
15426  // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15427  // at the function head
15428  // - cache the StartingDeclContext - this must be a lambda
15429  // - captureInLambda in the innermost lambda the variable.
15430  }
15431  return true;
15432  }
15433 
15434  FunctionScopesIndex--;
15435  DC = ParentDC;
15436  Explicit = false;
15437  } while (!VarDC->Equals(DC));
15438 
15439  // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15440  // computing the type of the capture at each step, checking type-specific
15441  // requirements, and adding captures if requested.
15442  // If the variable had already been captured previously, we start capturing
15443  // at the lambda nested within that one.
15444  for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15445  ++I) {
15446  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15447 
15448  if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15449  if (!captureInBlock(BSI, Var, ExprLoc,
15450  BuildAndDiagnose, CaptureType,
15451  DeclRefType, Nested, *this))
15452  return true;
15453  Nested = true;
15454  } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15455  if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15456  BuildAndDiagnose, CaptureType,
15457  DeclRefType, Nested, *this))
15458  return true;
15459  Nested = true;
15460  } else {
15461  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15462  if (!captureInLambda(LSI, Var, ExprLoc,
15463  BuildAndDiagnose, CaptureType,
15464  DeclRefType, Nested, Kind, EllipsisLoc,
15465  /*IsTopScope*/I == N - 1, *this))
15466  return true;
15467  Nested = true;
15468  }
15469  }
15470  return false;
15471 }
15472 
15474  TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15475  QualType CaptureType;
15476  QualType DeclRefType;
15477  return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15478  /*BuildAndDiagnose=*/true, CaptureType,
15479  DeclRefType, nullptr);
15480 }
15481 
15483  QualType CaptureType;
15484  QualType DeclRefType;
15485  return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15486  /*BuildAndDiagnose=*/false, CaptureType,
15487  DeclRefType, nullptr);
15488 }
15489 
15491  QualType CaptureType;
15492  QualType DeclRefType;
15493 
15494  // Determine whether we can capture this variable.
15495  if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15496  /*BuildAndDiagnose=*/false, CaptureType,
15497  DeclRefType, nullptr))
15498  return QualType();
15499 
15500  return DeclRefType;
15501 }
15502 
15503 
15504 
15505 // If either the type of the variable or the initializer is dependent,
15506 // return false. Otherwise, determine whether the variable is a constant
15507 // expression. Use this if you need to know if a variable that might or
15508 // might not be dependent is truly a constant expression.
15510  ASTContext &Context) {
15511 
15512  if (Var->getType()->isDependentType())
15513  return false;
15514  const VarDecl *DefVD = nullptr;
15515  Var->getAnyInitializer(DefVD);
15516  if (!DefVD)
15517  return false;
15518  EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15519  Expr *Init = cast<Expr>(Eval->Value);
15520  if (Init->isValueDependent())
15521  return false;
15522  return IsVariableAConstantExpression(Var, Context);
15523 }
15524 
15525 
15527  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15528  // an object that satisfies the requirements for appearing in a
15529  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15530  // is immediately applied." This function handles the lvalue-to-rvalue
15531  // conversion part.
15532  MaybeODRUseExprs.erase(E->IgnoreParens());
15533 
15534  // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15535  // to a variable that is a constant expression, and if so, identify it as
15536  // a reference to a variable that does not involve an odr-use of that
15537  // variable.
15538  if (LambdaScopeInfo *LSI = getCurLambda()) {
15539  Expr *SansParensExpr = E->IgnoreParens();
15540  VarDecl *Var = nullptr;
15541  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15542  Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15543  else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15544  Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15545 
15546  if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15547  LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15548  }
15549 }
15550 
15552  Res = CorrectDelayedTyposInExpr(Res);
15553 
15554  if (!Res.isUsable())
15555  return Res;
15556 
15557  // If a constant-expression is a reference to a variable where we delay
15558  // deciding whether it is an odr-use, just assume we will apply the
15559  // lvalue-to-rvalue conversion. In the one case where this doesn't happen
15560  // (a non-type template argument), we have special handling anyway.
15561  UpdateMarkingForLValueToRValue(Res.get());
15562  return Res;
15563 }
15564 
15566  for (Expr *E : MaybeODRUseExprs) {
15567  VarDecl *Var;
15568  SourceLocation Loc;
15569  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15570  Var = cast<VarDecl>(DRE->getDecl());
15571  Loc = DRE->getLocation();
15572  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15573  Var = cast<VarDecl>(ME->getMemberDecl());
15574  Loc = ME->getMemberLoc();
15575  } else {
15576  llvm_unreachable("Unexpected expression");
15577  }
15578 
15579  MarkVarDeclODRUsed(Var, Loc, *this,
15580  /*MaxFunctionScopeIndex Pointer*/ nullptr);
15581  }
15582 
15583  MaybeODRUseExprs.clear();
15584 }
15585 
15586 
15587 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15588  VarDecl *Var, Expr *E) {
15589  assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15590  "Invalid Expr argument to DoMarkVarDeclReferenced");
15591  Var->setReferenced();
15592 
15594 
15595  bool OdrUseContext = isOdrUseContext(SemaRef);
15596  bool UsableInConstantExpr =
15597  Var->isUsableInConstantExpressions(SemaRef.Context);
15598  bool NeedDefinition =
15599  OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15600 
15602  dyn_cast<VarTemplateSpecializationDecl>(Var);
15603  assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15604  "Can't instantiate a partial template specialization.");
15605 
15606  // If this might be a member specialization of a static data member, check
15607  // the specialization is visible. We already did the checks for variable
15608  // template specializations when we created them.
15609  if (NeedDefinition && TSK != TSK_Undeclared &&
15610  !isa<VarTemplateSpecializationDecl>(Var))
15611  SemaRef.checkSpecializationVisibility(Loc, Var);
15612 
15613  // Perform implicit instantiation of static data members, static data member
15614  // templates of class templates, and variable template specializations. Delay
15615  // instantiations of variable templates, except for those that could be used
15616  // in a constant expression.
15617  if (NeedDefinition && isTemplateInstantiation(TSK)) {
15618  // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15619  // instantiation declaration if a variable is usable in a constant
15620  // expression (among other cases).
15621  bool TryInstantiating =
15622  TSK == TSK_ImplicitInstantiation ||
15623  (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15624 
15625  if (TryInstantiating) {
15626  SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15627  bool FirstInstantiation = PointOfInstantiation.isInvalid();
15628  if (FirstInstantiation) {
15629  PointOfInstantiation = Loc;
15630  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15631  }
15632 
15633  bool InstantiationDependent = false;
15634  bool IsNonDependent =
15636  VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15637  : true;
15638 
15639  // Do not instantiate specializations that are still type-dependent.
15640  if (IsNonDependent) {
15641  if (UsableInConstantExpr) {
15642  // Do not defer instantiations of variables that could be used in a
15643  // constant expression.
15644  SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15645  } else if (FirstInstantiation ||
15646  isa<VarTemplateSpecializationDecl>(Var)) {
15647  // FIXME: For a specialization of a variable template, we don't
15648  // distinguish between "declaration and type implicitly instantiated"
15649  // and "implicit instantiation of definition requested", so we have
15650  // no direct way to avoid enqueueing the pending instantiation
15651  // multiple times.
15652  SemaRef.PendingInstantiations
15653  .push_back(std::make_pair(Var, PointOfInstantiation));
15654  }
15655  }
15656  }
15657  }
15658 
15659  // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15660  // the requirements for appearing in a constant expression (5.19) and, if
15661  // it is an object, the lvalue-to-rvalue conversion (4.1)
15662  // is immediately applied." We check the first part here, and
15663  // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15664  // Note that we use the C++11 definition everywhere because nothing in
15665  // C++03 depends on whether we get the C++03 version correct. The second
15666  // part does not apply to references, since they are not objects.
15667  if (OdrUseContext && E &&
15668  IsVariableAConstantExpression(Var, SemaRef.Context)) {
15669  // A reference initialized by a constant expression can never be
15670  // odr-used, so simply ignore it.
15671  if (!Var->getType()->isReferenceType() ||
15672  (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15673  SemaRef.MaybeODRUseExprs.insert(E);
15674  } else if (OdrUseContext) {
15675  MarkVarDeclODRUsed(Var, Loc, SemaRef,
15676  /*MaxFunctionScopeIndex ptr*/ nullptr);
15677  } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15678  // If this is a dependent context, we don't need to mark variables as
15679  // odr-used, but we may still need to track them for lambda capture.
15680  // FIXME: Do we also need to do this inside dependent typeid expressions
15681  // (which are modeled as unevaluated at this point)?
15682  const bool RefersToEnclosingScope =
15683  (SemaRef.CurContext != Var->getDeclContext() &&
15684  Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15685  if (RefersToEnclosingScope) {
15686  LambdaScopeInfo *const LSI =
15687  SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15688  if (LSI && (!LSI->CallOperator ||
15689  !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15690  // If a variable could potentially be odr-used, defer marking it so
15691  // until we finish analyzing the full expression for any
15692  // lvalue-to-rvalue
15693  // or discarded value conversions that would obviate odr-use.
15694  // Add it to the list of potential captures that will be analyzed
15695  // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15696  // unless the variable is a reference that was initialized by a constant
15697  // expression (this will never need to be captured or odr-used).
15698  assert(E && "Capture variable should be used in an expression.");
15699  if (!Var->getType()->isReferenceType() ||
15701  LSI->addPotentialCapture(E->IgnoreParens());
15702  }
15703  }
15704  }
15705 }
15706 
15707 /// Mark a variable referenced, and check whether it is odr-used
15708 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
15709 /// used directly for normal expressions referring to VarDecl.
15711  DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15712 }
15713 
15714 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15715  Decl *D, Expr *E, bool MightBeOdrUse) {
15716  if (SemaRef.isInOpenMPDeclareTargetContext())
15717  SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15718 
15719  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15720  DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15721  return;
15722  }
15723 
15724  SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15725 
15726  // If this is a call to a method via a cast, also mark the method in the
15727  // derived class used in case codegen can devirtualize the call.
15728  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15729  if (!ME)
15730  return;
15731  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15732  if (!MD)
15733  return;
15734  // Only attempt to devirtualize if this is truly a virtual call.
15735  bool IsVirtualCall = MD->isVirtual() &&
15736  ME->performsVirtualDispatch(SemaRef.getLangOpts());
15737  if (!IsVirtualCall)
15738  return;
15739 
15740  // If it's possible to devirtualize the call, mark the called function
15741  // referenced.
15743  ME->getBase(), SemaRef.getLangOpts().AppleKext);
15744  if (DM)
15745  SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15746 }
15747 
15748 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15750  // TODO: update this with DR# once a defect report is filed.
15751  // C++11 defect. The address of a pure member should not be an ODR use, even
15752  // if it's a qualified reference.
15753  bool OdrUse = true;
15754  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15755  if (Method->isVirtual() &&
15756  !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15757  OdrUse = false;
15758  MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15759 }
15760 
15761 /// Perform reference-marking and odr-use handling for a MemberExpr.
15763  // C++11 [basic.def.odr]p2:
15764  // A non-overloaded function whose name appears as a potentially-evaluated
15765  // expression or a member of a set of candidate functions, if selected by
15766  // overload resolution when referred to from a potentially-evaluated
15767  // expression, is odr-used, unless it is a pure virtual function and its
15768  // name is not explicitly qualified.
15769  bool MightBeOdrUse = true;
15770  if (E->performsVirtualDispatch(getLangOpts())) {
15771  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15772  if (Method->isPure())
15773  MightBeOdrUse = false;
15774  }
15775  SourceLocation Loc =
15776  E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15777  MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15778 }
15779 
15780 /// Perform marking for a reference to an arbitrary declaration. It
15781 /// marks the declaration referenced, and performs odr-use checking for
15782 /// functions and variables. This method should not be used when building a
15783 /// normal expression which refers to a variable.
15785  bool MightBeOdrUse) {
15786  if (MightBeOdrUse) {
15787  if (auto *VD = dyn_cast<VarDecl>(D)) {
15788  MarkVariableReferenced(Loc, VD);
15789  return;
15790  }
15791  }
15792  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15793  MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15794  return;
15795  }
15796  D->setReferenced();
15797 }
15798 
15799 namespace {
15800  // Mark all of the declarations used by a type as referenced.
15801  // FIXME: Not fully implemented yet! We need to have a better understanding
15802  // of when we're entering a context we should not recurse into.
15803  // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15804  // TreeTransforms rebuilding the type in a new context. Rather than
15805  // duplicating the TreeTransform logic, we should consider reusing it here.
15806  // Currently that causes problems when rebuilding LambdaExprs.
15807  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15808  Sema &S;
15809  SourceLocation Loc;
15810 
15811  public:
15812  typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15813 
15814  MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15815 
15816  bool TraverseTemplateArgument(const TemplateArgument &Arg);
15817  };
15818 }
15819 
15820 bool MarkReferencedDecls::TraverseTemplateArgument(
15821  const TemplateArgument &Arg) {
15822  {
15823  // A non-type template argument is a constant-evaluated context.
15826  if (Arg.getKind() == TemplateArgument::Declaration) {
15827  if (Decl *D = Arg.getAsDecl())
15828  S.MarkAnyDeclReferenced(Loc, D, true);
15829  } else if (Arg.getKind() == TemplateArgument::Expression) {
15831  }
15832  }
15833 
15834  return Inherited::TraverseTemplateArgument(Arg);
15835 }
15836 
15838  MarkReferencedDecls Marker(*this, Loc);
15839  Marker.TraverseType(T);
15840 }
15841 
15842 namespace {
15843  /// Helper class that marks all of the declarations referenced by
15844  /// potentially-evaluated subexpressions as "referenced".
15845  class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15846  Sema &S;
15847  bool SkipLocalVariables;
15848 
15849  public:
15851 
15852  EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15853  : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15854 
15855  void VisitDeclRefExpr(DeclRefExpr *E) {
15856  // If we were asked not to visit local variables, don't.
15857  if (SkipLocalVariables) {
15858  if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15859  if (VD->hasLocalStorage())
15860  return;
15861  }
15862 
15863  S.MarkDeclRefReferenced(E);
15864  }
15865 
15866  void VisitMemberExpr(MemberExpr *E) {
15867  S.MarkMemberReferenced(E);
15868  Inherited::VisitMemberExpr(E);
15869  }
15870 
15871  void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15873  E->getBeginLoc(),
15874  const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
15875  Visit(E->getSubExpr());
15876  }
15877 
15878  void VisitCXXNewExpr(CXXNewExpr *E) {
15879  if (E->getOperatorNew())
15881  if (E->getOperatorDelete())
15883  Inherited::VisitCXXNewExpr(E);
15884  }
15885 
15886  void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15887  if (E->getOperatorDelete())
15890  if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15891  CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15893  }
15894 
15895  Inherited::VisitCXXDeleteExpr(E);
15896  }
15897 
15898  void VisitCXXConstructExpr(CXXConstructExpr *E) {
15900  Inherited::VisitCXXConstructExpr(E);
15901  }
15902 
15903  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15904  Visit(E->getExpr());
15905  }
15906 
15907  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15908  Inherited::VisitImplicitCastExpr(E);
15909 
15910  if (E->getCastKind() == CK_LValueToRValue)
15912  }
15913  };
15914 }
15915 
15916 /// Mark any declarations that appear within this expression or any
15917 /// potentially-evaluated subexpressions as "referenced".
15918 ///
15919 /// \param SkipLocalVariables If true, don't mark local variables as
15920 /// 'referenced'.
15922  bool SkipLocalVariables) {
15923  EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15924 }
15925 
15926 /// Emit a diagnostic that describes an effect on the run-time behavior
15927 /// of the program being compiled.
15928 ///
15929 /// This routine emits the given diagnostic when the code currently being
15930 /// type-checked is "potentially evaluated", meaning that there is a
15931 /// possibility that the code will actually be executable. Code in sizeof()
15932 /// expressions, code used only during overload resolution, etc., are not
15933 /// potentially evaluated. This routine will suppress such diagnostics or,
15934 /// in the absolutely nutty case of potentially potentially evaluated
15935 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15936 /// later.
15937 ///
15938 /// This routine should be used for all diagnostics that describe the run-time
15939 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15940 /// Failure to do so will likely result in spurious diagnostics or failures
15941 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15942 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15943  const PartialDiagnostic &PD) {
15944  switch (ExprEvalContexts.back().Context) {
15945  case ExpressionEvaluationContext::Unevaluated:
15946  case ExpressionEvaluationContext::UnevaluatedList:
15947  case ExpressionEvaluationContext::UnevaluatedAbstract:
15948  case ExpressionEvaluationContext::DiscardedStatement:
15949  // The argument will never be evaluated, so don't complain.
15950  break;
15951 
15952  case ExpressionEvaluationContext::ConstantEvaluated:
15953  // Relevant diagnostics should be produced by constant evaluation.
15954  break;
15955 
15956  case ExpressionEvaluationContext::PotentiallyEvaluated:
15957  case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15958  if (Statement && getCurFunctionOrMethodDecl()) {
15959  FunctionScopes.back()->PossiblyUnreachableDiags.
15960  push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15961  return true;
15962  }
15963 
15964  // The initializer of a constexpr variable or of the first declaration of a
15965  // static data member is not syntactically a constant evaluated constant,
15966  // but nonetheless is always required to be a constant expression, so we
15967  // can skip diagnosing.
15968  // FIXME: Using the mangling context here is a hack.
15969  if (auto *VD = dyn_cast_or_null<VarDecl>(
15970  ExprEvalContexts.back().ManglingContextDecl)) {
15971  if (VD->isConstexpr() ||
15972  (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15973  break;
15974  // FIXME: For any other kind of variable, we should build a CFG for its
15975  // initializer and check whether the context in question is reachable.
15976  }
15977 
15978  Diag(Loc, PD);
15979  return true;
15980  }
15981 
15982  return false;
15983 }
15984 
15986  CallExpr *CE, FunctionDecl *FD) {
15987  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15988  return false;
15989 
15990  // If we're inside a decltype's expression, don't check for a valid return
15991  // type or construct temporaries until we know whether this is the last call.
15992  if (ExprEvalContexts.back().ExprContext ==
15993  ExpressionEvaluationContextRecord::EK_Decltype) {
15994  ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15995  return false;
15996  }
15997 
15998  class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15999  FunctionDecl *FD;
16000  CallExpr *CE;
16001 
16002  public:
16003  CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
16004  : FD(FD), CE(CE) { }
16005 
16006  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16007  if (!FD) {
16008  S.Diag(Loc, diag::err_call_incomplete_return)
16009  << T << CE->getSourceRange();
16010  return;
16011  }
16012 
16013  S.Diag(Loc, diag::err_call_function_incomplete_return)
16014  << CE->getSourceRange() << FD->getDeclName() << T;
16015  S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16016  << FD->getDeclName();
16017  }
16018  } Diagnoser(FD, CE);
16019 
16020  if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16021  return true;
16022 
16023  return false;
16024 }
16025 
16026 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16027 // will prevent this condition from triggering, which is what we want.
16029  SourceLocation Loc;
16030 
16031  unsigned diagnostic = diag::warn_condition_is_assignment;
16032  bool IsOrAssign = false;
16033 
16034  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16035  if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16036  return;
16037 
16038  IsOrAssign = Op->getOpcode() == BO_OrAssign;
16039 
16040  // Greylist some idioms by putting them into a warning subcategory.
16041  if (ObjCMessageExpr *ME
16042  = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16043  Selector Sel = ME->getSelector();
16044 
16045  // self = [<foo> init...]
16046  if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16047  diagnostic = diag::warn_condition_is_idiomatic_assignment;
16048 
16049  // <foo> = [<bar> nextObject]
16050  else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16051  diagnostic = diag::warn_condition_is_idiomatic_assignment;
16052  }
16053 
16054  Loc = Op->getOperatorLoc();
16055  } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16056  if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16057  return;
16058 
16059  IsOrAssign = Op->getOperator() == OO_PipeEqual;
16060  Loc = Op->getOperatorLoc();
16061  } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16062  return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16063  else {
16064  // Not an assignment.
16065  return;
16066  }
16067 
16068  Diag(Loc, diagnostic) << E->getSourceRange();
16069 
16071  SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16072  Diag(Loc, diag::note_condition_assign_silence)
16073  << FixItHint::CreateInsertion(Open, "(")
16074  << FixItHint::CreateInsertion(Close, ")");
16075 
16076  if (IsOrAssign)
16077  Diag(Loc, diag::note_condition_or_assign_to_comparison)
16078  << FixItHint::CreateReplacement(Loc, "!=");
16079  else
16080  Diag(Loc, diag::note_condition_assign_to_comparison)
16081  << FixItHint::CreateReplacement(Loc, "==");
16082 }
16083 
16084 /// Redundant parentheses over an equality comparison can indicate
16085 /// that the user intended an assignment used as condition.
16087  // Don't warn if the parens came from a macro.
16088  SourceLocation parenLoc = ParenE->getBeginLoc();
16089  if (parenLoc.isInvalid() || parenLoc.isMacroID())
16090  return;
16091  // Don't warn for dependent expressions.
16092  if (ParenE->isTypeDependent())
16093  return;
16094 
16095  Expr *E = ParenE->IgnoreParens();
16096 
16097  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
16098  if (opE->getOpcode() == BO_EQ &&
16099  opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
16100  == Expr::MLV_Valid) {
16101  SourceLocation Loc = opE->getOperatorLoc();
16102 
16103  Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
16104  SourceRange ParenERange = ParenE->getSourceRange();
16105  Diag(Loc, diag::note_equality_comparison_silence)
16106  << FixItHint::CreateRemoval(ParenERange.getBegin())
16107  << FixItHint::CreateRemoval(ParenERange.getEnd());
16108  Diag(Loc, diag::note_equality_comparison_to_assign)
16109  << FixItHint::CreateReplacement(Loc, "=");
16110  }
16111 }
16112 
16114  bool IsConstexpr) {
16115  DiagnoseAssignmentAsCondition(E);
16116  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
16117  DiagnoseEqualityWithExtraParens(parenE);
16118 
16119  ExprResult result = CheckPlaceholderExpr(E);
16120  if (result.isInvalid()) return ExprError();
16121  E = result.get();
16122 
16123  if (!E->isTypeDependent()) {
16124  if (getLangOpts().CPlusPlus)
16125  return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
16126 
16127  ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
16128  if (ERes.isInvalid())
16129  return ExprError();
16130  E = ERes.get();
16131 
16132  QualType T = E->getType();
16133  if (!T->isScalarType()) { // C99 6.8.4.1p1
16134  Diag(Loc, diag::err_typecheck_statement_requires_scalar)
16135  << T << E->getSourceRange();
16136  return ExprError();
16137  }
16138  CheckBoolLikeConversion(E, Loc);
16139  }
16140 
16141  return E;
16142 }
16143 
16145  Expr *SubExpr, ConditionKind CK) {
16146  // Empty conditions are valid in for-statements.
16147  if (!SubExpr)
16148  return ConditionResult();
16149 
16150  ExprResult Cond;
16151  switch (CK) {
16152  case ConditionKind::Boolean:
16153  Cond = CheckBooleanCondition(Loc, SubExpr);
16154  break;
16155 
16156  case ConditionKind::ConstexprIf:
16157  Cond = CheckBooleanCondition(Loc, SubExpr, true);
16158  break;
16159 
16160  case ConditionKind::Switch:
16161  Cond = CheckSwitchCondition(Loc, SubExpr);
16162  break;
16163  }
16164  if (Cond.isInvalid())
16165  return ConditionError();
16166 
16167  // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
16168  FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
16169  if (!FullExpr.get())
16170  return ConditionError();
16171 
16172  return ConditionResult(*this, nullptr, FullExpr,
16173  CK == ConditionKind::ConstexprIf);
16174 }
16175 
16176 namespace {
16177  /// A visitor for rebuilding a call to an __unknown_any expression
16178  /// to have an appropriate type.
16179  struct RebuildUnknownAnyFunction
16180  : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
16181 
16182  Sema &S;
16183 
16184  RebuildUnknownAnyFunction(Sema &S) : S(S) {}
16185 
16186  ExprResult VisitStmt(Stmt *S) {
16187  llvm_unreachable("unexpected statement!");
16188  }
16189 
16190  ExprResult VisitExpr(Expr *E) {
16191  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
16192  << E->getSourceRange();
16193  return ExprError();
16194  }
16195 
16196  /// Rebuild an expression which simply semantically wraps another
16197  /// expression which it shares the type and value kind of.
16198  template <class T> ExprResult rebuildSugarExpr(T *E) {
16199  ExprResult SubResult = Visit(E->getSubExpr());
16200  if (SubResult.isInvalid()) return ExprError();
16201 
16202  Expr *SubExpr = SubResult.get();
16203  E->setSubExpr(SubExpr);
16204  E->setType(SubExpr->getType());
16205  E->setValueKind(SubExpr->getValueKind());
16206  assert(E->getObjectKind() == OK_Ordinary);
16207  return E;
16208  }
16209 
16210  ExprResult VisitParenExpr(ParenExpr *E) {
16211  return rebuildSugarExpr(E);
16212  }
16213 
16214  ExprResult VisitUnaryExtension(UnaryOperator *E) {
16215  return rebuildSugarExpr(E);
16216  }
16217 
16218  ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16219  ExprResult SubResult = Visit(E->getSubExpr());
16220  if (SubResult.isInvalid()) return ExprError();
16221 
16222  Expr *SubExpr = SubResult.get();
16223  E->setSubExpr(SubExpr);
16224  E->setType(S.Context.getPointerType(SubExpr->getType()));
16225  assert(E->getValueKind() == VK_RValue);
16226  assert(E->getObjectKind() == OK_Ordinary);
16227  return E;
16228  }
16229 
16230  ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
16231  if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
16232 
16233  E->setType(VD->getType());
16234 
16235  assert(E->getValueKind() == VK_RValue);
16236  if (S.getLangOpts().CPlusPlus &&
16237  !(isa<CXXMethodDecl>(VD) &&
16238  cast<CXXMethodDecl>(VD)->isInstance()))
16239  E->setValueKind(VK_LValue);
16240 
16241  return E;
16242  }
16243 
16244  ExprResult VisitMemberExpr(MemberExpr *E) {
16245  return resolveDecl(E, E->getMemberDecl());
16246  }
16247 
16248  ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16249  return resolveDecl(E, E->getDecl());
16250  }
16251  };
16252 }
16253 
16254 /// Given a function expression of unknown-any type, try to rebuild it
16255 /// to have a function type.
16256 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
16257  ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
16258  if (Result.isInvalid()) return ExprError();
16259  return S.DefaultFunctionArrayConversion(Result.get());
16260 }
16261 
16262 namespace {
16263  /// A visitor for rebuilding an expression of type __unknown_anytype
16264  /// into one which resolves the type directly on the referring
16265  /// expression. Strict preservation of the original source
16266  /// structure is not a goal.
16267  struct RebuildUnknownAnyExpr
16268  : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16269 
16270  Sema &S;
16271 
16272  /// The current destination type.
16273  QualType DestType;
16274 
16275  RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16276  : S(S), DestType(CastType) {}
16277 
16278  ExprResult VisitStmt(Stmt *S) {
16279  llvm_unreachable("unexpected statement!");
16280  }
16281 
16282  ExprResult VisitExpr(Expr *E) {
16283  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16284  << E->getSourceRange();
16285  return ExprError();
16286  }
16287 
16288  ExprResult VisitCallExpr(CallExpr *E);
16289  ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16290 
16291  /// Rebuild an expression which simply semantically wraps another
16292  /// expression which it shares the type and value kind of.
16293  template <class T> ExprResult rebuildSugarExpr(T *E) {
16294  ExprResult SubResult = Visit(E->getSubExpr());
16295  if (SubResult.isInvalid()) return ExprError();
16296  Expr *SubExpr = SubResult.get();
16297  E->setSubExpr(SubExpr);
16298  E->setType(SubExpr->getType());
16299  E->setValueKind(SubExpr->getValueKind());
16300  assert(E->getObjectKind() == OK_Ordinary);
16301  return E;
16302  }
16303 
16304  ExprResult VisitParenExpr(ParenExpr *E) {
16305  return rebuildSugarExpr(E);
16306  }
16307 
16308  ExprResult VisitUnaryExtension(UnaryOperator *E) {
16309  return rebuildSugarExpr(E);
16310  }
16311 
16312  ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16313  const PointerType *Ptr = DestType->getAs<PointerType>();
16314  if (!Ptr) {
16315  S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16316  << E->getSourceRange();
16317  return ExprError();
16318  }
16319 
16320  if (isa<CallExpr>(E->getSubExpr())) {
16321  S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16322  << E->getSourceRange();
16323  return ExprError();
16324  }
16325 
16326  assert(E->getValueKind() == VK_RValue);
16327  assert(E->getObjectKind() == OK_Ordinary);
16328  E->setType(DestType);
16329 
16330  // Build the sub-expression as if it were an object of the pointee type.
16331  DestType = Ptr->getPointeeType();
16332  ExprResult SubResult = Visit(E->getSubExpr());
16333  if (SubResult.isInvalid()) return ExprError();
16334  E->setSubExpr(SubResult.get());
16335  return E;
16336  }
16337 
16338  ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16339 
16340  ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16341 
16342  ExprResult VisitMemberExpr(MemberExpr *E) {
16343  return resolveDecl(E, E->getMemberDecl());
16344  }
16345 
16346  ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16347  return resolveDecl(E, E->getDecl());
16348  }
16349  };
16350 }
16351 
16352 /// Rebuilds a call expression which yielded __unknown_anytype.
16353 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16354  Expr *CalleeExpr = E->getCallee();
16355 
16356  enum FnKind {
16357  FK_MemberFunction,
16358  FK_FunctionPointer,
16359  FK_BlockPointer
16360  };
16361 
16362  FnKind Kind;
16363  QualType CalleeType = CalleeExpr->getType();
16364  if (CalleeType == S.Context.BoundMemberTy) {
16365  assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16366  Kind = FK_MemberFunction;
16367  CalleeType = Expr::findBoundMemberType(CalleeExpr);
16368  } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16369  CalleeType = Ptr->getPointeeType();
16370  Kind = FK_FunctionPointer;
16371  } else {
16372  CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16373  Kind = FK_BlockPointer;
16374  }
16375  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16376 
16377  // Verify that this is a legal result type of a function.
16378  if (DestType->isArrayType() || DestType->isFunctionType()) {
16379  unsigned diagID = diag::err_func_returning_array_function;
16380  if (Kind == FK_BlockPointer)
16381  diagID = diag::err_block_returning_array_function;
16382 
16383  S.Diag(E->getExprLoc(), diagID)
16384  << DestType->isFunctionType() << DestType;
16385  return ExprError();
16386  }
16387 
16388  // Otherwise, go ahead and set DestType as the call's result.
16389  E->setType(DestType.getNonLValueExprType(S.Context));
16391  assert(E->getObjectKind() == OK_Ordinary);
16392 
16393  // Rebuild the function type, replacing the result type with DestType.
16394  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16395  if (Proto) {
16396  // __unknown_anytype(...) is a special case used by the debugger when
16397  // it has no idea what a function's signature is.
16398  //
16399  // We want to build this call essentially under the K&R
16400  // unprototyped rules, but making a FunctionNoProtoType in C++
16401  // would foul up all sorts of assumptions. However, we cannot
16402  // simply pass all arguments as variadic arguments, nor can we
16403  // portably just call the function under a non-variadic type; see
16404  // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16405  // However, it turns out that in practice it is generally safe to
16406  // call a function declared as "A foo(B,C,D);" under the prototype
16407  // "A foo(B,C,D,...);". The only known exception is with the
16408  // Windows ABI, where any variadic function is implicitly cdecl
16409  // regardless of its normal CC. Therefore we change the parameter
16410  // types to match the types of the arguments.
16411  //
16412  // This is a hack, but it is far superior to moving the
16413  // corresponding target-specific code from IR-gen to Sema/AST.
16414 
16415  ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16416  SmallVector<QualType, 8> ArgTypes;
16417  if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16418  ArgTypes.reserve(E->getNumArgs());
16419  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16420  Expr *Arg = E->getArg(i);
16421  QualType ArgType = Arg->getType();
16422  if (E->isLValue()) {
16423  ArgType = S.Context.getLValueReferenceType(ArgType);
16424  } else if (E->isXValue()) {
16425  ArgType = S.Context.getRValueReferenceType(ArgType);
16426  }
16427  ArgTypes.push_back(ArgType);
16428  }
16429  ParamTypes = ArgTypes;
16430  }
16431  DestType = S.Context.getFunctionType(DestType, ParamTypes,
16432  Proto->getExtProtoInfo());
16433  } else {
16434  DestType = S.Context.getFunctionNoProtoType(DestType,
16435  FnType->getExtInfo());
16436  }
16437 
16438  // Rebuild the appropriate pointer-to-function type.
16439  switch (Kind) {
16440  case FK_MemberFunction:
16441  // Nothing to do.
16442  break;
16443 
16444  case FK_FunctionPointer:
16445  DestType = S.Context.getPointerType(DestType);
16446  break;
16447 
16448  case FK_BlockPointer:
16449  DestType = S.Context.getBlockPointerType(DestType);
16450  break;
16451  }
16452 
16453  // Finally, we can recurse.
16454  ExprResult CalleeResult = Visit(CalleeExpr);
16455  if (!CalleeResult.isUsable()) return ExprError();
16456  E->setCallee(CalleeResult.get());
16457 
16458  // Bind a temporary if necessary.
16459  return S.MaybeBindToTemporary(E);
16460 }
16461 
16462 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16463  // Verify that this is a legal result type of a call.
16464  if (DestType->isArrayType() || DestType->isFunctionType()) {
16465  S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16466  << DestType->isFunctionType() << DestType;
16467  return ExprError();
16468  }
16469 
16470  // Rewrite the method result type if available.
16471  if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16472  assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16473  Method->setReturnType(DestType);
16474  }
16475 
16476  // Change the type of the message.
16477  E->setType(DestType.getNonReferenceType());
16479 
16480  return S.MaybeBindToTemporary(E);
16481 }
16482 
16483 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16484  // The only case we should ever see here is a function-to-pointer decay.
16485  if (E->getCastKind() == CK_FunctionToPointerDecay) {
16486  assert(E->getValueKind() == VK_RValue);
16487  assert(E->getObjectKind() == OK_Ordinary);
16488 
16489  E->setType(DestType);
16490 
16491  // Rebuild the sub-expression as the pointee (function) type.
16492  DestType = DestType->castAs<PointerType>()->getPointeeType();
16493 
16494  ExprResult Result = Visit(E->getSubExpr());
16495  if (!Result.isUsable()) return ExprError();
16496 
16497  E->setSubExpr(Result.get());
16498  return E;
16499  } else if (E->getCastKind() == CK_LValueToRValue) {
16500  assert(E->getValueKind() == VK_RValue);
16501  assert(E->getObjectKind() == OK_Ordinary);
16502 
16503  assert(isa<BlockPointerType>(E->getType()));
16504 
16505  E->setType(DestType);
16506 
16507  // The sub-expression has to be a lvalue reference, so rebuild it as such.
16508  DestType = S.Context.getLValueReferenceType(DestType);
16509 
16510  ExprResult Result = Visit(E->getSubExpr());
16511  if (!Result.isUsable()) return ExprError();
16512 
16513  E->setSubExpr(Result.get());
16514  return E;
16515  } else {
16516  llvm_unreachable("Unhandled cast type!");
16517  }
16518 }
16519 
16520 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16521  ExprValueKind ValueKind = VK_LValue;
16522  QualType Type = DestType;
16523 
16524  // We know how to make this work for certain kinds of decls:
16525 
16526  // - functions
16527  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16528  if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16529  DestType = Ptr->getPointeeType();
16530  ExprResult Result = resolveDecl(E, VD);
16531  if (Result.isInvalid()) return ExprError();
16532  return S.ImpCastExprToType(Result.get(), Type,
16533  CK_FunctionToPointerDecay, VK_RValue);
16534  }
16535 
16536  if (!Type->isFunctionType()) {
16537  S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16538  << VD << E->getSourceRange();
16539  return ExprError();
16540  }
16541  if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16542  // We must match the FunctionDecl's type to the hack introduced in
16543  // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16544  // type. See the lengthy commentary in that routine.
16545  QualType FDT = FD->getType();
16546  const FunctionType *FnType = FDT->castAs<FunctionType>();
16547  const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16548  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16549  if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16550  SourceLocation Loc = FD->getLocation();
16552  FD->getDeclContext(),
16553  Loc, Loc, FD->getNameInfo().getName(),
16554  DestType, FD->getTypeSourceInfo(),
16555  SC_None, false/*isInlineSpecified*/,
16556  FD->hasPrototype(),
16557  false/*isConstexprSpecified*/);
16558 
16559  if (FD->getQualifier())
16560  NewFD->setQualifierInfo(FD->getQualifierLoc());
16561 
16563  for (const auto &AI : FT->param_types()) {
16564  ParmVarDecl *Param =
16565  S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16566  Param->setScopeInfo(0, Params.size());
16567  Params.push_back(Param);
16568  }
16569  NewFD->setParams(Params);
16570  DRE->setDecl(NewFD);
16571  VD = DRE->getDecl();
16572  }
16573  }
16574 
16575  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16576  if (MD->isInstance()) {
16577  ValueKind = VK_RValue;
16578  Type = S.Context.BoundMemberTy;
16579  }
16580 
16581  // Function references aren't l-values in C.
16582  if (!S.getLangOpts().CPlusPlus)
16583  ValueKind = VK_RValue;
16584 
16585  // - variables
16586  } else if (isa<VarDecl>(VD)) {
16587  if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16588  Type = RefTy->getPointeeType();
16589  } else if (Type->isFunctionType()) {
16590  S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16591  << VD << E->getSourceRange();
16592  return ExprError();
16593  }
16594 
16595  // - nothing else
16596  } else {
16597  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16598  << VD << E->getSourceRange();
16599  return ExprError();
16600  }
16601 
16602  // Modifying the declaration like this is friendly to IR-gen but
16603  // also really dangerous.
16604  VD->setType(DestType);
16605  E->setType(Type);
16606  E->setValueKind(ValueKind);
16607  return E;
16608 }
16609 
16610 /// Check a cast of an unknown-any type. We intentionally only
16611 /// trigger this for C-style casts.
16614  ExprValueKind &VK, CXXCastPath &Path) {
16615  // The type we're casting to must be either void or complete.
16616  if (!CastType->isVoidType() &&
16617  RequireCompleteType(TypeRange.getBegin(), CastType,
16618  diag::err_typecheck_cast_to_incomplete))
16619  return ExprError();
16620 
16621  // Rewrite the casted expression from scratch.
16622  ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16623  if (!result.isUsable()) return ExprError();
16624 
16625  CastExpr = result.get();
16626  VK = CastExpr->getValueKind();
16627  CastKind = CK_NoOp;
16628 
16629  return CastExpr;
16630 }
16631 
16633  return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16634 }
16635 
16637  Expr *arg, QualType &paramType) {
16638  // If the syntactic form of the argument is not an explicit cast of
16639  // any sort, just do default argument promotion.
16640  ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16641  if (!castArg) {
16642  ExprResult result = DefaultArgumentPromotion(arg);
16643  if (result.isInvalid()) return ExprError();
16644  paramType = result.get()->getType();
16645  return result;
16646  }
16647 
16648  // Otherwise, use the type that was written in the explicit cast.
16649  assert(!arg->hasPlaceholderType());
16650  paramType = castArg->getTypeAsWritten();
16651 
16652  // Copy-initialize a parameter of that type.
16653  InitializedEntity entity =
16654  InitializedEntity::InitializeParameter(Context, paramType,
16655  /*consumed*/ false);
16656  return PerformCopyInitialization(entity, callLoc, arg);
16657 }
16658 
16660  Expr *orig = E;
16661  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16662  while (true) {
16663  E = E->IgnoreParenImpCasts();
16664  if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16665  E = call->getCallee();
16666  diagID = diag::err_uncasted_call_of_unknown_any;
16667  } else {
16668  break;
16669  }
16670  }
16671 
16672  SourceLocation loc;
16673  NamedDecl *d;
16674  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16675  loc = ref->getLocation();
16676  d = ref->getDecl();
16677  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16678  loc = mem->getMemberLoc();
16679  d = mem->getMemberDecl();
16680  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16681  diagID = diag::err_uncasted_call_of_unknown_any;
16682  loc = msg->getSelectorStartLoc();
16683  d = msg->getMethodDecl();
16684  if (!d) {
16685  S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16686  << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16687  << orig->getSourceRange();
16688  return ExprError();
16689  }
16690  } else {
16691  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16692  << E->getSourceRange();
16693  return ExprError();
16694  }
16695 
16696  S.Diag(loc, diagID) << d << orig->getSourceRange();
16697 
16698  // Never recoverable.
16699  return ExprError();
16700 }
16701 
16702 /// Check for operands with placeholder types and complain if found.
16703 /// Returns ExprError() if there was an error and no recovery was possible.
16705  if (!getLangOpts().CPlusPlus) {
16706  // C cannot handle TypoExpr nodes on either side of a binop because it
16707  // doesn't handle dependent types properly, so make sure any TypoExprs have
16708  // been dealt with before checking the operands.
16709  ExprResult Result = CorrectDelayedTyposInExpr(E);
16710  if (!Result.isUsable()) return ExprError();
16711  E = Result.get();
16712  }
16713 
16714  const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16715  if (!placeholderType) return E;
16716 
16717  switch (placeholderType->getKind()) {
16718 
16719  // Overloaded expressions.
16720  case BuiltinType::Overload: {
16721  // Try to resolve a single function template specialization.
16722  // This is obligatory.
16723  ExprResult Result = E;
16724  if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16725  return Result;
16726 
16727  // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16728  // leaves Result unchanged on failure.
16729  Result = E;
16730  if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16731  return Result;
16732 
16733  // If that failed, try to recover with a call.
16734  tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16735  /*complain*/ true);
16736  return Result;
16737  }
16738 
16739  // Bound member functions.
16740  case BuiltinType::BoundMember: {
16741  ExprResult result = E;
16742  const Expr *BME = E->IgnoreParens();
16743  PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16744  // Try to give a nicer diagnostic if it is a bound member that we recognize.
16745  if (isa<CXXPseudoDestructorExpr>(BME)) {
16746  PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16747  } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16748  if (ME->getMemberNameInfo().getName().getNameKind() ==
16750  PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16751  }
16752  tryToRecoverWithCall(result, PD,
16753  /*complain*/ true);
16754  return result;
16755  }
16756 
16757  // ARC unbridged casts.
16758  case BuiltinType::ARCUnbridgedCast: {
16759  Expr *realCast = stripARCUnbridgedCast(E);
16760  diagnoseARCUnbridgedCast(realCast);
16761  return realCast;
16762  }
16763 
16764  // Expressions of unknown type.
16765  case BuiltinType::UnknownAny:
16766  return diagnoseUnknownAnyExpr(*this, E);
16767 
16768  // Pseudo-objects.
16769  case BuiltinType::PseudoObject:
16770  return checkPseudoObjectRValue(E);
16771 
16772  case BuiltinType::BuiltinFn: {
16773  // Accept __noop without parens by implicitly converting it to a call expr.
16774  auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16775  if (DRE) {
16776  auto *FD = cast<FunctionDecl>(DRE->getDecl());
16777  if (FD->getBuiltinID() == Builtin::BI__noop) {
16778  E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16779  CK_BuiltinFnToFnPtr)
16780  .get();
16781  return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
16783  }
16784  }
16785 
16786  Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16787  return ExprError();
16788  }
16789 
16790  // Expressions of unknown type.
16791  case BuiltinType::OMPArraySection:
16792  Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16793  return ExprError();
16794 
16795  // Everything else should be impossible.
16796 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16797  case BuiltinType::Id:
16798 #include "clang/Basic/OpenCLImageTypes.def"
16799 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16800  case BuiltinType::Id:
16801 #include "clang/Basic/OpenCLExtensionTypes.def"
16802 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16803 #define PLACEHOLDER_TYPE(Id, SingletonId)
16804 #include "clang/AST/BuiltinTypes.def"
16805  break;
16806  }
16807 
16808  llvm_unreachable("invalid placeholder type!");
16809 }
16810 
16812  if (E->isTypeDependent())
16813  return true;
16814  if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16815  return E->getType()->isIntegralOrEnumerationType();
16816  return false;
16817 }
16818 
16819 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16820 ExprResult
16822  assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16823  "Unknown Objective-C Boolean value!");
16824  QualType BoolT = Context.ObjCBuiltinBoolTy;
16825  if (!Context.getBOOLDecl()) {
16826  LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16828  if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16829  NamedDecl *ND = Result.getFoundDecl();
16830  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16831  Context.setBOOLDecl(TD);
16832  }
16833  }
16834  if (Context.getBOOLDecl())
16835  BoolT = Context.getBOOLType();
16836  return new (Context)
16837  ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16838 }
16839 
16842  SourceLocation RParen) {
16843 
16844  StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16845 
16846  auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16847  [&](const AvailabilitySpec &Spec) {
16848  return Spec.getPlatform() == Platform;
16849  });
16850 
16851  VersionTuple Version;
16852  if (Spec != AvailSpecs.end())
16853  Version = Spec->getVersion();
16854 
16855  // The use of `@available` in the enclosing function should be analyzed to
16856  // warn when it's used inappropriately (i.e. not if(@available)).
16857  if (getCurFunctionOrMethodDecl())
16858  getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16859  else if (getCurBlock() || getCurLambda())
16860  getCurFunction()->HasPotentialAvailabilityViolations = true;
16861 
16862  return new (Context)
16863  ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16864 }
Abstract class used to diagnose incomplete types.
Definition: Sema.h:1510
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:9011
const Expr * getSubExpr() const
Definition: Expr.h:890
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1530
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
Definition: SemaExpr.cpp:12501
Defines the clang::ASTContext interface.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
const BlockDecl * getBlockDecl() const
Definition: Expr.h:5191
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1535
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2242
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false)
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:15921
VariadicCallType
Definition: Sema.h:9462
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1583
QualType getCurrentThisType()
Try to retrieve the type of the &#39;this&#39; pointer.
QualType withConst() const
Retrieves a version of this type with const applied.
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK)
Definition: SemaExpr.cpp:16144
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1196
bool isClassMethod() const
Definition: DeclObjC.h:430
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:12857
CanQualType LongLongTy
Definition: ASTContext.h:1025
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void setImplicit(bool I=true)
Definition: DeclBase.h:548
void MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt)
Definition: SemaInternal.h:70
Represents a function declaration or definition.
Definition: Decl.h:1738
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:14841
Stmt * body_back()
Definition: Stmt.h:1279
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition: Type.cpp:1630
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:2543
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:6338
bool isForRedeclaration() const
True if this lookup is just looking for an existing declaration.
Definition: Lookup.h:256
SourceRange getCorrectionRange() const
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc", where we know the signature a priori.
Definition: Builtins.h:141
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:755
bool isSignedOverflowDefined() const
Definition: LangOptions.h:272
CanQualType AccumTy
Definition: ASTContext.h:1029
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
void setKind(UnqualifiedIdKind kind)
Definition: DeclSpec.h:1017
Smart pointer class that efficiently represents Objective-C method names.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1849
A class which contains all the information about a particular captured value.
Definition: Decl.h:3864
PtrTy get() const
Definition: Ownership.h:81
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:14423
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2537
EvaluatedExprVisitor - This class visits &#39;Expr *&#39;s.
QualType getPointeeType() const
Definition: Type.h:2550
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc)
Definition: SemaExpr.cpp:3248
A (possibly-)qualified type.
Definition: Type.h:638
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
bool isBlockPointerType() const
Definition: Type.h:6304
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:6609
Simple class containing the result of Sema::CorrectTypo.
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType)
Definition: SemaExpr.cpp:11351
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2101
bool isArrayType() const
Definition: Type.h:6345
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:430
bool isMemberPointerType() const
Definition: Type.h:6327
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2773
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter&#39;s...
Definition: Overload.h:79
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:7002
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2376
unsigned char getFixedPointScale(QualType Ty) const
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2553
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition: Decl.h:3977
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
Definition: SemaExpr.cpp:12099
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1144
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:2902
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:228
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:8995
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:1904
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:7467
unsigned getLongWidth() const
getLongWidth/Align - Return the size of &#39;signed long&#39; and &#39;unsigned long&#39; for this target...
Definition: TargetInfo.h:388
DeclContext * getFunctionLevelDeclContext()
Definition: Sema.cpp:1183
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3210
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
Definition: SemaExpr.cpp:1034
llvm::APSInt getValue() const
Definition: FixedPoint.h:86
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:6189
CanQualType FractTy
Definition: ASTContext.h:1032
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C...
Definition: Type.h:6252
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3055
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:6511
CanQualType Char32Ty
Definition: ASTContext.h:1024
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:6596
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:16659
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:246
static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, QualType FieldType, QualType DeclRefType, SourceLocation Loc, bool RefersToCapturedVariable)
Create a field within the lambda class for the variable being captured.
Definition: SemaExpr.cpp:15142
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3073
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:219
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
bool isArithmeticType() const
Definition: Type.cpp:1952
Stmt - This represents one statement.
Definition: Stmt.h:66
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2540
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:39
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:286
Kind getKind() const
Definition: Type.h:2418
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3355
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1937
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:650
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
Definition: ScopeInfo.cpp:116
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:10917
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:472
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4227
Represents the declaration of a typedef-name via the &#39;typedef&#39; type specifier.
Definition: Decl.h:3018
Defines the SourceManager interface.
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:807
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed...
Definition: SemaExpr.cpp:4786
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2094
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:114
The template argument is an expression, and we&#39;ve not resolved it to one of the other forms yet...
Definition: TemplateBase.h:87
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:9844
bool isAscii() const
Definition: Expr.h:1685
bool isRecordType() const
Definition: Type.h:6369
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Definition: SemaExpr.cpp:8406
Expr * getBase() const
Definition: Expr.h:2767
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:11306
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:6531
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1933
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
const Type * getTypeForDecl() const
Definition: Decl.h:2898
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1308
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:8936
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:608
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
Definition: SemaExpr.cpp:6520
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:13546
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:11114
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4002
bool isVirtual() const
Definition: DeclCXX.h:2086
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:2033
bool isExtVectorType() const
Definition: Type.h:6385
void setType(QualType t)
Definition: Expr.h:129
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed...
Definition: Sema.h:7649
AssignConvertType
AssignConvertType - All of the &#39;assignment&#39; semantic checks return this enum to indicate whether the ...
Definition: Sema.h:9522
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:2828
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:10931
Defines the C++ template declaration subclasses.
Opcode getOpcode() const
Definition: Expr.h:3322
This is a while, do, switch, for, etc that can have break statements embedded into it...
Definition: Scope.h:52
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:828
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer...
Definition: SemaExpr.cpp:6803
Not a narrowing conversion.
Definition: Overload.h:205
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:3666
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:732
bool isCopyCapture() const
Definition: ScopeInfo.h:569
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1844
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6245
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:3906
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:16632
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4500
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1047
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2763
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13798
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
The base class of the type hierarchy.
Definition: Type.h:1407
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanQualType LongTy
Definition: ASTContext.h:1025
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:9603
bool isClkEventT() const
Definition: Type.h:6458
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:9318
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1890
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2812
Declaration of a variable template.
QualType getCorrespondingUnsignedType(QualType T) const
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:64
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1262
SourceLocation getEndLoc() const LLVM_READONLY
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:395
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:308
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
QualType withConst() const
Definition: Type.h:810
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
Definition: SemaExpr.cpp:9702
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:3621
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:690
TemplateNameKind Kind
The kind of template that Template refers to.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
A container of type source information.
Definition: Decl.h:87
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2324
static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:978
QualType getLogicalOperationType() const
The result type of logical operations, &#39;<&#39;, &#39;>&#39;, &#39;!=&#39;, etc.
Definition: ASTContext.h:1785
Floating point control options.
Definition: LangOptions.h:307
constexpr XRayInstrMask Function
Definition: XRayInstr.h:39
MS property subscript expression.
Definition: ExprCXX.h:828
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:2720
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10769
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:11178
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to...
Definition: Decl.h:1210
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1163
bool isImplicitlyInstantiable() const
Determines whether this function is a function template specialization or a member of a class templat...
Definition: Decl.cpp:3362
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:9977
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
Definition: SemaExpr.cpp:6942
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2484
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:543
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:4665
CanQualType WideCharTy
Definition: ASTContext.h:1020
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr *> Args)
Definition: SemaExpr.cpp:4834
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3)
Definition: SemaExpr.cpp:14628
size_t param_size() const
Definition: Decl.h:2278
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:13084
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
isModifiableLvalueResult
Definition: Expr.h:269
CanQualType HalfTy
Definition: ASTContext.h:1040
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:13914
QualType getElementType() const
Definition: Type.h:2847
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:540
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:13292
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:97
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1884
This file provides some common utility functions for processing Lambda related AST Constructs...
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:6250
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:9756
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:575
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.cpp:508
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:2708
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10853
Represents a variable declaration or definition.
Definition: Decl.h:813
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:1012
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:241
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1765
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC &#39;id&#39; type.
Definition: ExprObjC.h:1437
void removeObjCLifetime()
Definition: Type.h:332
QualType getReturnType() const
Definition: Decl.h:2302
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2925
bool isParamConsumed(unsigned I) const
Definition: Type.h:4092
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:9733
unsigned getNumParams() const
Definition: Type.h:3888
bool isEnumeralType() const
Definition: Type.h:6373
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
APFixedPoint getFixedPointMax(QualType Ty) const
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6748
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:6670
CanQualType Float128Ty
Definition: ASTContext.h:1028
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Extra information about a function prototype.
Definition: Type.h:3767
CanQualType ShortAccumTy
Definition: ASTContext.h:1029
std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD)
Retrieve the message suffix that should be added to a diagnostic complaining about the given function...
Definition: SemaExpr.cpp:327
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:26
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, const FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
Definition: SemaExpr.cpp:5238
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
Definition: SemaExpr.cpp:8508
Represents a variable template specialization, which refers to a variable template with a given set o...
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:432
bool isAmbiguous() const
Definition: Lookup.h:290
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Definition: Expr.h:747
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
DeclClass * getCorrectionDeclAs() const
static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
If two different enums are compared, raise a warning.
Definition: SemaExpr.cpp:9662
static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Converts an integer to complex float type.
Definition: SemaExpr.cpp:956
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:13206
bool isInvalidDecl() const
Definition: DeclBase.h:542
bool isOverloaded() const
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:3849
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:177
static InitializationKind CreateDirectList(SourceLocation InitLoc)
CanQualType ShortFractTy
Definition: ASTContext.h:1032
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input)
Definition: SemaExpr.cpp:13121
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:15276
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Definition: ExprCXX.h:3089
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
Definition: SemaExpr.cpp:10989
std::vector< FixItHint > Hints
The list of Hints generated so far.
Represents a parameter to a function.
Definition: Decl.h:1550
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
Defines the clang::Expr interface and subclasses for C++ expressions.
tok::TokenKind getKind() const
Definition: Token.h:90
bool isAdditiveOp() const
Definition: Expr.h:3364
bool isEqualityOp() const
Definition: Expr.h:3375
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1952
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:9214
The collection of all-type qualifiers we support.
Definition: Type.h:141
bool isVariableArrayType() const
Definition: Type.h:6357
tok::TokenKind ContextKind
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g., it is a floating-point type or a vector thereof.
Definition: Type.cpp:1930
bool isARCPseudoStrong() const
Determine whether this variable is an ARC pseudo-__strong variable.
Definition: Decl.h:1360
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5421
bool isXValue() const
Definition: Expr.h:251
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type. ...
Definition: Decl.cpp:3202
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:15837
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:57
LabelStmt - Represents a label, which has a substatement.
Definition: Stmt.h:1593
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
Definition: Expr.h:3162
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:7751
Represents a struct/union/class.
Definition: Decl.h:3593
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
Definition: SemaExpr.cpp:6888
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:96
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
Definition: SemaExpr.cpp:7152
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:348
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:416
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:986
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6...
Definition: SemaExpr.cpp:683
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:298
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4185
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1148
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.h:371
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3768
One of these records is kept for each identifier that is lexed.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:860
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1018
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
Definition: SemaExpr.cpp:1210
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations. ...
Definition: Decl.cpp:1817
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, QualType SrcType)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
Definition: SemaExpr.cpp:12245
void DiagnoseUnusedExprResult(const Stmt *S)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused...
Definition: SemaStmt.cpp:199
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Represents a class type in Objective C.
Definition: Type.h:5538
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:132
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:330
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
Definition: SemaExpr.cpp:7385
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, Sema &S)
Capture the given variable in the captured region.
Definition: SemaExpr.cpp:15081
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
A C++ nested-name-specifier augmented with source location information.
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:7520
ExprResult ExprEmpty()
Definition: Ownership.h:289
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:9046
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3895
LineState State
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3941
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
ObjCMethodFamily
A family of Objective-C methods.
Used for GCC&#39;s __alignof.
Definition: TypeTraits.h:107
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:877
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, bool &InstantiationDependent)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:3297
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
Definition: SemaExpr.cpp:7576
bool isCharType() const
Definition: Type.cpp:1787
field_range fields() const
Definition: Decl.h:3784
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
NameKind getNameKind() const
Determine what kind of name this is.
bool isObjCIdType() const
Definition: Type.h:6422
Represents a member of a struct/union/class.
Definition: Decl.h:2579
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We&#39;ve found a use of a templated declaration that would trigger an implicit instantiation.
The current expression is potentially evaluated at run time, which means that code may be generated t...
void setBOOLDecl(TypedefDecl *TD)
Save declaration of &#39;BOOL&#39; typedef.
Definition: ASTContext.h:1885
Identity conversion (no conversion)
Definition: Overload.h:81
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:97
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:231
CanQualType LongAccumTy
Definition: ASTContext.h:1029
Floating point conversions (C++ [conv.double].
Definition: Overload.h:111
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4057
bool isReferenceType() const
Definition: Type.h:6308
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2563
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:16086
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:496
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition: Expr.h:2574
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:848
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
Definition: Expr.cpp:406
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:9550
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:8961
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6511
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1872
Represents a C++ member access expression for which lookup produced a set of overloaded functions...
Definition: ExprCXX.h:3538
bool isNull() const
Definition: Diagnostic.h:86
void setKind(tok::TokenKind K)
Definition: Token.h:91
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:5116
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
Definition: SemaExpr.cpp:16821
LookupResultKind getResultKind() const
Definition: Lookup.h:310
Expr * getSubExpr()
Definition: Expr.h:3050
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:739
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
Definition: SemaExpr.cpp:7016
bool isObjCQualifiedClassType() const
Definition: Type.h:6416
enum clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:439
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:14486
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:6226
bool isAssignmentOp() const
Definition: Expr.h:3413
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6644
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:56
IdentifierTable & Idents
Definition: ASTContext.h:566
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:100
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:110
bool isInvalidType() const
Definition: DeclSpec.h:2443
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type, bool NRVO)
Values of this type can be null.
bool isUnarySelector() const
void setSubExpr(Expr *E)
As with any mutator of the AST, be very careful when modifying an existing AST to preserve its invari...
Definition: Expr.h:895
CanQualType LongFractTy
Definition: ASTContext.h:1032
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:63
DeclClass * getAsSingle() const
Definition: Lookup.h:496
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2444
StringRef getOpcodeStr() const
Definition: Expr.h:3343
SourceLocation getOpLoc() const
Definition: ExprObjC.h:564
static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:6559
bool isGLValue() const
Definition: Expr.h:252
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:986
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr *> Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4051
Describes an C or C++ initializer list.
Definition: Expr.h:4185
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter, check that it is non-null, and that if it is formed by array-to-pointer decay, the underlying array is sufficiently large.
Definition: SemaExpr.cpp:5118
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:10967
bool isArrow() const
Definition: ExprObjC.h:551
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
Definition: SemaExpr.cpp:13675
bool isThisCapture() const
Definition: ScopeInfo.h:561
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:3618
BinaryOperatorKind
Expr * getInitExpr() const
Definition: ScopeInfo.h:613
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:934
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:814
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:54
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10134
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2657
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:558
unsigned getLength() const
Definition: Expr.h:1678
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:521
Represents the results of name lookup.
Definition: Lookup.h:47
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:6833
PtrTy get() const
Definition: Ownership.h:174
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:661
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
Definition: SemaExpr.cpp:8546
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:437
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:2731
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2210
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
Definition: SemaExpr.cpp:6495
static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:14887
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:13518
QualType getOriginalType() const
Definition: Decl.cpp:2544
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1208
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:573
A convenient class for passing around template argument information.
Definition: TemplateBase.h:555
static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:8872
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
const FormatToken & Tok
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:1244
bool hasAddressSpace() const
Definition: Type.h:351
LabelDecl * getDecl() const
Definition: Stmt.h:1610
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:6797
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing, variable initialization, and function return values.
Definition: SemaExpr.cpp:7785
This is a while, do, for, which can have continue statements embedded into it.
Definition: Scope.h:56
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS)
Check for comparisons of floating point operands using != and ==.
SourceLocation getTemplateKeywordLoc() const
Gets the location of the template keyword, if present.
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2067
Whether values of this type can be null is (explicitly) unspecified.
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:119
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of &#39;this&#39; is actually available in the current context, if it is a potentially ev...
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:5311
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:2901
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:15749
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes...
Definition: SemaExpr.cpp:2039
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:721
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2434
Represents a declaration of a type.
Definition: Decl.h:2874
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3287
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6142
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:753
CanQualType PseudoObjectTy
Definition: ASTContext.h:1047
LangAS getAddressSpace() const
Definition: Type.h:352
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
Definition: SemaExpr.cpp:6738
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion, integral conversion, floating point conversion, floating-integral conversion, pointer conversion, pointer-to-member conversion, or boolean conversion.
Definition: Overload.h:241
ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef< AvailabilitySpec > AvailSpecs, SourceLocation AtLoc, SourceLocation RParen)
Definition: SemaExpr.cpp:16840
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
bool isArrow() const
Definition: Expr.h:2874
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:211
QualType getObjCClassRedefinitionType() const
Retrieve the type that Class has been defined to, which may be different from the built-in Class if C...
Definition: ASTContext.h:1649
CanQualType LongDoubleTy
Definition: ASTContext.h:1028
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2595
Values of this type can never be null.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope...
Definition: SemaExpr.cpp:15490
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:71
Expr * getSizeExpr() const
Definition: Type.h:2991
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence...
Definition: SemaInit.cpp:7284
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6072
TypedefDecl * getBOOLDecl() const
Retrieve declaration of &#39;BOOL&#39; typedef.
Definition: ASTContext.h:1880
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:3636
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:728
StringKind
StringLiteral is followed by several trailing objects.
Definition: Expr.h:1588
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr *> Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
Definition: SemaExpr.cpp:5597
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1158
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1660
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:5562
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
Definition: SemaExpr.cpp:14470
bool isInt() const
Definition: APValue.h:234
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token...
Definition: Lexer.h:349
bool isRelationalOp() const
Definition: Expr.h:3372
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:3916
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2998
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc)
CheckIndirectionOperand - Type check unary indirection (prefix &#39;*&#39;).
Definition: SemaExpr.cpp:11975
Helper class for OffsetOfExpr.
Definition: Expr.h:2013
The current expression occurs within a discarded statement.
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2064
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1217
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1236
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:3844
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1649
const LangOptions & getLangOpts() const
Definition: Sema.h:1231
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:792
bool isInstance() const
Definition: DeclCXX.h:2069
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:167
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:649
bool isScalarType() const
Definition: Type.h:6629
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3276
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:8207
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:503
An ordinary object is located at an address in memory.
Definition: Specifiers.h:126
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for &#39;&&&#39; in the right hand of a &#39;||&#39; expr.
Definition: SemaExpr.cpp:12594
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5...
Definition: Sema.h:7549
Represents an ObjC class declaration.
Definition: DeclObjC.h:1172
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition: Sema.h:986
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:1930
QualType getReturnType() const
Definition: DeclObjC.h:323
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:415
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:5978
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:5337
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:9546
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:2797
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:325
QualType getBOOLType() const
type of &#39;BOOL&#39; type.
Definition: ASTContext.h:1890
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:3339
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:143
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that&#39;s being passed to an __unknown_anytype parameter.
Definition: SemaExpr.cpp:16636
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3).
Definition: SemaExpr.cpp:15710
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2127
CanQualType UnsignedCharTy
Definition: ASTContext.h:1026
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1073
void setStmt(LabelStmt *T)
Definition: Decl.h:494
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified=false, bool hasWrittenPrototype=true, bool isConstexprSpecified=false)
Definition: Decl.h:1875
const LangOptions & LangOpts
Definition: Sema.h:322
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:870
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:477
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e.g., it is an unsigned integer type or a vector.
Definition: Type.cpp:1914
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
void ActOnStmtExprError()
Definition: SemaExpr.cpp:13210
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:543
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:314
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:976
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, Expr *LHS, Expr *RHS)
Definition: Expr.cpp:1960
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:629
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1235
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1772
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas...
Definition: ScopeInfo.h:904
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:1167
bool isHalfType() const
Definition: Type.h:6550
NodeId Parent
Definition: ASTDiff.cpp:192
OverloadFixItKind Kind
The type of fix applied.
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3213
OpenMP 4.0 [2.4, Array Sections].
Definition: ExprOpenMP.h:45
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK)
Definition: SemaExpr.cpp:3085
bool hasAttr() const
Definition: DeclBase.h:531
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3582
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:278
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:12668
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2455
void setNamingClass(CXXRecordDecl *Record)
Sets the &#39;naming class&#39; for this lookup.
Definition: Lookup.h:397
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
static bool ExprLooksBoolean(Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:7364
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:805
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1241
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1613
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
Definition: SemaExpr.cpp:847
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3687
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:119
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:7417
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:589
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:15784
bool isUsableInConstantExpressions(ASTContext &C) const
Determine whether this variable&#39;s value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2214
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:482
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:12176
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc...
Definition: SemaExpr.cpp:12255
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3300
Expr * IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY
IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the value (including ptr->int ...
Definition: Expr.cpp:2726
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:481
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if &#39;E&#39;, which is an expression that is about to be modified, refers to a shadowing declaration...
Definition: SemaDecl.cpp:7147
Retains information about a captured region.
Definition: ScopeInfo.h:737
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1334
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
Definition: SemaExpr.cpp:12611
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:157
static void emitEmptyLookupTypoDiagnostic(const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, DeclarationName Typo, SourceLocation TypoLoc, ArrayRef< Expr *> Args, unsigned DiagnosticID, unsigned DiagnosticSuggestID)
Definition: SemaExpr.cpp:1795
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1844
static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, ExprResult &RHS)
Handle when one or both operands are void type.
Definition: SemaExpr.cpp:6578
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:569
Specifies that the expression should never be value-dependent.
Definition: Expr.h:711
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:9224
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:9536
void setSubExpr(Expr *E)
Definition: Expr.h:1927
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:2222
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:6538
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to...
Definition: Expr.cpp:1888
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, std::unique_ptr< CorrectionCandidateCallback > CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr *> Args=None, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:1832
bool isObjCSelType(QualType T) const
Definition: ASTContext.h:2543
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6147
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
Definition: SemaExpr.cpp:9163
SourceLocation getLocation() const
Definition: Expr.h:1122
SourceRange getRange() const
Definition: DeclSpec.h:68
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
QualType getUsageType(QualType objectType) const
Retrieve the type of this instance variable when viewed as a member of a specific object type...
Definition: DeclObjC.cpp:1814
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4091
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param)
Definition: ExprCXX.h:1096
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:208
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:264
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1160
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr *> Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
Definition: SemaExpr.cpp:1517
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:8971
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
std::string getAsString(const LangOptions &LO) const
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10826
unsigned Offset
Definition: Format.cpp:1631
unsigned getValue() const
Definition: Expr.h:1426
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3101
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:5822
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:155
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:136
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition...
Definition: SemaExpr.cpp:16028
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:190
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12703
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true)
Create a binary operation that may resolve to an overloaded operator.
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:983
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:711
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1768
CXXMethodDecl * CallOperator
The lambda&#39;s compiler-generated operator().
Definition: ScopeInfo.h:791
QualType getElementType() const
Definition: Type.h:2490
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr *> Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1283
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
Definition: Decl.cpp:4394
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function)...
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
Pepresents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:3858
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:637
This represents one expression.
Definition: Expr.h:106
SourceLocation End
Represents a character-granular source range.
static bool isEvaluatableContext(Sema &SemaRef)
Are we within a context in which some evaluation could be performed (be it constant evaluation or run...
Definition: SemaExpr.cpp:14572
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:107
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for &#39;&&&#39; in the left hand of a &#39;||&#39; expr.
Definition: SemaExpr.cpp:12572
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2689
void setCallee(Expr *F)
Definition: Expr.h:2516
std::string Label
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:14872
int Id
Definition: ASTDiff.cpp:191
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1460
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1036
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:4481
unsigned getIntWidth() const
getIntWidth/Align - Return the size of &#39;signed int&#39; and &#39;unsigned int&#39; for this target, in bits.
Definition: TargetInfo.h:383
static bool EvaluatesAsTrue(Sema &S, Expr *E)
Returns true if the given expression can be evaluated as a constant &#39;true&#39;.
Definition: SemaExpr.cpp:12557
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1384
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:2695
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition: ExprCXX.cpp:1435
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:300
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool isObjCBuiltinType() const
Definition: Type.h:6440
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6811
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:13967
static bool captureInLambda(LambdaScopeInfo *LSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const Sema::TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S)
Capture the given variable in the lambda.
Definition: SemaExpr.cpp:15174
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5177
static Expr * maybeRebuildARCConsumingStmt(Stmt *Statement)
Given the last statement in a statement-expression, check whether the result is a producing expressio...
Definition: SemaExpr.cpp:13188
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:87
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2706
CanQualType OMPArraySectionTy
Definition: ASTContext.h:1055
Expr * getCallee()
Definition: Expr.h:2514
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
std::string getAsString() const
Retrieve the human-readable string for this name.
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:547
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
Defines the clang::Preprocessor interface.
bool isNullPtrType() const
Definition: Type.h:6569
bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context)
Definition: SemaInternal.h:44
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold=true)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:14233
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
#define bool
Definition: stdbool.h:31
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:2908
ObjCLifetime getObjCLifetime() const
Definition: Type.h:326
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isObjCClassType() const
Definition: Type.h:6428
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12640
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
DeclContext * getDeclContext()
Definition: DeclBase.h:427
SourceLocation getLParenLoc() const
Definition: Expr.h:4964
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1664
Overload resolution succeeded.
Definition: Overload.h:54
bool isObjCIdType() const
True if this is equivalent to the &#39;id&#39; type, i.e.
Definition: Type.h:5856
bool isAnyComplexType() const
Definition: Type.h:6377
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
Definition: SemaExpr.cpp:7800
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode. ...
Definition: Expr.cpp:1217
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
Definition: SemaExpr.cpp:12717
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:338
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1350
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:13986
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation...
Definition: DeclCXX.cpp:526
CanQualType ShortTy
Definition: ASTContext.h:1025
static ValueDecl * getCompareDecl(Expr *E)
Definition: SemaExpr.cpp:9937
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:5226
static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, ValueDecl *var, DeclContext *DC)
Definition: SemaExpr.cpp:14799
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don&#39;t permit to be...
Definition: Sema.h:9555
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:16704
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:1967
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2532
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1239
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:848
Represents a C++ template name within the type system.
Definition: TemplateName.h:179
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4219
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7598
Defines the clang::TypeLoc interface and its subclasses.
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:117
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1016
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:14551
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn&#39;t...
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:715
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:2695
QualType getType() const
Definition: Expr.h:128
bool isFunctionOrMethod() const
Definition: DeclBase.h:1800
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:969
Capture & getCapture(VarDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:692
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:621
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition: Sema.h:10754
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:422
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:297
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:207
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1752
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
void setAddressSpace(LangAS space)
Definition: Type.h:372
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, IdentKind IK, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:497
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr *> Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
Definition: SemaExpr.cpp:4880
ScalarTypeKind
Definition: Type.h:2061
VarDecl * isOpenMPCapturedDecl(ValueDecl *D)
Check if the specified variable is used in one of the private clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP constructs.
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:904
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:65
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:1008
ConditionKind
Definition: Sema.h:9921
bool isInvalid() const
Definition: Ownership.h:170
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:12077
SourceLocation getEnd() const
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1896
bool isInstanceMethod() const
Definition: DeclObjC.h:422
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1380
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of &#39;F&#39;...
Definition: Expr.h:2879
Represents a GCC generic vector type.
Definition: Type.h:3168
ArraySizeModifier getSizeModifier() const
Definition: Type.h:2849
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13474
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:2512
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1078
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:15565
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:6524
ValueDecl * getDecl()
Definition: Expr.h:1114
bool isUsable() const
Definition: Ownership.h:171
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2768
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1396
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:152
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
QualType getDestroyedType() const
Retrieve the type being destroyed.
Definition: ExprCXX.cpp:222
const Expr * getSubExpr() const
Definition: Expr.h:1860
const Expr * getSubExpr() const
Definition: ExprCXX.h:1240
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:752
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
Definition: SemaExpr.cpp:5836
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:703
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:414
void setBlockMangling(unsigned Number, Decl *Ctx)
Definition: Decl.h:4025
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:281
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level)
Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) for FD based on DSA for the...
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:170
static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args)
Check an argument list for placeholders that we won&#39;t try to handle later.
Definition: SemaExpr.cpp:5211
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2282
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:129
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2026
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12224
SourceRange getSourceRange() const
Definition: ExprCXX.h:141
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1...
Definition: Expr.h:1517
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:301
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:166
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:5100
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:412
A narrowing conversion, because a non-constant-expression variable might have got narrowed...
Definition: Overload.h:215
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing...
Definition: SemaExpr.cpp:5162
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool isUnresolvableResult() const
Definition: Lookup.h:306
static CharSourceRange getCharRange(SourceRange R)
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType)
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3537
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:84
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6131
bool isVoidPointerType() const
Definition: Type.cpp:469
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:3613
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types? That is, given that one of them is a vector...
Definition: SemaExpr.cpp:6215
bool isComparisonOp() const
Definition: Expr.h:3378
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:11728
RecordDecl * getDecl() const
Definition: Type.h:4380
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:129
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse)
Definition: SemaExpr.cpp:15714
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:3368
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:719
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1565
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:1897
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:6764
Wrapper for source info for arrays.
Definition: TypeLoc.h:1460
Expr * IgnoreConversionOperator() LLVM_READONLY
IgnoreConversionOperator - Ignore conversion operator.
Definition: Expr.cpp:2715
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:626
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
CanQualType OverloadTy
Definition: ASTContext.h:1045
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:9025
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:945
QualType getBuiltinMSVaListType() const
Retrieve the type of the __builtin_ms_va_list type.
Definition: ASTContext.h:1918
Integral conversions (C++ [conv.integral])
Definition: Overload.h:108
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:924
QualType getObjCIdRedefinitionType() const
Retrieve the type that id has been defined to, which may be different from the built-in id if id has ...
Definition: ASTContext.h:1636
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor...
CanQualType BuiltinFnTy
Definition: ASTContext.h:1046
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:169
Kind
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr...
Definition: ExprCXX.h:2635
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:487
QualType getCanonicalType() const
Definition: Type.h:6111
bool CheckCaseExpression(Expr *E)
Definition: SemaExpr.cpp:16811
not a target-specific vector type
Definition: Type.h:3172
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
LookupInObjCMethod - The parser has read a name in, and Sema has detected that we&#39;re currently inside...
Definition: SemaExpr.cpp:2413
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5299
param_type_range param_types() const
Definition: Type.h:4030
A stack object to be created when performing template instantiation.
Definition: Sema.h:7394
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4078
VarDecl * getVariable() const
Definition: ScopeInfo.h:593
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3899
ASTContext & getASTContext() const
Definition: Sema.h:1238
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:4945
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Definition: Expr.cpp:3438
Encodes a location in the source.
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_convertvector(...)
Definition: SemaExpr.cpp:5583
llvm::SmallPtrSet< Expr *, 2 > MaybeODRUseExprs
Store a list of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) ...
Definition: Sema.h:546
QualType getReturnType() const
Definition: Type.h:3613
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
llvm::APFloat::opStatus GetFloatValue(llvm::APFloat &Result)
GetFloatValue - Convert this numeric literal to a floating value, using the specified APFloat fltSema...
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4396
SourceLocation getOperatorLoc() const
Definition: Expr.h:3319
llvm::SmallPtrSet< Expr *, 2 > SavedMaybeODRUseExprs
Definition: Sema.h:982
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:5963
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6188
This represents &#39;#pragma omp declare reduction ...&#39; directive.
Definition: DeclOpenMP.h:103
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:477
Expression is not a Null pointer constant.
Definition: Expr.h:688
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:951
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:797
Expr * getSubExpr() const
Definition: Expr.h:1926
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5738
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
Definition: SemaExpr.cpp:7293
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2095
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:788
QualType getObjCSelRedefinitionType() const
Retrieve the type that &#39;SEL&#39; has been defined to, which may be different from the built-in &#39;SEL&#39; if &#39;...
Definition: ASTContext.h:1662
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11539
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10224
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:13932
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:498
CastKind getCastKind() const
Definition: Expr.h:3044
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1914
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2154
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:11671
void setLastStmt(Stmt *S)
Definition: Stmt.h:1283
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
Definition: SemaExpr.cpp:3684
DeclarationName getName() const
getName - Returns the embedded declaration name.
static ConstantExpr * Create(const ASTContext &Context, Expr *E)
Definition: Expr.h:909
static bool IgnoreCommaOperand(const Expr *E)
Definition: SemaExpr.cpp:11469
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of &#39;signed long long&#39; and &#39;unsigned long long&#39; for this targ...
Definition: TargetInfo.h:393
QualType getElementType() const
Definition: Type.h:3203
void setReferenced(bool R=true)
Definition: DeclBase.h:577
Represents the declaration of a label.
Definition: Decl.h:469
IncompatiblePointer - The assignment is between two pointers types that are not compatible, but we accept them as an extension.
Definition: Sema.h:9540
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3153
bool isOverloadedResult() const
Determines if the results are overloaded.
Definition: Lookup.h:302
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:124
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr *> exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1447
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1759
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2041
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type...
Definition: SemaExpr.cpp:8489
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:186
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2413
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:14412
static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl)
Definition: Expr.cpp:537
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size...
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:183
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:553
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
CanQualType FloatTy
Definition: ASTContext.h:1028
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2285
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:5922
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
Definition: Expr.h:719
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
CanQualType VoidTy
Definition: ASTContext.h:1016
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
Expr * getExpr(unsigned Init)
Definition: Expr.h:4947
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
Describes the kind of initialization being performed, along with location information for tokens rela...
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const
Return true if the provided declaration VD should be captured by reference.
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
const TemplateArgumentListInfo & getTemplateArgsInfo() const
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1741
Qualifiers withoutObjCLifetime() const
Definition: Type.h:319
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:8155
CanQualType Float16Ty
Definition: ASTContext.h:1041
bool isKnownToHaveBooleanValue() const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:134
bool isAnyPointerType() const
Definition: Type.h:6300
bool isObjCObjectPointerType() const
Definition: Type.h:6393
is AltiVec &#39;vector bool ...&#39;
Definition: Type.h:3181
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:642
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion...
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:980
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3115
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1152
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:2536
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:249
isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, does not have an incomplet...
is AltiVec vector
Definition: Type.h:3175
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1664
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR)
Definition: SemaExpr.cpp:14227
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics...
Definition: SemaExpr.cpp:212
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, Expr *Length, SourceLocation RBLoc)
Definition: SemaExpr.cpp:4352
bool isAddressSpaceOverlapping(const PointerType &other) const
Returns true if address spaces of pointers overlap.
Definition: Type.h:2560
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:909
TypeClass getTypeClass() const
Definition: Type.h:1811
Used for C&#39;s _Alignof and C++&#39;s alignof.
Definition: TypeTraits.h:101
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3076
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:397
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:149
bool typesAreBlockPointerCompatible(QualType, QualType)
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:1823
EnumDecl * getDecl() const
Definition: Type.h:4403
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1303
bool isVectorType() const
Definition: Type.h:6381
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:141
Assigning into this object requires a lifetime extension.
Definition: Type.h:175
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3801
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13...
Definition: Overload.h:837
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:162
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1473
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:14559
bool isCanonical() const
Definition: Type.h:6116
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:574
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2293
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:595
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
Definition: SemaExpr.cpp:9517
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2035
static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag)
Defines the fixed point number interface.
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13219
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3922
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:215
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat &#39;semantics&#39; for the specified scalar floating point type.
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:9434
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1142
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptions FPFeatures)
Definition: SemaExpr.cpp:12191
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
Definition: SemaExpr.cpp:16612
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3504
A POD class for pairing a NamedDecl* with an access specifier.
bool isRealType() const
Definition: Type.cpp:1943
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:6518
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we&#39;re in ARC.
Definition: SemaExpr.cpp:5948
Represents a C11 generic selection.
Definition: Expr.h:5010
ReuseLambdaContextDecl_t
Definition: Sema.h:4035
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template...
Definition: Decl.cpp:2495
Represents an element in a path from a derived class to a base class.
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:3757
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:15762
CanQualType CharTy
Definition: ASTContext.h:1018
Represents a template argument.
Definition: TemplateBase.h:51
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9125
bool isPipeType() const
Definition: Type.h:6477
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
Definition: SemaExpr.cpp:1773
static bool isInvalid(LocType Loc, bool *Invalid)
NonConstCaptureKind
Is the given expression (which must be &#39;const&#39;) a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:10930
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union...
Definition: SemaExpr.cpp:8136
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2535
Dataflow Directional Tag Classes.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i...
bool isValid() const
Return true if this is a valid SourceLocation object.
ExtInfo getExtInfo() const
Definition: Type.h:3624
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:12470
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:9428
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false)
UnaryOperatorKind
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1262
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input)
Definition: SemaExpr.cpp:13169
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:571
const DeclContext * getCurObjCLexicalContext() const
Definition: Sema.h:10744
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2170
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
ArrayRef< Capture > captures() const
Definition: Decl.h:3985
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
Definition: SemaExpr.cpp:9133
bool isSentinelNullExpr(const Expr *E)
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:10694
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type &#39;Type&#39;, insert an implicit cast.
Definition: Sema.cpp:474
typedef char* __builtin_va_list;
Definition: TargetInfo.h:183
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, QualType RHSType)
Diagnose attempts to convert between __float128 and long double if there is no support for such conve...
Definition: SemaExpr.cpp:1104
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:131
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
Definition: SemaExpr.cpp:10734
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3558
SourceRange getSourceRange(const SourceRange &Range)
Returns the SourceRange of a SourceRange.
Definition: FixIt.h:34
bool isShiftOp() const
Definition: Expr.h:3366
bool isRecord() const
Definition: DeclBase.h:1827
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
SourceLocation RAngleLoc
The location of the &#39;>&#39; after the template argument list.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:9802
bool isCXX98PODType(const ASTContext &Context) const
Return true if this is a POD type according to the rules of the C++98 standard, regardless of the cur...
Definition: Type.cpp:2109
static bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, ASTContext &Context)
Definition: SemaExpr.cpp:15509
Represents a field injected from an anonymous union/struct into the parent scope. ...
Definition: Decl.h:2825
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
Definition: SemaExpr.cpp:8442
void setSubExpr(Expr *E)
Definition: Expr.h:3052
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_astype(...)
Definition: SemaExpr.cpp:5562
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:15942
BinaryOperator::Opcode getOpcode(const SymExpr *SE)
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:8836
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1027
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
Definition: SemaCast.cpp:1773
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:9952
const Expr * getInit() const
Definition: Decl.h:1220
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:562
A runtime availability query.
Definition: ExprObjC.h:1636
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:87
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:160
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:2790
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of &#39;this&#39;; zero if &#39;this&#39; is not captured...
Definition: ScopeInfo.h:639
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:3707
The name of a declaration.
StmtClass getStmtClass() const
Definition: Stmt.h:1029
VectorKind getVectorKind() const
Definition: Type.h:3213
const char * getCastKindName() const
Definition: Expr.h:3048
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:506
Expr * getDefaultArg()
Definition: Decl.cpp:2573
void setInstantiationIsPending(bool IC)
State that the instantiation of this function is pending.
Definition: Decl.h:2109
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:971
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:346
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2166
const Expr * getExpr() const
Definition: ExprCXX.h:1106
bool isBooleanType() const
Definition: Type.h:6657
Kind getKind() const
Definition: DeclBase.h:421
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type...
Definition: SemaExpr.cpp:16256
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like &#39;int()&#39;.
Expression is a Null pointer constant built from a zero integer expression that is not a simple...
Definition: Expr.h:695
U cast(CodeGen::Address addr)
Definition: Address.h:109
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:6270
A set of unresolved declarations.
virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR)=0
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:9573
Expression is a C++11 nullptr.
Definition: Expr.h:701
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
Definition: SemaExpr.cpp:9894
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:3636
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a &#39;&&&#39; expr that is inside a &#39;||&#39; one.
Definition: SemaExpr.cpp:12544
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:146
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
Expr * get() const
Definition: Sema.h:3673
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1391
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration...
Definition: DeclCXX.h:2144
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3190
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4205
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3136
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:4303
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:15551
unsigned getLength() const
Definition: Token.h:127
IdentifierInfo * getCorrectionAsIdentifierInfo() const
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1081
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr *> Args, SmallVectorImpl< Expr *> &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:4996
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo *> Types, ArrayRef< Expr *> Exprs)
Definition: SemaExpr.cpp:1363
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2693
void addConst()
Definition: Type.h:261
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression&#39;s result is syntactically ignored, perform any conversions that are required.
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions)
Represents a pointer to an Objective C object.
Definition: Type.h:5794
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:151
Pointer to a block type.
Definition: Type.h:2639
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1049
The standard open() call: int open(const char *path, int oflag, ...);.
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures...
Definition: Sema.h:3636
static bool EvaluatesAsFalse(Sema &S, Expr *E)
Returns true if the given expression can be evaluated as a constant &#39;false&#39;.
Definition: SemaExpr.cpp:12565
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2221
unsigned getIntWidth(QualType T) const
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:8898
Not an overloaded operator.
Definition: OperatorKinds.h:23
RecordDecl * TheRecordDecl
The captured record type.
Definition: ScopeInfo.h:743
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
Definition: SemaExpr.cpp:4131
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:544
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4370
Complex values, per C99 6.2.5p11.
Definition: Type.h:2477
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:450
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2615
CanQualType UnknownAnyTy
Definition: ASTContext.h:1045
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3575
bool body_empty() const
Definition: Stmt.h:1268
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface...
Definition: Type.h:5850
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2312
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it&#39;s possible to devirtualize a call to this method, return the called function.
Definition: DeclCXX.cpp:1952
ObjCLiteralKind
Definition: Sema.h:2738
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator"...
Definition: SemaExpr.cpp:6970
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6578
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2330
CanQualType UnsignedLongTy
Definition: ASTContext.h:1026
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1771
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
T * getAttr() const
Definition: DeclBase.h:527
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
Definition: SemaExpr.cpp:6303
SourceLocation getLocation() const
Definition: ExprObjC.h:556
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:12626
const llvm::APInt & getSize() const
Definition: Type.h:2890
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2074
CanQualType DependentTy
Definition: ASTContext.h:1045
bool isImageType() const
Definition: Type.h:6470
FunctionDecl * getCurFunctionDecl()
getCurFunctionDecl - If inside of a function body, this returns a pointer to the function decl for th...
Definition: Sema.cpp:1203
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
Definition: SemaExpr.cpp:9078
bool isAtomicType() const
Definition: Type.h:6406
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:10091
bool isFunctionType() const
Definition: Type.h:6292
bool isAddressSpaceSupersetOf(Qualifiers other) const
Returns true if this address space is a superset of the other one.
Definition: Type.h:469
bool isObjCQualifiedIdType() const
Definition: Type.h:6410
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
Definition: SemaExpr.cpp:1509
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:716
ExtVectorType - Extended vector type.
Definition: Type.h:3287
Opcode getOpcode() const
Definition: Expr.h:1921
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2673
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1730
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2269
CanQualType BoundMemberTy
Definition: ASTContext.h:1045
LValueClassification
Definition: Expr.h:254
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1041
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:7700
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: Sema.h:8823
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
Definition: SemaExpr.cpp:12867
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn&#39;t need to call Usual...
Definition: SemaExpr.cpp:11575
qual_range quals() const
Definition: Type.h:5917
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:32
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D)
Diagnoses obvious problems with the use of the given declaration as an expression.
Definition: SemaExpr.cpp:2766
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1507
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:251
const Expr * getBase() const
Definition: ExprObjC.h:547
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3696
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2806
bool isConstantArrayType() const
Definition: Type.h:6349
llvm::DenseMap< VarDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition: ScopeInfo.h:635
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:13455
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:129
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, ExprResult *Vector)
Attempt to convert and splat Scalar into a vector whose types matches Vector following GCC conversion...
Definition: SemaExpr.cpp:8590
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:412
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2070
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
This is a scope that can contain a declaration.
Definition: Scope.h:60
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:9691
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
Definition: SemaExpr.cpp:8379
bool isObjCObjectType() const
Definition: Type.h:6397
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2031
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, std::unique_ptr< CorrectionCandidateCallback > CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2080
CanQualType Char8Ty
Definition: ASTContext.h:1022
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2356
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function&#39;s address can be taken or not, optionally emitting a diagnostic if...
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:830
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:1360
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2253
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:238
CXXRecordDecl * getNamingClass() const
Returns the &#39;naming class&#39; for this lookup, i.e.
Definition: Lookup.h:392
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:4442
Reading or writing from this object requires a barrier call.
Definition: Type.h:172
bool isQueueT() const
Definition: Type.h:6462
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4042
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:235
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4425
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
QualType getParamType(unsigned i) const
Definition: Type.h:3890
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:894
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:698
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups, surround it with a ExprWithCleanups node.
ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:1700
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E)
Definition: SemaExpr.cpp:15587
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:90
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1009
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr *> ArgExprs)
Definition: SemaExpr.cpp:1337
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2682
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:964
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10791
Describes the sequence of initializations required to initialize a given object or reference with a s...
ActionResult< Expr * > ExprResult
Definition: Ownership.h:267
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6152
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3274
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
Definition: SemaExpr.cpp:1065
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2585
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:9743
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g., it is an signed integer type or a vector.
Definition: Type.cpp:1874
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
Compatible - the types are compatible according to the standard.
Definition: Sema.h:9524
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
bool isVoidType() const
Definition: Type.h:6544
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2994
CUDAFunctionTarget
Definition: Sema.h:10156
void markUsed(bool IsODRUse)
Definition: ScopeInfo.h:591
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1358
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition: Expr.cpp:4257
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1864
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:3977
static bool hasAnyTypeDependentArguments(ArrayRef< Expr *> Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:2886
bool isNested() const
Definition: ScopeInfo.h:585
static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
Definition: SemaExpr.cpp:7318
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3655
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:1733
SourceLocation getRParenLoc() const
Definition: Expr.h:4965
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6099
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal...
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1945
CanQualType Char16Ty
Definition: ASTContext.h:1023
bool isMultiplicativeOp() const
Definition: Expr.h:3362
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type...
Definition: SemaExpr.cpp:6242
TryCaptureKind
Definition: Sema.h:4071
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:15482
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10253
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:8911
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:568
Location information for a TemplateArgument.
Definition: TemplateBase.h:393
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:336
bool isSamplerT() const
Definition: Type.h:6450
bool isCXXThisCaptured() const
Determine whether the C++ &#39;this&#39; is captured.
Definition: ScopeInfo.h:674
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:189
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates)...
Definition: Expr.h:214
bool isRValue() const
Definition: Expr.h:250
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:129
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2391
void addVLATypeCapture(SourceLocation Loc, QualType CaptureType)
Definition: ScopeInfo.h:660
SourceManager & getSourceManager() const
Definition: Sema.h:1236
iterator end() const
Definition: Lookup.h:325
A template-id, e.g., f<int>.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:276
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11490
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all...
Definition: Sema.h:917
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3216
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1566
Defines the clang::TargetInfo interface.
bool isComplexIntegerType() const
Definition: Type.cpp:487
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2396
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:10054
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion)
type checking for vector binary operators.
Definition: SemaExpr.cpp:8665
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
static CUDAKernelCallExpr * Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config, ArrayRef< Expr *> Args, QualType Ty, ExprValueKind VK, SourceLocation RP, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:1639
void UpdateMarkingForLValueToRValue(Expr *E)
Definition: SemaExpr.cpp:15526
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3637
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
unsigned getCVRQualifiers() const
Definition: Type.h:274
ExprResult ExprError()
Definition: Ownership.h:283
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber...
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member&#39;s actual type.
Definition: SemaExpr.cpp:2560
uint64_t Width
Definition: ASTContext.h:144
CanQualType IntTy
Definition: ASTContext.h:1025
static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S)
Definition: SemaExpr.cpp:14955
unsigned getNumElements() const
Definition: Type.h:3204
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:82
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2079
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:5379
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1600
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1041
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:819
The class facilities generation and storage of conversion FixIts.
Expr * getRHS() const
Definition: Expr.h:3329
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13805
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2136
bool isPointerType() const
Definition: Type.h:6296
bool isBitwiseOp() const
Definition: Expr.h:3369
bool isIncrementDecrementOp() const
Definition: Expr.h:1970
static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses=true)
Are we within a context in which references to resolved functions or to variables result in odr-use...
Definition: SemaExpr.cpp:14597
void setSubStmt(Stmt *SS)
Definition: Stmt.h:1617
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e.g.
Definition: SemaExpr.cpp:1553
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:1935
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, Expr *Cpy)
Definition: ScopeInfo.h:652
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:196
DeclaratorContext getContext() const
Definition: DeclSpec.h:1879
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:572
void setLocation(SourceLocation L)
Definition: Token.h:132
QualType getType() const
Definition: Decl.h:648
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:114
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:328
bool isFloatingType() const
Definition: Type.cpp:1921
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:324
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< CorrectionCandidateCallback > CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2983
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1428
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:9578
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:16113
This represents a decl that may have a name.
Definition: Decl.h:249
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1023
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:160
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:6412
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1141
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:457
CanQualType BoolTy
Definition: ASTContext.h:1017
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2971
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression&#39;s return type is complete.
Definition: SemaExpr.cpp:15985
No keyword precedes the qualified type name.
Definition: Type.h:5071
bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1550
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12751
APSInt & getInt()
Definition: APValue.h:252
AccessControl getAccessControl() const
Definition: DeclObjC.h:1984
iterator begin() const
Definition: Lookup.h:324
CanQualType DoubleTy
Definition: ASTContext.h:1028
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:595
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2050
Describes an entity that is being initialized.
bool isFunctionPointerType() const
Definition: Type.h:6320
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:3762
unsigned NumArgs
NumArgs - The number of template arguments.
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:513
ComparisonCategoryType
An enumeration representing the different comparison categories types.
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef< Expr *> Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:339
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:306
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, ArrayRef< Expr *> Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:85
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:6922
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3055
void setType(QualType newType)
Definition: Decl.h:649
void removeAddressSpace()
Definition: Type.h:377
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3377
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:92
bool hasInit() const
Definition: Decl.cpp:2164
SourceLocation getBegin() const
AssignmentAction
Definition: Sema.h:2525
SourceLocation ColonLoc
Location of &#39;:&#39;.
Definition: OpenMPClause.h:108
const LangOptions & getLangOpts() const
Definition: ASTContext.h:707
void WillReplaceSpecifier(bool ForceReplacement)
bool isBlockCapture() const
Definition: ScopeInfo.h:577
An implicit &#39;self&#39; parameter.
No in-class initializer.
Definition: Specifiers.h:230
The lookup resulted in an error.
Definition: Sema.h:3127
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
Definition: SemaExpr.cpp:12135
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2872
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:7308
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types...
Definition: Sema.h:9561
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
Declaration of a template function.
Definition: DeclTemplate.h:969
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:559
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3466
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:14620
The current expression occurs within a braced-init-list within an unevaluated operand.
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant()...
Definition: Expr.h:686
One specifier in an expression.
Definition: Availability.h:31
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1943
Attr - This represents one attribute.
Definition: Attr.h:44
SourceLocation getLocation() const
Definition: DeclBase.h:418
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type...
Definition: Type.h:1861
CastType
Definition: SemaCast.cpp:46
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, bool IsCompAssign=false)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6...
Definition: SemaExpr.cpp:1257
void startToken()
Reset all flags to cleared.
Definition: Token.h:169
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:13175
bool isExternallyVisible() const
Definition: Decl.h:380
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:11740
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:98
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:367
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:8984
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type...
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth, signed/unsigned.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:13663
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, const NamedDecl *D, SourceLocation Loc)
Check whether we&#39;re in an extern inline function and referring to a variable or function with interna...
Definition: SemaExpr.cpp:145
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1261
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form, which contains extra information on the evaluated value of the initializer.
Definition: Decl.cpp:2244
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2560
OriginalExprKind
Definition: SemaExpr.cpp:11108
CanQualType UnsignedIntTy
Definition: ASTContext.h:1026
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:3602
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1058
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:11956
Structure used to store a statement, the constant value to which it was evaluated (if any)...
Definition: Decl.h:784
A RAII object to temporarily push a declaration context.
Definition: Sema.h:728
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:4794
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5810
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3.1.1).
Definition: Overload.h:230
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4148