clang  6.0.0svn
Expr.cpp
Go to the documentation of this file.
1 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
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 the Expr class and subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/Mangle.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/Basic/Builtins.h"
26 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Lexer.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <algorithm>
35 #include <cstring>
36 using namespace clang;
37 
39  const Expr *E = this;
40  while (true) {
41  E = E->ignoreParenBaseCasts();
42 
43  // Follow the RHS of a comma operator.
44  if (auto *BO = dyn_cast<BinaryOperator>(E)) {
45  if (BO->getOpcode() == BO_Comma) {
46  E = BO->getRHS();
47  continue;
48  }
49  }
50 
51  // Step into initializer for materialized temporaries.
52  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
53  E = MTE->GetTemporaryExpr();
54  continue;
55  }
56 
57  break;
58  }
59 
60  return E;
61 }
62 
64  const Expr *E = getBestDynamicClassTypeExpr();
65  QualType DerivedType = E->getType();
66  if (const PointerType *PTy = DerivedType->getAs<PointerType>())
67  DerivedType = PTy->getPointeeType();
68 
69  if (DerivedType->isDependentType())
70  return nullptr;
71 
72  const RecordType *Ty = DerivedType->castAs<RecordType>();
73  Decl *D = Ty->getDecl();
74  return cast<CXXRecordDecl>(D);
75 }
76 
79  SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
80  const Expr *E = this;
81  while (true) {
82  E = E->IgnoreParens();
83 
84  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
85  if ((CE->getCastKind() == CK_DerivedToBase ||
86  CE->getCastKind() == CK_UncheckedDerivedToBase) &&
87  E->getType()->isRecordType()) {
88  E = CE->getSubExpr();
89  CXXRecordDecl *Derived
90  = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
91  Adjustments.push_back(SubobjectAdjustment(CE, Derived));
92  continue;
93  }
94 
95  if (CE->getCastKind() == CK_NoOp) {
96  E = CE->getSubExpr();
97  continue;
98  }
99  } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
100  if (!ME->isArrow()) {
101  assert(ME->getBase()->getType()->isRecordType());
102  if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
103  if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
104  E = ME->getBase();
105  Adjustments.push_back(SubobjectAdjustment(Field));
106  continue;
107  }
108  }
109  }
110  } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
111  if (BO->isPtrMemOp()) {
112  assert(BO->getRHS()->isRValue());
113  E = BO->getLHS();
114  const MemberPointerType *MPT =
115  BO->getRHS()->getType()->getAs<MemberPointerType>();
116  Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
117  continue;
118  } else if (BO->getOpcode() == BO_Comma) {
119  CommaLHSs.push_back(BO->getLHS());
120  E = BO->getRHS();
121  continue;
122  }
123  }
124 
125  // Nothing changed.
126  break;
127  }
128  return E;
129 }
130 
131 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
132 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
133 /// but also int expressions which are produced by things like comparisons in
134 /// C.
136  const Expr *E = IgnoreParens();
137 
138  // If this value has _Bool type, it is obvious 0/1.
139  if (E->getType()->isBooleanType()) return true;
140  // If this is a non-scalar-integer type, we don't care enough to try.
141  if (!E->getType()->isIntegralOrEnumerationType()) return false;
142 
143  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
144  switch (UO->getOpcode()) {
145  case UO_Plus:
146  return UO->getSubExpr()->isKnownToHaveBooleanValue();
147  case UO_LNot:
148  return true;
149  default:
150  return false;
151  }
152  }
153 
154  // Only look through implicit casts. If the user writes
155  // '(int) (a && b)' treat it as an arbitrary int.
156  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
157  return CE->getSubExpr()->isKnownToHaveBooleanValue();
158 
159  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
160  switch (BO->getOpcode()) {
161  default: return false;
162  case BO_LT: // Relational operators.
163  case BO_GT:
164  case BO_LE:
165  case BO_GE:
166  case BO_EQ: // Equality operators.
167  case BO_NE:
168  case BO_LAnd: // AND operator.
169  case BO_LOr: // Logical OR operator.
170  return true;
171 
172  case BO_And: // Bitwise AND operator.
173  case BO_Xor: // Bitwise XOR operator.
174  case BO_Or: // Bitwise OR operator.
175  // Handle things like (x==2)|(y==12).
176  return BO->getLHS()->isKnownToHaveBooleanValue() &&
177  BO->getRHS()->isKnownToHaveBooleanValue();
178 
179  case BO_Comma:
180  case BO_Assign:
181  return BO->getRHS()->isKnownToHaveBooleanValue();
182  }
183  }
184 
185  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
186  return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
187  CO->getFalseExpr()->isKnownToHaveBooleanValue();
188 
189  return false;
190 }
191 
192 // Amusing macro metaprogramming hack: check whether a class provides
193 // a more specific implementation of getExprLoc().
194 //
195 // See also Stmt.cpp:{getLocStart(),getLocEnd()}.
196 namespace {
197  /// This implementation is used when a class provides a custom
198  /// implementation of getExprLoc.
199  template <class E, class T>
200  SourceLocation getExprLocImpl(const Expr *expr,
201  SourceLocation (T::*v)() const) {
202  return static_cast<const E*>(expr)->getExprLoc();
203  }
204 
205  /// This implementation is used when a class doesn't provide
206  /// a custom implementation of getExprLoc. Overload resolution
207  /// should pick it over the implementation above because it's
208  /// more specialized according to function template partial ordering.
209  template <class E>
210  SourceLocation getExprLocImpl(const Expr *expr,
211  SourceLocation (Expr::*v)() const) {
212  return static_cast<const E*>(expr)->getLocStart();
213  }
214 }
215 
217  switch (getStmtClass()) {
218  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
219 #define ABSTRACT_STMT(type)
220 #define STMT(type, base) \
221  case Stmt::type##Class: break;
222 #define EXPR(type, base) \
223  case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
224 #include "clang/AST/StmtNodes.inc"
225  }
226  llvm_unreachable("unknown expression kind");
227 }
228 
229 //===----------------------------------------------------------------------===//
230 // Primary Expressions.
231 //===----------------------------------------------------------------------===//
232 
233 /// \brief Compute the type-, value-, and instantiation-dependence of a
234 /// declaration reference
235 /// based on the declaration being referenced.
236 static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
237  QualType T, bool &TypeDependent,
238  bool &ValueDependent,
239  bool &InstantiationDependent) {
240  TypeDependent = false;
241  ValueDependent = false;
242  InstantiationDependent = false;
243 
244  // (TD) C++ [temp.dep.expr]p3:
245  // An id-expression is type-dependent if it contains:
246  //
247  // and
248  //
249  // (VD) C++ [temp.dep.constexpr]p2:
250  // An identifier is value-dependent if it is:
251 
252  // (TD) - an identifier that was declared with dependent type
253  // (VD) - a name declared with a dependent type,
254  if (T->isDependentType()) {
255  TypeDependent = true;
256  ValueDependent = true;
257  InstantiationDependent = true;
258  return;
259  } else if (T->isInstantiationDependentType()) {
260  InstantiationDependent = true;
261  }
262 
263  // (TD) - a conversion-function-id that specifies a dependent type
264  if (D->getDeclName().getNameKind()
267  if (T->isDependentType()) {
268  TypeDependent = true;
269  ValueDependent = true;
270  InstantiationDependent = true;
271  return;
272  }
273 
275  InstantiationDependent = true;
276  }
277 
278  // (VD) - the name of a non-type template parameter,
279  if (isa<NonTypeTemplateParmDecl>(D)) {
280  ValueDependent = true;
281  InstantiationDependent = true;
282  return;
283  }
284 
285  // (VD) - a constant with integral or enumeration type and is
286  // initialized with an expression that is value-dependent.
287  // (VD) - a constant with literal type and is initialized with an
288  // expression that is value-dependent [C++11].
289  // (VD) - FIXME: Missing from the standard:
290  // - an entity with reference type and is initialized with an
291  // expression that is value-dependent [C++11]
292  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
293  if ((Ctx.getLangOpts().CPlusPlus11 ?
294  Var->getType()->isLiteralType(Ctx) :
295  Var->getType()->isIntegralOrEnumerationType()) &&
296  (Var->getType().isConstQualified() ||
297  Var->getType()->isReferenceType())) {
298  if (const Expr *Init = Var->getAnyInitializer())
299  if (Init->isValueDependent()) {
300  ValueDependent = true;
301  InstantiationDependent = true;
302  }
303  }
304 
305  // (VD) - FIXME: Missing from the standard:
306  // - a member function or a static data member of the current
307  // instantiation
308  if (Var->isStaticDataMember() &&
309  Var->getDeclContext()->isDependentContext()) {
310  ValueDependent = true;
311  InstantiationDependent = true;
312  TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
313  if (TInfo->getType()->isIncompleteArrayType())
314  TypeDependent = true;
315  }
316 
317  return;
318  }
319 
320  // (VD) - FIXME: Missing from the standard:
321  // - a member function or a static data member of the current
322  // instantiation
323  if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
324  ValueDependent = true;
325  InstantiationDependent = true;
326  }
327 }
328 
329 void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
330  bool TypeDependent = false;
331  bool ValueDependent = false;
332  bool InstantiationDependent = false;
333  computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
334  ValueDependent, InstantiationDependent);
335 
336  ExprBits.TypeDependent |= TypeDependent;
337  ExprBits.ValueDependent |= ValueDependent;
338  ExprBits.InstantiationDependent |= InstantiationDependent;
339 
340  // Is the declaration a parameter pack?
341  if (getDecl()->isParameterPack())
342  ExprBits.ContainsUnexpandedParameterPack = true;
343 }
344 
345 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
346  NestedNameSpecifierLoc QualifierLoc,
347  SourceLocation TemplateKWLoc,
348  ValueDecl *D, bool RefersToEnclosingVariableOrCapture,
349  const DeclarationNameInfo &NameInfo,
350  NamedDecl *FoundD,
351  const TemplateArgumentListInfo *TemplateArgs,
353  : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
354  D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
355  DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
356  if (QualifierLoc) {
357  new (getTrailingObjects<NestedNameSpecifierLoc>())
358  NestedNameSpecifierLoc(QualifierLoc);
359  auto *NNS = QualifierLoc.getNestedNameSpecifier();
360  if (NNS->isInstantiationDependent())
361  ExprBits.InstantiationDependent = true;
362  if (NNS->containsUnexpandedParameterPack())
363  ExprBits.ContainsUnexpandedParameterPack = true;
364  }
365  DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
366  if (FoundD)
367  *getTrailingObjects<NamedDecl *>() = FoundD;
368  DeclRefExprBits.HasTemplateKWAndArgsInfo
369  = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
370  DeclRefExprBits.RefersToEnclosingVariableOrCapture =
371  RefersToEnclosingVariableOrCapture;
372  if (TemplateArgs) {
373  bool Dependent = false;
374  bool InstantiationDependent = false;
375  bool ContainsUnexpandedParameterPack = false;
376  getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
377  TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
378  Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
379  assert(!Dependent && "built a DeclRefExpr with dependent template args");
380  ExprBits.InstantiationDependent |= InstantiationDependent;
381  ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
382  } else if (TemplateKWLoc.isValid()) {
383  getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
384  TemplateKWLoc);
385  }
386  DeclRefExprBits.HadMultipleCandidates = 0;
387 
388  computeDependence(Ctx);
389 }
390 
392  NestedNameSpecifierLoc QualifierLoc,
393  SourceLocation TemplateKWLoc,
394  ValueDecl *D,
395  bool RefersToEnclosingVariableOrCapture,
396  SourceLocation NameLoc,
397  QualType T,
398  ExprValueKind VK,
399  NamedDecl *FoundD,
400  const TemplateArgumentListInfo *TemplateArgs) {
401  return Create(Context, QualifierLoc, TemplateKWLoc, D,
402  RefersToEnclosingVariableOrCapture,
403  DeclarationNameInfo(D->getDeclName(), NameLoc),
404  T, VK, FoundD, TemplateArgs);
405 }
406 
408  NestedNameSpecifierLoc QualifierLoc,
409  SourceLocation TemplateKWLoc,
410  ValueDecl *D,
411  bool RefersToEnclosingVariableOrCapture,
412  const DeclarationNameInfo &NameInfo,
413  QualType T,
414  ExprValueKind VK,
415  NamedDecl *FoundD,
416  const TemplateArgumentListInfo *TemplateArgs) {
417  // Filter out cases where the found Decl is the same as the value refenenced.
418  if (D == FoundD)
419  FoundD = nullptr;
420 
421  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
422  std::size_t Size =
423  totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
425  QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
426  HasTemplateKWAndArgsInfo ? 1 : 0,
427  TemplateArgs ? TemplateArgs->size() : 0);
428 
429  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
430  return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
431  RefersToEnclosingVariableOrCapture,
432  NameInfo, FoundD, TemplateArgs, T, VK);
433 }
434 
436  bool HasQualifier,
437  bool HasFoundDecl,
438  bool HasTemplateKWAndArgsInfo,
439  unsigned NumTemplateArgs) {
440  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
441  std::size_t Size =
442  totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
444  HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
445  NumTemplateArgs);
446  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
447  return new (Mem) DeclRefExpr(EmptyShell());
448 }
449 
451  if (hasQualifier())
452  return getQualifierLoc().getBeginLoc();
453  return getNameInfo().getLocStart();
454 }
456  if (hasExplicitTemplateArgs())
457  return getRAngleLoc();
458  return getNameInfo().getLocEnd();
459 }
460 
462  StringLiteral *SL)
463  : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
464  FNTy->isDependentType(), FNTy->isDependentType(),
465  FNTy->isInstantiationDependentType(),
466  /*ContainsUnexpandedParameterPack=*/false),
467  Loc(L), Type(IT), FnName(SL) {}
468 
470  return cast_or_null<StringLiteral>(FnName);
471 }
472 
474  switch (IT) {
475  case Func:
476  return "__func__";
477  case Function:
478  return "__FUNCTION__";
479  case FuncDName:
480  return "__FUNCDNAME__";
481  case LFunction:
482  return "L__FUNCTION__";
483  case PrettyFunction:
484  return "__PRETTY_FUNCTION__";
485  case FuncSig:
486  return "__FUNCSIG__";
488  break;
489  }
490  llvm_unreachable("Unknown ident type for PredefinedExpr");
491 }
492 
493 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
494 // expr" policy instead.
495 std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
496  ASTContext &Context = CurrentDecl->getASTContext();
497 
498  if (IT == PredefinedExpr::FuncDName) {
499  if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
500  std::unique_ptr<MangleContext> MC;
501  MC.reset(Context.createMangleContext());
502 
503  if (MC->shouldMangleDeclName(ND)) {
504  SmallString<256> Buffer;
505  llvm::raw_svector_ostream Out(Buffer);
506  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
507  MC->mangleCXXCtor(CD, Ctor_Base, Out);
508  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
509  MC->mangleCXXDtor(DD, Dtor_Base, Out);
510  else
511  MC->mangleName(ND, Out);
512 
513  if (!Buffer.empty() && Buffer.front() == '\01')
514  return Buffer.substr(1);
515  return Buffer.str();
516  } else
517  return ND->getIdentifier()->getName();
518  }
519  return "";
520  }
521  if (isa<BlockDecl>(CurrentDecl)) {
522  // For blocks we only emit something if it is enclosed in a function
523  // For top-level block we'd like to include the name of variable, but we
524  // don't have it at this point.
525  auto DC = CurrentDecl->getDeclContext();
526  if (DC->isFileContext())
527  return "";
528 
529  SmallString<256> Buffer;
530  llvm::raw_svector_ostream Out(Buffer);
531  if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
532  // For nested blocks, propagate up to the parent.
533  Out << ComputeName(IT, DCBlock);
534  else if (auto *DCDecl = dyn_cast<Decl>(DC))
535  Out << ComputeName(IT, DCDecl) << "_block_invoke";
536  return Out.str();
537  }
538  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
539  if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual && IT != FuncSig)
540  return FD->getNameAsString();
541 
542  SmallString<256> Name;
543  llvm::raw_svector_ostream Out(Name);
544 
545  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
546  if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
547  Out << "virtual ";
548  if (MD->isStatic())
549  Out << "static ";
550  }
551 
552  PrintingPolicy Policy(Context.getLangOpts());
553  std::string Proto;
554  llvm::raw_string_ostream POut(Proto);
555 
556  const FunctionDecl *Decl = FD;
557  if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
558  Decl = Pattern;
559  const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
560  const FunctionProtoType *FT = nullptr;
561  if (FD->hasWrittenPrototype())
562  FT = dyn_cast<FunctionProtoType>(AFT);
563 
564  if (IT == FuncSig) {
565  switch (AFT->getCallConv()) {
566  case CC_C: POut << "__cdecl "; break;
567  case CC_X86StdCall: POut << "__stdcall "; break;
568  case CC_X86FastCall: POut << "__fastcall "; break;
569  case CC_X86ThisCall: POut << "__thiscall "; break;
570  case CC_X86VectorCall: POut << "__vectorcall "; break;
571  case CC_X86RegCall: POut << "__regcall "; break;
572  // Only bother printing the conventions that MSVC knows about.
573  default: break;
574  }
575  }
576 
577  FD->printQualifiedName(POut, Policy);
578 
579  POut << "(";
580  if (FT) {
581  for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
582  if (i) POut << ", ";
583  POut << Decl->getParamDecl(i)->getType().stream(Policy);
584  }
585 
586  if (FT->isVariadic()) {
587  if (FD->getNumParams()) POut << ", ";
588  POut << "...";
589  } else if ((IT == FuncSig || !Context.getLangOpts().CPlusPlus) &&
590  !Decl->getNumParams()) {
591  POut << "void";
592  }
593  }
594  POut << ")";
595 
596  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
597  assert(FT && "We must have a written prototype in this case.");
598  if (FT->isConst())
599  POut << " const";
600  if (FT->isVolatile())
601  POut << " volatile";
602  RefQualifierKind Ref = MD->getRefQualifier();
603  if (Ref == RQ_LValue)
604  POut << " &";
605  else if (Ref == RQ_RValue)
606  POut << " &&";
607  }
608 
610  SpecsTy Specs;
611  const DeclContext *Ctx = FD->getDeclContext();
612  while (Ctx && isa<NamedDecl>(Ctx)) {
614  = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
615  if (Spec && !Spec->isExplicitSpecialization())
616  Specs.push_back(Spec);
617  Ctx = Ctx->getParent();
618  }
619 
620  std::string TemplateParams;
621  llvm::raw_string_ostream TOut(TemplateParams);
622  for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
623  I != E; ++I) {
624  const TemplateParameterList *Params
625  = (*I)->getSpecializedTemplate()->getTemplateParameters();
626  const TemplateArgumentList &Args = (*I)->getTemplateArgs();
627  assert(Params->size() == Args.size());
628  for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
629  StringRef Param = Params->getParam(i)->getName();
630  if (Param.empty()) continue;
631  TOut << Param << " = ";
632  Args.get(i).print(Policy, TOut);
633  TOut << ", ";
634  }
635  }
636 
638  = FD->getTemplateSpecializationInfo();
639  if (FSI && !FSI->isExplicitSpecialization()) {
640  const TemplateParameterList* Params
642  const TemplateArgumentList* Args = FSI->TemplateArguments;
643  assert(Params->size() == Args->size());
644  for (unsigned i = 0, e = Params->size(); i != e; ++i) {
645  StringRef Param = Params->getParam(i)->getName();
646  if (Param.empty()) continue;
647  TOut << Param << " = ";
648  Args->get(i).print(Policy, TOut);
649  TOut << ", ";
650  }
651  }
652 
653  TOut.flush();
654  if (!TemplateParams.empty()) {
655  // remove the trailing comma and space
656  TemplateParams.resize(TemplateParams.size() - 2);
657  POut << " [" << TemplateParams << "]";
658  }
659 
660  POut.flush();
661 
662  // Print "auto" for all deduced return types. This includes C++1y return
663  // type deduction and lambdas. For trailing return types resolve the
664  // decltype expression. Otherwise print the real type when this is
665  // not a constructor or destructor.
666  if (isa<CXXMethodDecl>(FD) &&
667  cast<CXXMethodDecl>(FD)->getParent()->isLambda())
668  Proto = "auto " + Proto;
669  else if (FT && FT->getReturnType()->getAs<DecltypeType>())
670  FT->getReturnType()
671  ->getAs<DecltypeType>()
673  .getAsStringInternal(Proto, Policy);
674  else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
675  AFT->getReturnType().getAsStringInternal(Proto, Policy);
676 
677  Out << Proto;
678 
679  return Name.str().str();
680  }
681  if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
682  for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
683  // Skip to its enclosing function or method, but not its enclosing
684  // CapturedDecl.
685  if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
686  const Decl *D = Decl::castFromDeclContext(DC);
687  return ComputeName(IT, D);
688  }
689  llvm_unreachable("CapturedDecl not inside a function or method");
690  }
691  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
692  SmallString<256> Name;
693  llvm::raw_svector_ostream Out(Name);
694  Out << (MD->isInstanceMethod() ? '-' : '+');
695  Out << '[';
696 
697  // For incorrect code, there might not be an ObjCInterfaceDecl. Do
698  // a null check to avoid a crash.
699  if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
700  Out << *ID;
701 
702  if (const ObjCCategoryImplDecl *CID =
703  dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
704  Out << '(' << *CID << ')';
705 
706  Out << ' ';
707  MD->getSelector().print(Out);
708  Out << ']';
709 
710  return Name.str().str();
711  }
712  if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
713  // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
714  return "top level";
715  }
716  return "";
717 }
718 
720  const llvm::APInt &Val) {
721  if (hasAllocation())
722  C.Deallocate(pVal);
723 
724  BitWidth = Val.getBitWidth();
725  unsigned NumWords = Val.getNumWords();
726  const uint64_t* Words = Val.getRawData();
727  if (NumWords > 1) {
728  pVal = new (C) uint64_t[NumWords];
729  std::copy(Words, Words + NumWords, pVal);
730  } else if (NumWords == 1)
731  VAL = Words[0];
732  else
733  VAL = 0;
734 }
735 
736 IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
738  : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
739  false, false),
740  Loc(l) {
741  assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
742  assert(V.getBitWidth() == C.getIntWidth(type) &&
743  "Integer type is not the correct size for constant.");
744  setValue(C, V);
745 }
746 
748 IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
750  return new (C) IntegerLiteral(C, V, type, l);
751 }
752 
755  return new (C) IntegerLiteral(Empty);
756 }
757 
758 FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
759  bool isexact, QualType Type, SourceLocation L)
760  : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
761  false, false), Loc(L) {
762  setSemantics(V.getSemantics());
763  FloatingLiteralBits.IsExact = isexact;
764  setValue(C, V);
765 }
766 
767 FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
768  : Expr(FloatingLiteralClass, Empty) {
769  setRawSemantics(IEEEhalf);
770  FloatingLiteralBits.IsExact = false;
771 }
772 
774 FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
775  bool isexact, QualType Type, SourceLocation L) {
776  return new (C) FloatingLiteral(C, V, isexact, Type, L);
777 }
778 
781  return new (C) FloatingLiteral(C, Empty);
782 }
783 
784 const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
785  switch(FloatingLiteralBits.Semantics) {
786  case IEEEhalf:
787  return llvm::APFloat::IEEEhalf();
788  case IEEEsingle:
789  return llvm::APFloat::IEEEsingle();
790  case IEEEdouble:
791  return llvm::APFloat::IEEEdouble();
792  case x87DoubleExtended:
793  return llvm::APFloat::x87DoubleExtended();
794  case IEEEquad:
795  return llvm::APFloat::IEEEquad();
796  case PPCDoubleDouble:
797  return llvm::APFloat::PPCDoubleDouble();
798  }
799  llvm_unreachable("Unrecognised floating semantics");
800 }
801 
802 void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
803  if (&Sem == &llvm::APFloat::IEEEhalf())
804  FloatingLiteralBits.Semantics = IEEEhalf;
805  else if (&Sem == &llvm::APFloat::IEEEsingle())
806  FloatingLiteralBits.Semantics = IEEEsingle;
807  else if (&Sem == &llvm::APFloat::IEEEdouble())
808  FloatingLiteralBits.Semantics = IEEEdouble;
809  else if (&Sem == &llvm::APFloat::x87DoubleExtended())
811  else if (&Sem == &llvm::APFloat::IEEEquad())
812  FloatingLiteralBits.Semantics = IEEEquad;
813  else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
815  else
816  llvm_unreachable("Unknown floating semantics");
817 }
818 
819 /// getValueAsApproximateDouble - This returns the value as an inaccurate
820 /// double. Note that this may cause loss of precision, but is useful for
821 /// debugging dumps, etc.
823  llvm::APFloat V = getValue();
824  bool ignored;
825  V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
826  &ignored);
827  return V.convertToDouble();
828 }
829 
830 int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
831  int CharByteWidth = 0;
832  switch(k) {
833  case Ascii:
834  case UTF8:
835  CharByteWidth = target.getCharWidth();
836  break;
837  case Wide:
838  CharByteWidth = target.getWCharWidth();
839  break;
840  case UTF16:
841  CharByteWidth = target.getChar16Width();
842  break;
843  case UTF32:
844  CharByteWidth = target.getChar32Width();
845  break;
846  }
847  assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
848  CharByteWidth /= 8;
849  assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
850  && "character byte widths supported are 1, 2, and 4 only");
851  return CharByteWidth;
852 }
853 
855  StringKind Kind, bool Pascal, QualType Ty,
856  const SourceLocation *Loc,
857  unsigned NumStrs) {
858  assert(C.getAsConstantArrayType(Ty) &&
859  "StringLiteral must be of constant array type!");
860 
861  // Allocate enough space for the StringLiteral plus an array of locations for
862  // any concatenated string tokens.
863  void *Mem =
864  C.Allocate(sizeof(StringLiteral) + sizeof(SourceLocation) * (NumStrs - 1),
865  alignof(StringLiteral));
866  StringLiteral *SL = new (Mem) StringLiteral(Ty);
867 
868  // OPTIMIZE: could allocate this appended to the StringLiteral.
869  SL->setString(C,Str,Kind,Pascal);
870 
871  SL->TokLocs[0] = Loc[0];
872  SL->NumConcatenated = NumStrs;
873 
874  if (NumStrs != 1)
875  memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
876  return SL;
877 }
878 
880  unsigned NumStrs) {
881  void *Mem =
882  C.Allocate(sizeof(StringLiteral) + sizeof(SourceLocation) * (NumStrs - 1),
883  alignof(StringLiteral));
884  StringLiteral *SL = new (Mem) StringLiteral(QualType());
885  SL->CharByteWidth = 0;
886  SL->Length = 0;
887  SL->NumConcatenated = NumStrs;
888  return SL;
889 }
890 
891 void StringLiteral::outputString(raw_ostream &OS) const {
892  switch (getKind()) {
893  case Ascii: break; // no prefix.
894  case Wide: OS << 'L'; break;
895  case UTF8: OS << "u8"; break;
896  case UTF16: OS << 'u'; break;
897  case UTF32: OS << 'U'; break;
898  }
899  OS << '"';
900  static const char Hex[] = "0123456789ABCDEF";
901 
902  unsigned LastSlashX = getLength();
903  for (unsigned I = 0, N = getLength(); I != N; ++I) {
904  switch (uint32_t Char = getCodeUnit(I)) {
905  default:
906  // FIXME: Convert UTF-8 back to codepoints before rendering.
907 
908  // Convert UTF-16 surrogate pairs back to codepoints before rendering.
909  // Leave invalid surrogates alone; we'll use \x for those.
910  if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
911  Char <= 0xdbff) {
912  uint32_t Trail = getCodeUnit(I + 1);
913  if (Trail >= 0xdc00 && Trail <= 0xdfff) {
914  Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
915  ++I;
916  }
917  }
918 
919  if (Char > 0xff) {
920  // If this is a wide string, output characters over 0xff using \x
921  // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
922  // codepoint: use \x escapes for invalid codepoints.
923  if (getKind() == Wide ||
924  (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
925  // FIXME: Is this the best way to print wchar_t?
926  OS << "\\x";
927  int Shift = 28;
928  while ((Char >> Shift) == 0)
929  Shift -= 4;
930  for (/**/; Shift >= 0; Shift -= 4)
931  OS << Hex[(Char >> Shift) & 15];
932  LastSlashX = I;
933  break;
934  }
935 
936  if (Char > 0xffff)
937  OS << "\\U00"
938  << Hex[(Char >> 20) & 15]
939  << Hex[(Char >> 16) & 15];
940  else
941  OS << "\\u";
942  OS << Hex[(Char >> 12) & 15]
943  << Hex[(Char >> 8) & 15]
944  << Hex[(Char >> 4) & 15]
945  << Hex[(Char >> 0) & 15];
946  break;
947  }
948 
949  // If we used \x... for the previous character, and this character is a
950  // hexadecimal digit, prevent it being slurped as part of the \x.
951  if (LastSlashX + 1 == I) {
952  switch (Char) {
953  case '0': case '1': case '2': case '3': case '4':
954  case '5': case '6': case '7': case '8': case '9':
955  case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
956  case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
957  OS << "\"\"";
958  }
959  }
960 
961  assert(Char <= 0xff &&
962  "Characters above 0xff should already have been handled.");
963 
964  if (isPrintable(Char))
965  OS << (char)Char;
966  else // Output anything hard as an octal escape.
967  OS << '\\'
968  << (char)('0' + ((Char >> 6) & 7))
969  << (char)('0' + ((Char >> 3) & 7))
970  << (char)('0' + ((Char >> 0) & 7));
971  break;
972  // Handle some common non-printable cases to make dumps prettier.
973  case '\\': OS << "\\\\"; break;
974  case '"': OS << "\\\""; break;
975  case '\a': OS << "\\a"; break;
976  case '\b': OS << "\\b"; break;
977  case '\f': OS << "\\f"; break;
978  case '\n': OS << "\\n"; break;
979  case '\r': OS << "\\r"; break;
980  case '\t': OS << "\\t"; break;
981  case '\v': OS << "\\v"; break;
982  }
983  }
984  OS << '"';
985 }
986 
987 void StringLiteral::setString(const ASTContext &C, StringRef Str,
988  StringKind Kind, bool IsPascal) {
989  //FIXME: we assume that the string data comes from a target that uses the same
990  // code unit size and endianness for the type of string.
991  this->Kind = Kind;
992  this->IsPascal = IsPascal;
993 
994  CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
995  assert((Str.size()%CharByteWidth == 0)
996  && "size of data must be multiple of CharByteWidth");
997  Length = Str.size()/CharByteWidth;
998 
999  switch(CharByteWidth) {
1000  case 1: {
1001  char *AStrData = new (C) char[Length];
1002  std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
1003  StrData.asChar = AStrData;
1004  break;
1005  }
1006  case 2: {
1007  uint16_t *AStrData = new (C) uint16_t[Length];
1008  std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
1009  StrData.asUInt16 = AStrData;
1010  break;
1011  }
1012  case 4: {
1013  uint32_t *AStrData = new (C) uint32_t[Length];
1014  std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
1015  StrData.asUInt32 = AStrData;
1016  break;
1017  }
1018  default:
1019  llvm_unreachable("unsupported CharByteWidth");
1020  }
1021 }
1022 
1023 /// getLocationOfByte - Return a source location that points to the specified
1024 /// byte of this string literal.
1025 ///
1026 /// Strings are amazingly complex. They can be formed from multiple tokens and
1027 /// can have escape sequences in them in addition to the usual trigraph and
1028 /// escaped newline business. This routine handles this complexity.
1029 ///
1030 /// The *StartToken sets the first token to be searched in this function and
1031 /// the *StartTokenByteOffset is the byte offset of the first token. Before
1032 /// returning, it updates the *StartToken to the TokNo of the token being found
1033 /// and sets *StartTokenByteOffset to the byte offset of the token in the
1034 /// string.
1035 /// Using these two parameters can reduce the time complexity from O(n^2) to
1036 /// O(n) if one wants to get the location of byte for all the tokens in a
1037 /// string.
1038 ///
1041  const LangOptions &Features,
1042  const TargetInfo &Target, unsigned *StartToken,
1043  unsigned *StartTokenByteOffset) const {
1044  assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) &&
1045  "Only narrow string literals are currently supported");
1046 
1047  // Loop over all of the tokens in this string until we find the one that
1048  // contains the byte we're looking for.
1049  unsigned TokNo = 0;
1050  unsigned StringOffset = 0;
1051  if (StartToken)
1052  TokNo = *StartToken;
1053  if (StartTokenByteOffset) {
1054  StringOffset = *StartTokenByteOffset;
1055  ByteNo -= StringOffset;
1056  }
1057  while (1) {
1058  assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1059  SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1060 
1061  // Get the spelling of the string so that we can get the data that makes up
1062  // the string literal, not the identifier for the macro it is potentially
1063  // expanded through.
1064  SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1065 
1066  // Re-lex the token to get its length and original spelling.
1067  std::pair<FileID, unsigned> LocInfo =
1068  SM.getDecomposedLoc(StrTokSpellingLoc);
1069  bool Invalid = false;
1070  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1071  if (Invalid) {
1072  if (StartTokenByteOffset != nullptr)
1073  *StartTokenByteOffset = StringOffset;
1074  if (StartToken != nullptr)
1075  *StartToken = TokNo;
1076  return StrTokSpellingLoc;
1077  }
1078 
1079  const char *StrData = Buffer.data()+LocInfo.second;
1080 
1081  // Create a lexer starting at the beginning of this token.
1082  Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1083  Buffer.begin(), StrData, Buffer.end());
1084  Token TheTok;
1085  TheLexer.LexFromRawLexer(TheTok);
1086 
1087  // Use the StringLiteralParser to compute the length of the string in bytes.
1088  StringLiteralParser SLP(TheTok, SM, Features, Target);
1089  unsigned TokNumBytes = SLP.GetStringLength();
1090 
1091  // If the byte is in this token, return the location of the byte.
1092  if (ByteNo < TokNumBytes ||
1093  (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1094  unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1095 
1096  // Now that we know the offset of the token in the spelling, use the
1097  // preprocessor to get the offset in the original source.
1098  if (StartTokenByteOffset != nullptr)
1099  *StartTokenByteOffset = StringOffset;
1100  if (StartToken != nullptr)
1101  *StartToken = TokNo;
1102  return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1103  }
1104 
1105  // Move to the next string token.
1106  StringOffset += TokNumBytes;
1107  ++TokNo;
1108  ByteNo -= TokNumBytes;
1109  }
1110 }
1111 
1112 
1113 
1114 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1115 /// corresponds to, e.g. "sizeof" or "[pre]++".
1117  switch (Op) {
1118 #define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1119 #include "clang/AST/OperationKinds.def"
1120  }
1121  llvm_unreachable("Unknown unary operator");
1122 }
1123 
1126  switch (OO) {
1127  default: llvm_unreachable("No unary operator for overloaded function");
1128  case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1129  case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1130  case OO_Amp: return UO_AddrOf;
1131  case OO_Star: return UO_Deref;
1132  case OO_Plus: return UO_Plus;
1133  case OO_Minus: return UO_Minus;
1134  case OO_Tilde: return UO_Not;
1135  case OO_Exclaim: return UO_LNot;
1136  case OO_Coawait: return UO_Coawait;
1137  }
1138 }
1139 
1141  switch (Opc) {
1142  case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1143  case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1144  case UO_AddrOf: return OO_Amp;
1145  case UO_Deref: return OO_Star;
1146  case UO_Plus: return OO_Plus;
1147  case UO_Minus: return OO_Minus;
1148  case UO_Not: return OO_Tilde;
1149  case UO_LNot: return OO_Exclaim;
1150  case UO_Coawait: return OO_Coawait;
1151  default: return OO_None;
1152  }
1153 }
1154 
1155 
1156 //===----------------------------------------------------------------------===//
1157 // Postfix Operators.
1158 //===----------------------------------------------------------------------===//
1159 
1161  ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
1162  ExprValueKind VK, SourceLocation rparenloc)
1163  : Expr(SC, t, VK, OK_Ordinary, fn->isTypeDependent(),
1166  NumArgs(args.size()) {
1167 
1168  unsigned NumPreArgs = preargs.size();
1169  SubExprs = new (C) Stmt *[args.size()+PREARGS_START+NumPreArgs];
1170  SubExprs[FN] = fn;
1171  for (unsigned i = 0; i != NumPreArgs; ++i) {
1172  updateDependenciesFromArg(preargs[i]);
1173  SubExprs[i+PREARGS_START] = preargs[i];
1174  }
1175  for (unsigned i = 0; i != args.size(); ++i) {
1176  updateDependenciesFromArg(args[i]);
1177  SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
1178  }
1179 
1180  CallExprBits.NumPreArgs = NumPreArgs;
1181  RParenLoc = rparenloc;
1182 }
1183 
1186  SourceLocation rparenloc)
1187  : CallExpr(C, SC, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {}
1188 
1190  QualType t, ExprValueKind VK, SourceLocation rparenloc)
1191  : CallExpr(C, CallExprClass, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {
1192 }
1193 
1195  : CallExpr(C, SC, /*NumPreArgs=*/0, Empty) {}
1196 
1197 CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
1198  EmptyShell Empty)
1199  : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) {
1200  // FIXME: Why do we allocate this?
1201  SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs]();
1202  CallExprBits.NumPreArgs = NumPreArgs;
1203 }
1204 
1205 void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1206  if (Arg->isTypeDependent())
1207  ExprBits.TypeDependent = true;
1208  if (Arg->isValueDependent())
1209  ExprBits.ValueDependent = true;
1210  if (Arg->isInstantiationDependent())
1211  ExprBits.InstantiationDependent = true;
1213  ExprBits.ContainsUnexpandedParameterPack = true;
1214 }
1215 
1217  return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
1218 }
1219 
1222 }
1223 
1225  Expr *CEE = IgnoreParenImpCasts();
1226 
1227  while (SubstNonTypeTemplateParmExpr *NTTP
1228  = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1229  CEE = NTTP->getReplacement()->IgnoreParenCasts();
1230  }
1231 
1232  // If we're calling a dereference, look at the pointer instead.
1233  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1234  if (BO->isPtrMemOp())
1235  CEE = BO->getRHS()->IgnoreParenCasts();
1236  } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1237  if (UO->getOpcode() == UO_Deref)
1238  CEE = UO->getSubExpr()->IgnoreParenCasts();
1239  }
1240  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
1241  return DRE->getDecl();
1242  if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1243  return ME->getMemberDecl();
1244 
1245  return nullptr;
1246 }
1247 
1248 /// setNumArgs - This changes the number of arguments present in this call.
1249 /// Any orphaned expressions are deleted by this, and any new operands are set
1250 /// to null.
1251 void CallExpr::setNumArgs(const ASTContext& C, unsigned NumArgs) {
1252  // No change, just return.
1253  if (NumArgs == getNumArgs()) return;
1254 
1255  // If shrinking # arguments, just delete the extras and forgot them.
1256  if (NumArgs < getNumArgs()) {
1257  this->NumArgs = NumArgs;
1258  return;
1259  }
1260 
1261  // Otherwise, we are growing the # arguments. New an bigger argument array.
1262  unsigned NumPreArgs = getNumPreArgs();
1263  Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
1264  // Copy over args.
1265  for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
1266  NewSubExprs[i] = SubExprs[i];
1267  // Null out new args.
1268  for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
1269  i != NumArgs+PREARGS_START+NumPreArgs; ++i)
1270  NewSubExprs[i] = nullptr;
1271 
1272  if (SubExprs) C.Deallocate(SubExprs);
1273  SubExprs = NewSubExprs;
1274  this->NumArgs = NumArgs;
1275 }
1276 
1277 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
1278 /// not, return 0.
1279 unsigned CallExpr::getBuiltinCallee() const {
1280  // All simple function calls (e.g. func()) are implicitly cast to pointer to
1281  // function. As a result, we try and obtain the DeclRefExpr from the
1282  // ImplicitCastExpr.
1283  const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1284  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
1285  return 0;
1286 
1287  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1288  if (!DRE)
1289  return 0;
1290 
1291  const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1292  if (!FDecl)
1293  return 0;
1294 
1295  if (!FDecl->getIdentifier())
1296  return 0;
1297 
1298  return FDecl->getBuiltinID();
1299 }
1300 
1302  if (unsigned BI = getBuiltinCallee())
1303  return Ctx.BuiltinInfo.isUnevaluated(BI);
1304  return false;
1305 }
1306 
1308  const Expr *Callee = getCallee();
1309  QualType CalleeType = Callee->getType();
1310  if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1311  CalleeType = FnTypePtr->getPointeeType();
1312  } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1313  CalleeType = BPT->getPointeeType();
1314  } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1315  if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1316  return Ctx.VoidTy;
1317 
1318  // This should never be overloaded and so should never return null.
1319  CalleeType = Expr::findBoundMemberType(Callee);
1320  }
1321 
1322  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1323  return FnType->getReturnType();
1324 }
1325 
1327  if (isa<CXXOperatorCallExpr>(this))
1328  return cast<CXXOperatorCallExpr>(this)->getLocStart();
1329 
1330  SourceLocation begin = getCallee()->getLocStart();
1331  if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1332  begin = getArg(0)->getLocStart();
1333  return begin;
1334 }
1336  if (isa<CXXOperatorCallExpr>(this))
1337  return cast<CXXOperatorCallExpr>(this)->getLocEnd();
1338 
1339  SourceLocation end = getRParenLoc();
1340  if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1341  end = getArg(getNumArgs() - 1)->getLocEnd();
1342  return end;
1343 }
1344 
1346  SourceLocation OperatorLoc,
1347  TypeSourceInfo *tsi,
1348  ArrayRef<OffsetOfNode> comps,
1349  ArrayRef<Expr*> exprs,
1350  SourceLocation RParenLoc) {
1351  void *Mem = C.Allocate(
1352  totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1353 
1354  return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1355  RParenLoc);
1356 }
1357 
1359  unsigned numComps, unsigned numExprs) {
1360  void *Mem =
1361  C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1362  return new (Mem) OffsetOfExpr(numComps, numExprs);
1363 }
1364 
1365 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1366  SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1368  SourceLocation RParenLoc)
1369  : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1370  /*TypeDependent=*/false,
1371  /*ValueDependent=*/tsi->getType()->isDependentType(),
1374  OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1375  NumComps(comps.size()), NumExprs(exprs.size())
1376 {
1377  for (unsigned i = 0; i != comps.size(); ++i) {
1378  setComponent(i, comps[i]);
1379  }
1380 
1381  for (unsigned i = 0; i != exprs.size(); ++i) {
1382  if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
1383  ExprBits.ValueDependent = true;
1384  if (exprs[i]->containsUnexpandedParameterPack())
1385  ExprBits.ContainsUnexpandedParameterPack = true;
1386 
1387  setIndexExpr(i, exprs[i]);
1388  }
1389 }
1390 
1392  assert(getKind() == Field || getKind() == Identifier);
1393  if (getKind() == Field)
1394  return getField()->getIdentifier();
1395 
1396  return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1397 }
1398 
1400  UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1402  : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1403  false, // Never type-dependent (C++ [temp.dep.expr]p3).
1404  // Value-dependent if the argument is type-dependent.
1407  OpLoc(op), RParenLoc(rp) {
1408  UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1409  UnaryExprOrTypeTraitExprBits.IsType = false;
1410  Argument.Ex = E;
1411 
1412  // Check to see if we are in the situation where alignof(decl) should be
1413  // dependent because decl's alignment is dependent.
1414  if (ExprKind == UETT_AlignOf) {
1416  E = E->IgnoreParens();
1417 
1418  const ValueDecl *D = nullptr;
1419  if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1420  D = DRE->getDecl();
1421  else if (const auto *ME = dyn_cast<MemberExpr>(E))
1422  D = ME->getMemberDecl();
1423 
1424  if (D) {
1425  for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1426  if (I->isAlignmentDependent()) {
1427  setValueDependent(true);
1429  break;
1430  }
1431  }
1432  }
1433  }
1434  }
1435 }
1436 
1438  const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1439  NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1440  ValueDecl *memberdecl, DeclAccessPair founddecl,
1441  DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1442  QualType ty, ExprValueKind vk, ExprObjectKind ok) {
1443 
1444  bool hasQualOrFound = (QualifierLoc ||
1445  founddecl.getDecl() != memberdecl ||
1446  founddecl.getAccess() != memberdecl->getAccess());
1447 
1448  bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1449  std::size_t Size =
1451  TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1452  HasTemplateKWAndArgsInfo ? 1 : 0,
1453  targs ? targs->size() : 0);
1454 
1455  void *Mem = C.Allocate(Size, alignof(MemberExpr));
1456  MemberExpr *E = new (Mem)
1457  MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
1458 
1459  if (hasQualOrFound) {
1460  // FIXME: Wrong. We should be looking at the member declaration we found.
1461  if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1462  E->setValueDependent(true);
1463  E->setTypeDependent(true);
1464  E->setInstantiationDependent(true);
1465  }
1466  else if (QualifierLoc &&
1468  E->setInstantiationDependent(true);
1469 
1470  E->HasQualifierOrFoundDecl = true;
1471 
1472  MemberExprNameQualifier *NQ =
1473  E->getTrailingObjects<MemberExprNameQualifier>();
1474  NQ->QualifierLoc = QualifierLoc;
1475  NQ->FoundDecl = founddecl;
1476  }
1477 
1478  E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
1479 
1480  if (targs) {
1481  bool Dependent = false;
1482  bool InstantiationDependent = false;
1483  bool ContainsUnexpandedParameterPack = false;
1484  E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1485  TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1486  Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
1487  if (InstantiationDependent)
1488  E->setInstantiationDependent(true);
1489  } else if (TemplateKWLoc.isValid()) {
1490  E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1491  TemplateKWLoc);
1492  }
1493 
1494  return E;
1495 }
1496 
1498  if (isImplicitAccess()) {
1499  if (hasQualifier())
1500  return getQualifierLoc().getBeginLoc();
1501  return MemberLoc;
1502  }
1503 
1504  // FIXME: We don't want this to happen. Rather, we should be able to
1505  // detect all kinds of implicit accesses more cleanly.
1506  SourceLocation BaseStartLoc = getBase()->getLocStart();
1507  if (BaseStartLoc.isValid())
1508  return BaseStartLoc;
1509  return MemberLoc;
1510 }
1512  SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1513  if (hasExplicitTemplateArgs())
1514  EndLoc = getRAngleLoc();
1515  else if (EndLoc.isInvalid())
1516  EndLoc = getBase()->getLocEnd();
1517  return EndLoc;
1518 }
1519 
1520 bool CastExpr::CastConsistency() const {
1521  switch (getCastKind()) {
1522  case CK_DerivedToBase:
1523  case CK_UncheckedDerivedToBase:
1524  case CK_DerivedToBaseMemberPointer:
1525  case CK_BaseToDerived:
1526  case CK_BaseToDerivedMemberPointer:
1527  assert(!path_empty() && "Cast kind should have a base path!");
1528  break;
1529 
1530  case CK_CPointerToObjCPointerCast:
1531  assert(getType()->isObjCObjectPointerType());
1532  assert(getSubExpr()->getType()->isPointerType());
1533  goto CheckNoBasePath;
1534 
1535  case CK_BlockPointerToObjCPointerCast:
1536  assert(getType()->isObjCObjectPointerType());
1537  assert(getSubExpr()->getType()->isBlockPointerType());
1538  goto CheckNoBasePath;
1539 
1540  case CK_ReinterpretMemberPointer:
1541  assert(getType()->isMemberPointerType());
1542  assert(getSubExpr()->getType()->isMemberPointerType());
1543  goto CheckNoBasePath;
1544 
1545  case CK_BitCast:
1546  // Arbitrary casts to C pointer types count as bitcasts.
1547  // Otherwise, we should only have block and ObjC pointer casts
1548  // here if they stay within the type kind.
1549  if (!getType()->isPointerType()) {
1550  assert(getType()->isObjCObjectPointerType() ==
1551  getSubExpr()->getType()->isObjCObjectPointerType());
1552  assert(getType()->isBlockPointerType() ==
1553  getSubExpr()->getType()->isBlockPointerType());
1554  }
1555  goto CheckNoBasePath;
1556 
1557  case CK_AnyPointerToBlockPointerCast:
1558  assert(getType()->isBlockPointerType());
1559  assert(getSubExpr()->getType()->isAnyPointerType() &&
1560  !getSubExpr()->getType()->isBlockPointerType());
1561  goto CheckNoBasePath;
1562 
1563  case CK_CopyAndAutoreleaseBlockObject:
1564  assert(getType()->isBlockPointerType());
1565  assert(getSubExpr()->getType()->isBlockPointerType());
1566  goto CheckNoBasePath;
1567 
1568  case CK_FunctionToPointerDecay:
1569  assert(getType()->isPointerType());
1570  assert(getSubExpr()->getType()->isFunctionType());
1571  goto CheckNoBasePath;
1572 
1573  case CK_AddressSpaceConversion:
1574  assert(getType()->isPointerType() || getType()->isBlockPointerType());
1575  assert(getSubExpr()->getType()->isPointerType() ||
1576  getSubExpr()->getType()->isBlockPointerType());
1577  assert(getType()->getPointeeType().getAddressSpace() !=
1578  getSubExpr()->getType()->getPointeeType().getAddressSpace());
1579  LLVM_FALLTHROUGH;
1580  // These should not have an inheritance path.
1581  case CK_Dynamic:
1582  case CK_ToUnion:
1583  case CK_ArrayToPointerDecay:
1584  case CK_NullToMemberPointer:
1585  case CK_NullToPointer:
1586  case CK_ConstructorConversion:
1587  case CK_IntegralToPointer:
1588  case CK_PointerToIntegral:
1589  case CK_ToVoid:
1590  case CK_VectorSplat:
1591  case CK_IntegralCast:
1592  case CK_BooleanToSignedIntegral:
1593  case CK_IntegralToFloating:
1594  case CK_FloatingToIntegral:
1595  case CK_FloatingCast:
1596  case CK_ObjCObjectLValueCast:
1597  case CK_FloatingRealToComplex:
1598  case CK_FloatingComplexToReal:
1599  case CK_FloatingComplexCast:
1600  case CK_FloatingComplexToIntegralComplex:
1601  case CK_IntegralRealToComplex:
1602  case CK_IntegralComplexToReal:
1603  case CK_IntegralComplexCast:
1604  case CK_IntegralComplexToFloatingComplex:
1605  case CK_ARCProduceObject:
1606  case CK_ARCConsumeObject:
1607  case CK_ARCReclaimReturnedObject:
1608  case CK_ARCExtendBlockObject:
1609  case CK_ZeroToOCLEvent:
1610  case CK_ZeroToOCLQueue:
1611  case CK_IntToOCLSampler:
1612  assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1613  goto CheckNoBasePath;
1614 
1615  case CK_Dependent:
1616  case CK_LValueToRValue:
1617  case CK_NoOp:
1618  case CK_AtomicToNonAtomic:
1619  case CK_NonAtomicToAtomic:
1620  case CK_PointerToBoolean:
1621  case CK_IntegralToBoolean:
1622  case CK_FloatingToBoolean:
1623  case CK_MemberPointerToBoolean:
1624  case CK_FloatingComplexToBoolean:
1625  case CK_IntegralComplexToBoolean:
1626  case CK_LValueBitCast: // -> bool&
1627  case CK_UserDefinedConversion: // operator bool()
1628  case CK_BuiltinFnToFnPtr:
1629  CheckNoBasePath:
1630  assert(path_empty() && "Cast kind should not have a base path!");
1631  break;
1632  }
1633  return true;
1634 }
1635 
1636 const char *CastExpr::getCastKindName() const {
1637  switch (getCastKind()) {
1638 #define CAST_OPERATION(Name) case CK_##Name: return #Name;
1639 #include "clang/AST/OperationKinds.def"
1640  }
1641  llvm_unreachable("Unhandled cast kind!");
1642 }
1643 
1644 namespace {
1645  Expr *skipImplicitTemporary(Expr *expr) {
1646  // Skip through reference binding to temporary.
1647  if (MaterializeTemporaryExpr *Materialize
1648  = dyn_cast<MaterializeTemporaryExpr>(expr))
1649  expr = Materialize->GetTemporaryExpr();
1650 
1651  // Skip any temporary bindings; they're implicit.
1652  if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(expr))
1653  expr = Binder->getSubExpr();
1654 
1655  return expr;
1656  }
1657 }
1658 
1660  Expr *SubExpr = nullptr;
1661  CastExpr *E = this;
1662  do {
1663  SubExpr = skipImplicitTemporary(E->getSubExpr());
1664 
1665  // Conversions by constructor and conversion functions have a
1666  // subexpression describing the call; strip it off.
1667  if (E->getCastKind() == CK_ConstructorConversion)
1668  SubExpr =
1669  skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
1670  else if (E->getCastKind() == CK_UserDefinedConversion) {
1671  assert((isa<CXXMemberCallExpr>(SubExpr) ||
1672  isa<BlockExpr>(SubExpr)) &&
1673  "Unexpected SubExpr for CK_UserDefinedConversion.");
1674  if (isa<CXXMemberCallExpr>(SubExpr))
1675  SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1676  }
1677 
1678  // If the subexpression we're left with is an implicit cast, look
1679  // through that, too.
1680  } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1681 
1682  return SubExpr;
1683 }
1684 
1685 CXXBaseSpecifier **CastExpr::path_buffer() {
1686  switch (getStmtClass()) {
1687 #define ABSTRACT_STMT(x)
1688 #define CASTEXPR(Type, Base) \
1689  case Stmt::Type##Class: \
1690  return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1691 #define STMT(Type, Base)
1692 #include "clang/AST/StmtNodes.inc"
1693  default:
1694  llvm_unreachable("non-cast expressions not possible here");
1695  }
1696 }
1697 
1699  QualType opType) {
1700  auto RD = unionType->castAs<RecordType>()->getDecl();
1701  return getTargetFieldForToUnionCast(RD, opType);
1702 }
1703 
1705  QualType OpType) {
1706  auto &Ctx = RD->getASTContext();
1707  RecordDecl::field_iterator Field, FieldEnd;
1708  for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1709  Field != FieldEnd; ++Field) {
1710  if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1711  !Field->isUnnamedBitfield()) {
1712  return *Field;
1713  }
1714  }
1715  return nullptr;
1716 }
1717 
1719  CastKind Kind, Expr *Operand,
1720  const CXXCastPath *BasePath,
1721  ExprValueKind VK) {
1722  unsigned PathSize = (BasePath ? BasePath->size() : 0);
1723  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1724  ImplicitCastExpr *E =
1725  new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1726  if (PathSize)
1727  std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1728  E->getTrailingObjects<CXXBaseSpecifier *>());
1729  return E;
1730 }
1731 
1733  unsigned PathSize) {
1734  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1735  return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1736 }
1737 
1738 
1740  ExprValueKind VK, CastKind K, Expr *Op,
1741  const CXXCastPath *BasePath,
1742  TypeSourceInfo *WrittenTy,
1744  unsigned PathSize = (BasePath ? BasePath->size() : 0);
1745  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1746  CStyleCastExpr *E =
1747  new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1748  if (PathSize)
1749  std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1750  E->getTrailingObjects<CXXBaseSpecifier *>());
1751  return E;
1752 }
1753 
1755  unsigned PathSize) {
1756  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1757  return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1758 }
1759 
1760 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1761 /// corresponds to, e.g. "<<=".
1763  switch (Op) {
1764 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1765 #include "clang/AST/OperationKinds.def"
1766  }
1767  llvm_unreachable("Invalid OpCode!");
1768 }
1769 
1772  switch (OO) {
1773  default: llvm_unreachable("Not an overloadable binary operator");
1774  case OO_Plus: return BO_Add;
1775  case OO_Minus: return BO_Sub;
1776  case OO_Star: return BO_Mul;
1777  case OO_Slash: return BO_Div;
1778  case OO_Percent: return BO_Rem;
1779  case OO_Caret: return BO_Xor;
1780  case OO_Amp: return BO_And;
1781  case OO_Pipe: return BO_Or;
1782  case OO_Equal: return BO_Assign;
1783  case OO_Less: return BO_LT;
1784  case OO_Greater: return BO_GT;
1785  case OO_PlusEqual: return BO_AddAssign;
1786  case OO_MinusEqual: return BO_SubAssign;
1787  case OO_StarEqual: return BO_MulAssign;
1788  case OO_SlashEqual: return BO_DivAssign;
1789  case OO_PercentEqual: return BO_RemAssign;
1790  case OO_CaretEqual: return BO_XorAssign;
1791  case OO_AmpEqual: return BO_AndAssign;
1792  case OO_PipeEqual: return BO_OrAssign;
1793  case OO_LessLess: return BO_Shl;
1794  case OO_GreaterGreater: return BO_Shr;
1795  case OO_LessLessEqual: return BO_ShlAssign;
1796  case OO_GreaterGreaterEqual: return BO_ShrAssign;
1797  case OO_EqualEqual: return BO_EQ;
1798  case OO_ExclaimEqual: return BO_NE;
1799  case OO_LessEqual: return BO_LE;
1800  case OO_GreaterEqual: return BO_GE;
1801  case OO_AmpAmp: return BO_LAnd;
1802  case OO_PipePipe: return BO_LOr;
1803  case OO_Comma: return BO_Comma;
1804  case OO_ArrowStar: return BO_PtrMemI;
1805  }
1806 }
1807 
1809  static const OverloadedOperatorKind OverOps[] = {
1810  /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1811  OO_Star, OO_Slash, OO_Percent,
1812  OO_Plus, OO_Minus,
1813  OO_LessLess, OO_GreaterGreater,
1814  OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1815  OO_EqualEqual, OO_ExclaimEqual,
1816  OO_Amp,
1817  OO_Caret,
1818  OO_Pipe,
1819  OO_AmpAmp,
1820  OO_PipePipe,
1821  OO_Equal, OO_StarEqual,
1822  OO_SlashEqual, OO_PercentEqual,
1823  OO_PlusEqual, OO_MinusEqual,
1824  OO_LessLessEqual, OO_GreaterGreaterEqual,
1825  OO_AmpEqual, OO_CaretEqual,
1826  OO_PipeEqual,
1827  OO_Comma
1828  };
1829  return OverOps[Opc];
1830 }
1831 
1833  Opcode Opc,
1834  Expr *LHS, Expr *RHS) {
1835  if (Opc != BO_Add)
1836  return false;
1837 
1838  // Check that we have one pointer and one integer operand.
1839  Expr *PExp;
1840  if (LHS->getType()->isPointerType()) {
1841  if (!RHS->getType()->isIntegerType())
1842  return false;
1843  PExp = LHS;
1844  } else if (RHS->getType()->isPointerType()) {
1845  if (!LHS->getType()->isIntegerType())
1846  return false;
1847  PExp = RHS;
1848  } else {
1849  return false;
1850  }
1851 
1852  // Check that the pointer is a nullptr.
1853  if (!PExp->IgnoreParenCasts()
1855  return false;
1856 
1857  // Check that the pointee type is char-sized.
1858  const PointerType *PTy = PExp->getType()->getAs<PointerType>();
1859  if (!PTy || !PTy->getPointeeType()->isCharType())
1860  return false;
1861 
1862  return true;
1863 }
1865  ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
1866  : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1867  false, false),
1868  InitExprs(C, initExprs.size()),
1869  LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
1870 {
1871  sawArrayRangeDesignator(false);
1872  for (unsigned I = 0; I != initExprs.size(); ++I) {
1873  if (initExprs[I]->isTypeDependent())
1874  ExprBits.TypeDependent = true;
1875  if (initExprs[I]->isValueDependent())
1876  ExprBits.ValueDependent = true;
1877  if (initExprs[I]->isInstantiationDependent())
1878  ExprBits.InstantiationDependent = true;
1879  if (initExprs[I]->containsUnexpandedParameterPack())
1880  ExprBits.ContainsUnexpandedParameterPack = true;
1881  }
1882 
1883  InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
1884 }
1885 
1886 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
1887  if (NumInits > InitExprs.size())
1888  InitExprs.reserve(C, NumInits);
1889 }
1890 
1891 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
1892  InitExprs.resize(C, NumInits, nullptr);
1893 }
1894 
1895 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
1896  if (Init >= InitExprs.size()) {
1897  InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
1898  setInit(Init, expr);
1899  return nullptr;
1900  }
1901 
1902  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1903  setInit(Init, expr);
1904  return Result;
1905 }
1906 
1908  assert(!hasArrayFiller() && "Filler already set!");
1909  ArrayFillerOrUnionFieldInit = filler;
1910  // Fill out any "holes" in the array due to designated initializers.
1911  Expr **inits = getInits();
1912  for (unsigned i = 0, e = getNumInits(); i != e; ++i)
1913  if (inits[i] == nullptr)
1914  inits[i] = filler;
1915 }
1916 
1918  if (getNumInits() != 1)
1919  return false;
1920  const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
1921  if (!AT || !AT->getElementType()->isIntegerType())
1922  return false;
1923  // It is possible for getInit() to return null.
1924  const Expr *Init = getInit(0);
1925  if (!Init)
1926  return false;
1927  Init = Init->IgnoreParens();
1928  return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
1929 }
1930 
1932  assert(isSemanticForm() && "syntactic form never semantically transparent");
1933 
1934  // A glvalue InitListExpr is always just sugar.
1935  if (isGLValue()) {
1936  assert(getNumInits() == 1 && "multiple inits in glvalue init list");
1937  return true;
1938  }
1939 
1940  // Otherwise, we're sugar if and only if we have exactly one initializer that
1941  // is of the same type.
1942  if (getNumInits() != 1 || !getInit(0))
1943  return false;
1944 
1945  // Don't confuse aggregate initialization of a struct X { X &x; }; with a
1946  // transparent struct copy.
1947  if (!getInit(0)->isRValue() && getType()->isRecordType())
1948  return false;
1949 
1950  return getType().getCanonicalType() ==
1952 }
1953 
1955  assert(isSyntacticForm() && "only test syntactic form as zero initializer");
1956 
1957  if (LangOpts.CPlusPlus || getNumInits() != 1) {
1958  return false;
1959  }
1960 
1961  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
1962  return Lit && Lit->getValue() == 0;
1963 }
1964 
1966  if (InitListExpr *SyntacticForm = getSyntacticForm())
1967  return SyntacticForm->getLocStart();
1968  SourceLocation Beg = LBraceLoc;
1969  if (Beg.isInvalid()) {
1970  // Find the first non-null initializer.
1971  for (InitExprsTy::const_iterator I = InitExprs.begin(),
1972  E = InitExprs.end();
1973  I != E; ++I) {
1974  if (Stmt *S = *I) {
1975  Beg = S->getLocStart();
1976  break;
1977  }
1978  }
1979  }
1980  return Beg;
1981 }
1982 
1984  if (InitListExpr *SyntacticForm = getSyntacticForm())
1985  return SyntacticForm->getLocEnd();
1986  SourceLocation End = RBraceLoc;
1987  if (End.isInvalid()) {
1988  // Find the first non-null initializer from the end.
1989  for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1990  E = InitExprs.rend();
1991  I != E; ++I) {
1992  if (Stmt *S = *I) {
1993  End = S->getLocEnd();
1994  break;
1995  }
1996  }
1997  }
1998  return End;
1999 }
2000 
2001 /// getFunctionType - Return the underlying function type for this block.
2002 ///
2004  // The block pointer is never sugared, but the function type might be.
2005  return cast<BlockPointerType>(getType())
2006  ->getPointeeType()->castAs<FunctionProtoType>();
2007 }
2008 
2010  return TheBlock->getCaretLocation();
2011 }
2012 const Stmt *BlockExpr::getBody() const {
2013  return TheBlock->getBody();
2014 }
2016  return TheBlock->getBody();
2017 }
2018 
2019 
2020 //===----------------------------------------------------------------------===//
2021 // Generic Expression Routines
2022 //===----------------------------------------------------------------------===//
2023 
2024 /// isUnusedResultAWarning - Return true if this immediate expression should
2025 /// be warned about if the result is unused. If so, fill in Loc and Ranges
2026 /// with location to warn on and the source range[s] to report with the
2027 /// warning.
2029  SourceRange &R1, SourceRange &R2,
2030  ASTContext &Ctx) const {
2031  // Don't warn if the expr is type dependent. The type could end up
2032  // instantiating to void.
2033  if (isTypeDependent())
2034  return false;
2035 
2036  switch (getStmtClass()) {
2037  default:
2038  if (getType()->isVoidType())
2039  return false;
2040  WarnE = this;
2041  Loc = getExprLoc();
2042  R1 = getSourceRange();
2043  return true;
2044  case ParenExprClass:
2045  return cast<ParenExpr>(this)->getSubExpr()->
2046  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2047  case GenericSelectionExprClass:
2048  return cast<GenericSelectionExpr>(this)->getResultExpr()->
2049  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2050  case ChooseExprClass:
2051  return cast<ChooseExpr>(this)->getChosenSubExpr()->
2052  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2053  case UnaryOperatorClass: {
2054  const UnaryOperator *UO = cast<UnaryOperator>(this);
2055 
2056  switch (UO->getOpcode()) {
2057  case UO_Plus:
2058  case UO_Minus:
2059  case UO_AddrOf:
2060  case UO_Not:
2061  case UO_LNot:
2062  case UO_Deref:
2063  break;
2064  case UO_Coawait:
2065  // This is just the 'operator co_await' call inside the guts of a
2066  // dependent co_await call.
2067  case UO_PostInc:
2068  case UO_PostDec:
2069  case UO_PreInc:
2070  case UO_PreDec: // ++/--
2071  return false; // Not a warning.
2072  case UO_Real:
2073  case UO_Imag:
2074  // accessing a piece of a volatile complex is a side-effect.
2075  if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2076  .isVolatileQualified())
2077  return false;
2078  break;
2079  case UO_Extension:
2080  return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2081  }
2082  WarnE = this;
2083  Loc = UO->getOperatorLoc();
2084  R1 = UO->getSubExpr()->getSourceRange();
2085  return true;
2086  }
2087  case BinaryOperatorClass: {
2088  const BinaryOperator *BO = cast<BinaryOperator>(this);
2089  switch (BO->getOpcode()) {
2090  default:
2091  break;
2092  // Consider the RHS of comma for side effects. LHS was checked by
2093  // Sema::CheckCommaOperands.
2094  case BO_Comma:
2095  // ((foo = <blah>), 0) is an idiom for hiding the result (and
2096  // lvalue-ness) of an assignment written in a macro.
2097  if (IntegerLiteral *IE =
2098  dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2099  if (IE->getValue() == 0)
2100  return false;
2101  return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2102  // Consider '||', '&&' to have side effects if the LHS or RHS does.
2103  case BO_LAnd:
2104  case BO_LOr:
2105  if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2106  !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2107  return false;
2108  break;
2109  }
2110  if (BO->isAssignmentOp())
2111  return false;
2112  WarnE = this;
2113  Loc = BO->getOperatorLoc();
2114  R1 = BO->getLHS()->getSourceRange();
2115  R2 = BO->getRHS()->getSourceRange();
2116  return true;
2117  }
2118  case CompoundAssignOperatorClass:
2119  case VAArgExprClass:
2120  case AtomicExprClass:
2121  return false;
2122 
2123  case ConditionalOperatorClass: {
2124  // If only one of the LHS or RHS is a warning, the operator might
2125  // be being used for control flow. Only warn if both the LHS and
2126  // RHS are warnings.
2127  const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
2128  if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2129  return false;
2130  if (!Exp->getLHS())
2131  return true;
2132  return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2133  }
2134 
2135  case MemberExprClass:
2136  WarnE = this;
2137  Loc = cast<MemberExpr>(this)->getMemberLoc();
2138  R1 = SourceRange(Loc, Loc);
2139  R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2140  return true;
2141 
2142  case ArraySubscriptExprClass:
2143  WarnE = this;
2144  Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2145  R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2146  R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2147  return true;
2148 
2149  case CXXOperatorCallExprClass: {
2150  // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2151  // overloads as there is no reasonable way to define these such that they
2152  // have non-trivial, desirable side-effects. See the -Wunused-comparison
2153  // warning: operators == and != are commonly typo'ed, and so warning on them
2154  // provides additional value as well. If this list is updated,
2155  // DiagnoseUnusedComparison should be as well.
2156  const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2157  switch (Op->getOperator()) {
2158  default:
2159  break;
2160  case OO_EqualEqual:
2161  case OO_ExclaimEqual:
2162  case OO_Less:
2163  case OO_Greater:
2164  case OO_GreaterEqual:
2165  case OO_LessEqual:
2166  if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2167  Op->getCallReturnType(Ctx)->isVoidType())
2168  break;
2169  WarnE = this;
2170  Loc = Op->getOperatorLoc();
2171  R1 = Op->getSourceRange();
2172  return true;
2173  }
2174 
2175  // Fallthrough for generic call handling.
2176  LLVM_FALLTHROUGH;
2177  }
2178  case CallExprClass:
2179  case CXXMemberCallExprClass:
2180  case UserDefinedLiteralClass: {
2181  // If this is a direct call, get the callee.
2182  const CallExpr *CE = cast<CallExpr>(this);
2183  if (const Decl *FD = CE->getCalleeDecl()) {
2184  const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2185  bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2186  : FD->hasAttr<WarnUnusedResultAttr>();
2187 
2188  // If the callee has attribute pure, const, or warn_unused_result, warn
2189  // about it. void foo() { strlen("bar"); } should warn.
2190  //
2191  // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2192  // updated to match for QoI.
2193  if (HasWarnUnusedResultAttr ||
2194  FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2195  WarnE = this;
2196  Loc = CE->getCallee()->getLocStart();
2197  R1 = CE->getCallee()->getSourceRange();
2198 
2199  if (unsigned NumArgs = CE->getNumArgs())
2200  R2 = SourceRange(CE->getArg(0)->getLocStart(),
2201  CE->getArg(NumArgs-1)->getLocEnd());
2202  return true;
2203  }
2204  }
2205  return false;
2206  }
2207 
2208  // If we don't know precisely what we're looking at, let's not warn.
2209  case UnresolvedLookupExprClass:
2210  case CXXUnresolvedConstructExprClass:
2211  return false;
2212 
2213  case CXXTemporaryObjectExprClass:
2214  case CXXConstructExprClass: {
2215  if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2216  if (Type->hasAttr<WarnUnusedAttr>()) {
2217  WarnE = this;
2218  Loc = getLocStart();
2219  R1 = getSourceRange();
2220  return true;
2221  }
2222  }
2223  return false;
2224  }
2225 
2226  case ObjCMessageExprClass: {
2227  const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2228  if (Ctx.getLangOpts().ObjCAutoRefCount &&
2229  ME->isInstanceMessage() &&
2230  !ME->getType()->isVoidType() &&
2231  ME->getMethodFamily() == OMF_init) {
2232  WarnE = this;
2233  Loc = getExprLoc();
2234  R1 = ME->getSourceRange();
2235  return true;
2236  }
2237 
2238  if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2239  if (MD->hasAttr<WarnUnusedResultAttr>()) {
2240  WarnE = this;
2241  Loc = getExprLoc();
2242  return true;
2243  }
2244 
2245  return false;
2246  }
2247 
2248  case ObjCPropertyRefExprClass:
2249  WarnE = this;
2250  Loc = getExprLoc();
2251  R1 = getSourceRange();
2252  return true;
2253 
2254  case PseudoObjectExprClass: {
2255  const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2256 
2257  // Only complain about things that have the form of a getter.
2258  if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2259  isa<BinaryOperator>(PO->getSyntacticForm()))
2260  return false;
2261 
2262  WarnE = this;
2263  Loc = getExprLoc();
2264  R1 = getSourceRange();
2265  return true;
2266  }
2267 
2268  case StmtExprClass: {
2269  // Statement exprs don't logically have side effects themselves, but are
2270  // sometimes used in macros in ways that give them a type that is unused.
2271  // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2272  // however, if the result of the stmt expr is dead, we don't want to emit a
2273  // warning.
2274  const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2275  if (!CS->body_empty()) {
2276  if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2277  return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2278  if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2279  if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2280  return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2281  }
2282 
2283  if (getType()->isVoidType())
2284  return false;
2285  WarnE = this;
2286  Loc = cast<StmtExpr>(this)->getLParenLoc();
2287  R1 = getSourceRange();
2288  return true;
2289  }
2290  case CXXFunctionalCastExprClass:
2291  case CStyleCastExprClass: {
2292  // Ignore an explicit cast to void unless the operand is a non-trivial
2293  // volatile lvalue.
2294  const CastExpr *CE = cast<CastExpr>(this);
2295  if (CE->getCastKind() == CK_ToVoid) {
2296  if (CE->getSubExpr()->isGLValue() &&
2297  CE->getSubExpr()->getType().isVolatileQualified()) {
2298  const DeclRefExpr *DRE =
2299  dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2300  if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2301  cast<VarDecl>(DRE->getDecl())->hasLocalStorage())) {
2302  return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2303  R1, R2, Ctx);
2304  }
2305  }
2306  return false;
2307  }
2308 
2309  // If this is a cast to a constructor conversion, check the operand.
2310  // Otherwise, the result of the cast is unused.
2311  if (CE->getCastKind() == CK_ConstructorConversion)
2312  return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2313 
2314  WarnE = this;
2315  if (const CXXFunctionalCastExpr *CXXCE =
2316  dyn_cast<CXXFunctionalCastExpr>(this)) {
2317  Loc = CXXCE->getLocStart();
2318  R1 = CXXCE->getSubExpr()->getSourceRange();
2319  } else {
2320  const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2321  Loc = CStyleCE->getLParenLoc();
2322  R1 = CStyleCE->getSubExpr()->getSourceRange();
2323  }
2324  return true;
2325  }
2326  case ImplicitCastExprClass: {
2327  const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2328 
2329  // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2330  if (ICE->getCastKind() == CK_LValueToRValue &&
2332  return false;
2333 
2334  return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2335  }
2336  case CXXDefaultArgExprClass:
2337  return (cast<CXXDefaultArgExpr>(this)
2338  ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2339  case CXXDefaultInitExprClass:
2340  return (cast<CXXDefaultInitExpr>(this)
2341  ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2342 
2343  case CXXNewExprClass:
2344  // FIXME: In theory, there might be new expressions that don't have side
2345  // effects (e.g. a placement new with an uninitialized POD).
2346  case CXXDeleteExprClass:
2347  return false;
2348  case MaterializeTemporaryExprClass:
2349  return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2350  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2351  case CXXBindTemporaryExprClass:
2352  return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2353  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2354  case ExprWithCleanupsClass:
2355  return cast<ExprWithCleanups>(this)->getSubExpr()
2356  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2357  }
2358 }
2359 
2360 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2361 /// returns true, if it is; false otherwise.
2363  const Expr *E = IgnoreParens();
2364  switch (E->getStmtClass()) {
2365  default:
2366  return false;
2367  case ObjCIvarRefExprClass:
2368  return true;
2369  case Expr::UnaryOperatorClass:
2370  return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2371  case ImplicitCastExprClass:
2372  return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2373  case MaterializeTemporaryExprClass:
2374  return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2375  ->isOBJCGCCandidate(Ctx);
2376  case CStyleCastExprClass:
2377  return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2378  case DeclRefExprClass: {
2379  const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2380 
2381  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2382  if (VD->hasGlobalStorage())
2383  return true;
2384  QualType T = VD->getType();
2385  // dereferencing to a pointer is always a gc'able candidate,
2386  // unless it is __weak.
2387  return T->isPointerType() &&
2388  (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2389  }
2390  return false;
2391  }
2392  case MemberExprClass: {
2393  const MemberExpr *M = cast<MemberExpr>(E);
2394  return M->getBase()->isOBJCGCCandidate(Ctx);
2395  }
2396  case ArraySubscriptExprClass:
2397  return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2398  }
2399 }
2400 
2402  if (isTypeDependent())
2403  return false;
2404  return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2405 }
2406 
2408  assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2409 
2410  // Bound member expressions are always one of these possibilities:
2411  // x->m x.m x->*y x.*y
2412  // (possibly parenthesized)
2413 
2414  expr = expr->IgnoreParens();
2415  if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2416  assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2417  return mem->getMemberDecl()->getType();
2418  }
2419 
2420  if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2421  QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2422  ->getPointeeType();
2423  assert(type->isFunctionType());
2424  return type;
2425  }
2426 
2427  assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
2428  return QualType();
2429 }
2430 
2432  Expr* E = this;
2433  while (true) {
2434  if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2435  E = P->getSubExpr();
2436  continue;
2437  }
2438  if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2439  if (P->getOpcode() == UO_Extension) {
2440  E = P->getSubExpr();
2441  continue;
2442  }
2443  }
2444  if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2445  if (!P->isResultDependent()) {
2446  E = P->getResultExpr();
2447  continue;
2448  }
2449  }
2450  if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2451  if (!P->isConditionDependent()) {
2452  E = P->getChosenSubExpr();
2453  continue;
2454  }
2455  }
2456  return E;
2457  }
2458 }
2459 
2460 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2461 /// or CastExprs or ImplicitCastExprs, returning their operand.
2463  Expr *E = this;
2464  while (true) {
2465  E = E->IgnoreParens();
2466  if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2467  E = P->getSubExpr();
2468  continue;
2469  }
2470  if (MaterializeTemporaryExpr *Materialize
2471  = dyn_cast<MaterializeTemporaryExpr>(E)) {
2472  E = Materialize->GetTemporaryExpr();
2473  continue;
2474  }
2476  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2477  E = NTTP->getReplacement();
2478  continue;
2479  }
2480  return E;
2481  }
2482 }
2483 
2485  Expr *E = this;
2486  while (true) {
2487  if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2488  E = P->getSubExpr();
2489  continue;
2490  }
2491  if (MaterializeTemporaryExpr *Materialize
2492  = dyn_cast<MaterializeTemporaryExpr>(E)) {
2493  E = Materialize->GetTemporaryExpr();
2494  continue;
2495  }
2497  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2498  E = NTTP->getReplacement();
2499  continue;
2500  }
2501  return E;
2502  }
2503 }
2504 
2505 /// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2506 /// casts. This is intended purely as a temporary workaround for code
2507 /// that hasn't yet been rewritten to do the right thing about those
2508 /// casts, and may disappear along with the last internal use.
2510  Expr *E = this;
2511  while (true) {
2512  E = E->IgnoreParens();
2513  if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2514  if (P->getCastKind() == CK_LValueToRValue) {
2515  E = P->getSubExpr();
2516  continue;
2517  }
2518  } else if (MaterializeTemporaryExpr *Materialize
2519  = dyn_cast<MaterializeTemporaryExpr>(E)) {
2520  E = Materialize->GetTemporaryExpr();
2521  continue;
2522  } else if (SubstNonTypeTemplateParmExpr *NTTP
2523  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2524  E = NTTP->getReplacement();
2525  continue;
2526  }
2527  break;
2528  }
2529  return E;
2530 }
2531 
2533  Expr *E = this;
2534  while (true) {
2535  E = E->IgnoreParens();
2536  if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2537  if (CE->getCastKind() == CK_DerivedToBase ||
2538  CE->getCastKind() == CK_UncheckedDerivedToBase ||
2539  CE->getCastKind() == CK_NoOp) {
2540  E = CE->getSubExpr();
2541  continue;
2542  }
2543  }
2544 
2545  return E;
2546  }
2547 }
2548 
2550  Expr *E = this;
2551  while (true) {
2552  E = E->IgnoreParens();
2553  if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
2554  E = P->getSubExpr();
2555  continue;
2556  }
2557  if (MaterializeTemporaryExpr *Materialize
2558  = dyn_cast<MaterializeTemporaryExpr>(E)) {
2559  E = Materialize->GetTemporaryExpr();
2560  continue;
2561  }
2563  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2564  E = NTTP->getReplacement();
2565  continue;
2566  }
2567  return E;
2568  }
2569 }
2570 
2572  if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2573  if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2574  return MCE->getImplicitObjectArgument();
2575  }
2576  return this;
2577 }
2578 
2579 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2580 /// value (including ptr->int casts of the same size). Strip off any
2581 /// ParenExpr or CastExprs, returning their operand.
2583  Expr *E = this;
2584  while (true) {
2585  E = E->IgnoreParens();
2586 
2587  if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2588  // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2589  // ptr<->int casts of the same width. We also ignore all identity casts.
2590  Expr *SE = P->getSubExpr();
2591 
2592  if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2593  E = SE;
2594  continue;
2595  }
2596 
2597  if ((E->getType()->isPointerType() ||
2598  E->getType()->isIntegralType(Ctx)) &&
2599  (SE->getType()->isPointerType() ||
2600  SE->getType()->isIntegralType(Ctx)) &&
2601  Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2602  E = SE;
2603  continue;
2604  }
2605  }
2606 
2608  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2609  E = NTTP->getReplacement();
2610  continue;
2611  }
2612 
2613  return E;
2614  }
2615 }
2616 
2618  const Expr *E = this;
2619  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2620  E = M->GetTemporaryExpr();
2621 
2622  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2623  E = ICE->getSubExprAsWritten();
2624 
2625  return isa<CXXDefaultArgExpr>(E);
2626 }
2627 
2628 /// \brief Skip over any no-op casts and any temporary-binding
2629 /// expressions.
2631  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2632  E = M->GetTemporaryExpr();
2633 
2634  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2635  if (ICE->getCastKind() == CK_NoOp)
2636  E = ICE->getSubExpr();
2637  else
2638  break;
2639  }
2640 
2641  while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2642  E = BE->getSubExpr();
2643 
2644  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2645  if (ICE->getCastKind() == CK_NoOp)
2646  E = ICE->getSubExpr();
2647  else
2648  break;
2649  }
2650 
2651  return E->IgnoreParens();
2652 }
2653 
2654 /// isTemporaryObject - Determines if this expression produces a
2655 /// temporary of the given class type.
2656 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2657  if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2658  return false;
2659 
2661 
2662  // Temporaries are by definition pr-values of class type.
2663  if (!E->Classify(C).isPRValue()) {
2664  // In this context, property reference is a message call and is pr-value.
2665  if (!isa<ObjCPropertyRefExpr>(E))
2666  return false;
2667  }
2668 
2669  // Black-list a few cases which yield pr-values of class type that don't
2670  // refer to temporaries of that type:
2671 
2672  // - implicit derived-to-base conversions
2673  if (isa<ImplicitCastExpr>(E)) {
2674  switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2675  case CK_DerivedToBase:
2676  case CK_UncheckedDerivedToBase:
2677  return false;
2678  default:
2679  break;
2680  }
2681  }
2682 
2683  // - member expressions (all)
2684  if (isa<MemberExpr>(E))
2685  return false;
2686 
2687  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2688  if (BO->isPtrMemOp())
2689  return false;
2690 
2691  // - opaque values (all)
2692  if (isa<OpaqueValueExpr>(E))
2693  return false;
2694 
2695  return true;
2696 }
2697 
2699  const Expr *E = this;
2700 
2701  // Strip away parentheses and casts we don't care about.
2702  while (true) {
2703  if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2704  E = Paren->getSubExpr();
2705  continue;
2706  }
2707 
2708  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2709  if (ICE->getCastKind() == CK_NoOp ||
2710  ICE->getCastKind() == CK_LValueToRValue ||
2711  ICE->getCastKind() == CK_DerivedToBase ||
2712  ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2713  E = ICE->getSubExpr();
2714  continue;
2715  }
2716  }
2717 
2718  if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2719  if (UnOp->getOpcode() == UO_Extension) {
2720  E = UnOp->getSubExpr();
2721  continue;
2722  }
2723  }
2724 
2725  if (const MaterializeTemporaryExpr *M
2726  = dyn_cast<MaterializeTemporaryExpr>(E)) {
2727  E = M->GetTemporaryExpr();
2728  continue;
2729  }
2730 
2731  break;
2732  }
2733 
2734  if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2735  return This->isImplicit();
2736 
2737  return false;
2738 }
2739 
2740 /// hasAnyTypeDependentArguments - Determines if any of the expressions
2741 /// in Exprs is type-dependent.
2743  for (unsigned I = 0; I < Exprs.size(); ++I)
2744  if (Exprs[I]->isTypeDependent())
2745  return true;
2746 
2747  return false;
2748 }
2749 
2750 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2751  const Expr **Culprit) const {
2752  // This function is attempting whether an expression is an initializer
2753  // which can be evaluated at compile-time. It very closely parallels
2754  // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2755  // will lead to unexpected results. Like ConstExprEmitter, it falls back
2756  // to isEvaluatable most of the time.
2757  //
2758  // If we ever capture reference-binding directly in the AST, we can
2759  // kill the second parameter.
2760 
2761  if (IsForRef) {
2763  if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2764  return true;
2765  if (Culprit)
2766  *Culprit = this;
2767  return false;
2768  }
2769 
2770  switch (getStmtClass()) {
2771  default: break;
2772  case StringLiteralClass:
2773  case ObjCEncodeExprClass:
2774  return true;
2775  case CXXTemporaryObjectExprClass:
2776  case CXXConstructExprClass: {
2777  const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2778 
2779  if (CE->getConstructor()->isTrivial() &&
2781  // Trivial default constructor
2782  if (!CE->getNumArgs()) return true;
2783 
2784  // Trivial copy constructor
2785  assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
2786  return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
2787  }
2788 
2789  break;
2790  }
2791  case CompoundLiteralExprClass: {
2792  // This handles gcc's extension that allows global initializers like
2793  // "struct x {int x;} x = (struct x) {};".
2794  // FIXME: This accepts other cases it shouldn't!
2795  const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2796  return Exp->isConstantInitializer(Ctx, false, Culprit);
2797  }
2798  case DesignatedInitUpdateExprClass: {
2799  const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2800  return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2801  DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2802  }
2803  case InitListExprClass: {
2804  const InitListExpr *ILE = cast<InitListExpr>(this);
2805  if (ILE->getType()->isArrayType()) {
2806  unsigned numInits = ILE->getNumInits();
2807  for (unsigned i = 0; i < numInits; i++) {
2808  if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
2809  return false;
2810  }
2811  return true;
2812  }
2813 
2814  if (ILE->getType()->isRecordType()) {
2815  unsigned ElementNo = 0;
2816  RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
2817  for (const auto *Field : RD->fields()) {
2818  // If this is a union, skip all the fields that aren't being initialized.
2819  if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
2820  continue;
2821 
2822  // Don't emit anonymous bitfields, they just affect layout.
2823  if (Field->isUnnamedBitfield())
2824  continue;
2825 
2826  if (ElementNo < ILE->getNumInits()) {
2827  const Expr *Elt = ILE->getInit(ElementNo++);
2828  if (Field->isBitField()) {
2829  // Bitfields have to evaluate to an integer.
2830  llvm::APSInt ResultTmp;
2831  if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
2832  if (Culprit)
2833  *Culprit = Elt;
2834  return false;
2835  }
2836  } else {
2837  bool RefType = Field->getType()->isReferenceType();
2838  if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
2839  return false;
2840  }
2841  }
2842  }
2843  return true;
2844  }
2845 
2846  break;
2847  }
2848  case ImplicitValueInitExprClass:
2849  case NoInitExprClass:
2850  return true;
2851  case ParenExprClass:
2852  return cast<ParenExpr>(this)->getSubExpr()
2853  ->isConstantInitializer(Ctx, IsForRef, Culprit);
2854  case GenericSelectionExprClass:
2855  return cast<GenericSelectionExpr>(this)->getResultExpr()
2856  ->isConstantInitializer(Ctx, IsForRef, Culprit);
2857  case ChooseExprClass:
2858  if (cast<ChooseExpr>(this)->isConditionDependent()) {
2859  if (Culprit)
2860  *Culprit = this;
2861  return false;
2862  }
2863  return cast<ChooseExpr>(this)->getChosenSubExpr()
2864  ->isConstantInitializer(Ctx, IsForRef, Culprit);
2865  case UnaryOperatorClass: {
2866  const UnaryOperator* Exp = cast<UnaryOperator>(this);
2867  if (Exp->getOpcode() == UO_Extension)
2868  return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
2869  break;
2870  }
2871  case CXXFunctionalCastExprClass:
2872  case CXXStaticCastExprClass:
2873  case ImplicitCastExprClass:
2874  case CStyleCastExprClass:
2875  case ObjCBridgedCastExprClass:
2876  case CXXDynamicCastExprClass:
2877  case CXXReinterpretCastExprClass:
2878  case CXXConstCastExprClass: {
2879  const CastExpr *CE = cast<CastExpr>(this);
2880 
2881  // Handle misc casts we want to ignore.
2882  if (CE->getCastKind() == CK_NoOp ||
2883  CE->getCastKind() == CK_LValueToRValue ||
2884  CE->getCastKind() == CK_ToUnion ||
2885  CE->getCastKind() == CK_ConstructorConversion ||
2886  CE->getCastKind() == CK_NonAtomicToAtomic ||
2887  CE->getCastKind() == CK_AtomicToNonAtomic ||
2888  CE->getCastKind() == CK_IntToOCLSampler)
2889  return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
2890 
2891  break;
2892  }
2893  case MaterializeTemporaryExprClass:
2894  return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2895  ->isConstantInitializer(Ctx, false, Culprit);
2896 
2897  case SubstNonTypeTemplateParmExprClass:
2898  return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
2899  ->isConstantInitializer(Ctx, false, Culprit);
2900  case CXXDefaultArgExprClass:
2901  return cast<CXXDefaultArgExpr>(this)->getExpr()
2902  ->isConstantInitializer(Ctx, false, Culprit);
2903  case CXXDefaultInitExprClass:
2904  return cast<CXXDefaultInitExpr>(this)->getExpr()
2905  ->isConstantInitializer(Ctx, false, Culprit);
2906  }
2907  // Allow certain forms of UB in constant initializers: signed integer
2908  // overflow and floating-point division by zero. We'll give a warning on
2909  // these, but they're common enough that we have to accept them.
2911  return true;
2912  if (Culprit)
2913  *Culprit = this;
2914  return false;
2915 }
2916 
2917 namespace {
2918  /// \brief Look for any side effects within a Stmt.
2919  class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
2921  const bool IncludePossibleEffects;
2922  bool HasSideEffects;
2923 
2924  public:
2925  explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
2926  : Inherited(Context),
2927  IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
2928 
2929  bool hasSideEffects() const { return HasSideEffects; }
2930 
2931  void VisitExpr(const Expr *E) {
2932  if (!HasSideEffects &&
2933  E->HasSideEffects(Context, IncludePossibleEffects))
2934  HasSideEffects = true;
2935  }
2936  };
2937 }
2938 
2940  bool IncludePossibleEffects) const {
2941  // In circumstances where we care about definite side effects instead of
2942  // potential side effects, we want to ignore expressions that are part of a
2943  // macro expansion as a potential side effect.
2944  if (!IncludePossibleEffects && getExprLoc().isMacroID())
2945  return false;
2946 
2948  return IncludePossibleEffects;
2949 
2950  switch (getStmtClass()) {
2951  case NoStmtClass:
2952  #define ABSTRACT_STMT(Type)
2953  #define STMT(Type, Base) case Type##Class:
2954  #define EXPR(Type, Base)
2955  #include "clang/AST/StmtNodes.inc"
2956  llvm_unreachable("unexpected Expr kind");
2957 
2958  case DependentScopeDeclRefExprClass:
2959  case CXXUnresolvedConstructExprClass:
2960  case CXXDependentScopeMemberExprClass:
2961  case UnresolvedLookupExprClass:
2962  case UnresolvedMemberExprClass:
2963  case PackExpansionExprClass:
2964  case SubstNonTypeTemplateParmPackExprClass:
2965  case FunctionParmPackExprClass:
2966  case TypoExprClass:
2967  case CXXFoldExprClass:
2968  llvm_unreachable("shouldn't see dependent / unresolved nodes here");
2969 
2970  case DeclRefExprClass:
2971  case ObjCIvarRefExprClass:
2972  case PredefinedExprClass:
2973  case IntegerLiteralClass:
2974  case FloatingLiteralClass:
2975  case ImaginaryLiteralClass:
2976  case StringLiteralClass:
2977  case CharacterLiteralClass:
2978  case OffsetOfExprClass:
2979  case ImplicitValueInitExprClass:
2980  case UnaryExprOrTypeTraitExprClass:
2981  case AddrLabelExprClass:
2982  case GNUNullExprClass:
2983  case ArrayInitIndexExprClass:
2984  case NoInitExprClass:
2985  case CXXBoolLiteralExprClass:
2986  case CXXNullPtrLiteralExprClass:
2987  case CXXThisExprClass:
2988  case CXXScalarValueInitExprClass:
2989  case TypeTraitExprClass:
2990  case ArrayTypeTraitExprClass:
2991  case ExpressionTraitExprClass:
2992  case CXXNoexceptExprClass:
2993  case SizeOfPackExprClass:
2994  case ObjCStringLiteralClass:
2995  case ObjCEncodeExprClass:
2996  case ObjCBoolLiteralExprClass:
2997  case ObjCAvailabilityCheckExprClass:
2998  case CXXUuidofExprClass:
2999  case OpaqueValueExprClass:
3000  // These never have a side-effect.
3001  return false;
3002 
3003  case CallExprClass:
3004  case CXXOperatorCallExprClass:
3005  case CXXMemberCallExprClass:
3006  case CUDAKernelCallExprClass:
3007  case UserDefinedLiteralClass: {
3008  // We don't know a call definitely has side effects, except for calls
3009  // to pure/const functions that definitely don't.
3010  // If the call itself is considered side-effect free, check the operands.
3011  const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3012  bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3013  if (IsPure || !IncludePossibleEffects)
3014  break;
3015  return true;
3016  }
3017 
3018  case BlockExprClass:
3019  case CXXBindTemporaryExprClass:
3020  if (!IncludePossibleEffects)
3021  break;
3022  return true;
3023 
3024  case MSPropertyRefExprClass:
3025  case MSPropertySubscriptExprClass:
3026  case CompoundAssignOperatorClass:
3027  case VAArgExprClass:
3028  case AtomicExprClass:
3029  case CXXThrowExprClass:
3030  case CXXNewExprClass:
3031  case CXXDeleteExprClass:
3032  case CoawaitExprClass:
3033  case DependentCoawaitExprClass:
3034  case CoyieldExprClass:
3035  // These always have a side-effect.
3036  return true;
3037 
3038  case StmtExprClass: {
3039  // StmtExprs have a side-effect if any substatement does.
3040  SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3041  Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3042  return Finder.hasSideEffects();
3043  }
3044 
3045  case ExprWithCleanupsClass:
3046  if (IncludePossibleEffects)
3047  if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3048  return true;
3049  break;
3050 
3051  case ParenExprClass:
3052  case ArraySubscriptExprClass:
3053  case OMPArraySectionExprClass:
3054  case MemberExprClass:
3055  case ConditionalOperatorClass:
3056  case BinaryConditionalOperatorClass:
3057  case CompoundLiteralExprClass:
3058  case ExtVectorElementExprClass:
3059  case DesignatedInitExprClass:
3060  case DesignatedInitUpdateExprClass:
3061  case ArrayInitLoopExprClass:
3062  case ParenListExprClass:
3063  case CXXPseudoDestructorExprClass:
3064  case CXXStdInitializerListExprClass:
3065  case SubstNonTypeTemplateParmExprClass:
3066  case MaterializeTemporaryExprClass:
3067  case ShuffleVectorExprClass:
3068  case ConvertVectorExprClass:
3069  case AsTypeExprClass:
3070  // These have a side-effect if any subexpression does.
3071  break;
3072 
3073  case UnaryOperatorClass:
3074  if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3075  return true;
3076  break;
3077 
3078  case BinaryOperatorClass:
3079  if (cast<BinaryOperator>(this)->isAssignmentOp())
3080  return true;
3081  break;
3082 
3083  case InitListExprClass:
3084  // FIXME: The children for an InitListExpr doesn't include the array filler.
3085  if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3086  if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3087  return true;
3088  break;
3089 
3090  case GenericSelectionExprClass:
3091  return cast<GenericSelectionExpr>(this)->getResultExpr()->
3092  HasSideEffects(Ctx, IncludePossibleEffects);
3093 
3094  case ChooseExprClass:
3095  return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3096  Ctx, IncludePossibleEffects);
3097 
3098  case CXXDefaultArgExprClass:
3099  return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3100  Ctx, IncludePossibleEffects);
3101 
3102  case CXXDefaultInitExprClass: {
3103  const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3104  if (const Expr *E = FD->getInClassInitializer())
3105  return E->HasSideEffects(Ctx, IncludePossibleEffects);
3106  // If we've not yet parsed the initializer, assume it has side-effects.
3107  return true;
3108  }
3109 
3110  case CXXDynamicCastExprClass: {
3111  // A dynamic_cast expression has side-effects if it can throw.
3112  const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3113  if (DCE->getTypeAsWritten()->isReferenceType() &&
3114  DCE->getCastKind() == CK_Dynamic)
3115  return true;
3116  } // Fall through.
3117  case ImplicitCastExprClass:
3118  case CStyleCastExprClass:
3119  case CXXStaticCastExprClass:
3120  case CXXReinterpretCastExprClass:
3121  case CXXConstCastExprClass:
3122  case CXXFunctionalCastExprClass: {
3123  // While volatile reads are side-effecting in both C and C++, we treat them
3124  // as having possible (not definite) side-effects. This allows idiomatic
3125  // code to behave without warning, such as sizeof(*v) for a volatile-
3126  // qualified pointer.
3127  if (!IncludePossibleEffects)
3128  break;
3129 
3130  const CastExpr *CE = cast<CastExpr>(this);
3131  if (CE->getCastKind() == CK_LValueToRValue &&
3133  return true;
3134  break;
3135  }
3136 
3137  case CXXTypeidExprClass:
3138  // typeid might throw if its subexpression is potentially-evaluated, so has
3139  // side-effects in that case whether or not its subexpression does.
3140  return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3141 
3142  case CXXConstructExprClass:
3143  case CXXTemporaryObjectExprClass: {
3144  const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3145  if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3146  return true;
3147  // A trivial constructor does not add any side-effects of its own. Just look
3148  // at its arguments.
3149  break;
3150  }
3151 
3152  case CXXInheritedCtorInitExprClass: {
3153  const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3154  if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3155  return true;
3156  break;
3157  }
3158 
3159  case LambdaExprClass: {
3160  const LambdaExpr *LE = cast<LambdaExpr>(this);
3162  E = LE->capture_end(); I != E; ++I)
3163  if (I->getCaptureKind() == LCK_ByCopy)
3164  // FIXME: Only has a side-effect if the variable is volatile or if
3165  // the copy would invoke a non-trivial copy constructor.
3166  return true;
3167  return false;
3168  }
3169 
3170  case PseudoObjectExprClass: {
3171  // Only look for side-effects in the semantic form, and look past
3172  // OpaqueValueExpr bindings in that form.
3173  const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3175  E = PO->semantics_end();
3176  I != E; ++I) {
3177  const Expr *Subexpr = *I;
3178  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3179  Subexpr = OVE->getSourceExpr();
3180  if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3181  return true;
3182  }
3183  return false;
3184  }
3185 
3186  case ObjCBoxedExprClass:
3187  case ObjCArrayLiteralClass:
3188  case ObjCDictionaryLiteralClass:
3189  case ObjCSelectorExprClass:
3190  case ObjCProtocolExprClass:
3191  case ObjCIsaExprClass:
3192  case ObjCIndirectCopyRestoreExprClass:
3193  case ObjCSubscriptRefExprClass:
3194  case ObjCBridgedCastExprClass:
3195  case ObjCMessageExprClass:
3196  case ObjCPropertyRefExprClass:
3197  // FIXME: Classify these cases better.
3198  if (IncludePossibleEffects)
3199  return true;
3200  break;
3201  }
3202 
3203  // Recurse to children.
3204  for (const Stmt *SubStmt : children())
3205  if (SubStmt &&
3206  cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3207  return true;
3208 
3209  return false;
3210 }
3211 
3212 namespace {
3213  /// \brief Look for a call to a non-trivial function within an expression.
3214  class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3215  {
3217 
3218  bool NonTrivial;
3219 
3220  public:
3221  explicit NonTrivialCallFinder(const ASTContext &Context)
3222  : Inherited(Context), NonTrivial(false) { }
3223 
3224  bool hasNonTrivialCall() const { return NonTrivial; }
3225 
3226  void VisitCallExpr(const CallExpr *E) {
3227  if (const CXXMethodDecl *Method
3228  = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3229  if (Method->isTrivial()) {
3230  // Recurse to children of the call.
3231  Inherited::VisitStmt(E);
3232  return;
3233  }
3234  }
3235 
3236  NonTrivial = true;
3237  }
3238 
3239  void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3240  if (E->getConstructor()->isTrivial()) {
3241  // Recurse to children of the call.
3242  Inherited::VisitStmt(E);
3243  return;
3244  }
3245 
3246  NonTrivial = true;
3247  }
3248 
3249  void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3250  if (E->getTemporary()->getDestructor()->isTrivial()) {
3251  Inherited::VisitStmt(E);
3252  return;
3253  }
3254 
3255  NonTrivial = true;
3256  }
3257  };
3258 }
3259 
3260 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3261  NonTrivialCallFinder Finder(Ctx);
3262  Finder.Visit(this);
3263  return Finder.hasNonTrivialCall();
3264 }
3265 
3266 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3267 /// pointer constant or not, as well as the specific kind of constant detected.
3268 /// Null pointer constants can be integer constant expressions with the
3269 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3270 /// (a GNU extension).
3274  if (isValueDependent() &&
3275  (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3276  switch (NPC) {
3278  llvm_unreachable("Unexpected value dependent expression!");
3280  if (isTypeDependent() || getType()->isIntegralType(Ctx))
3281  return NPCK_ZeroExpression;
3282  else
3283  return NPCK_NotNull;
3284 
3286  return NPCK_NotNull;
3287  }
3288  }
3289 
3290  // Strip off a cast to void*, if it exists. Except in C++.
3291  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3292  if (!Ctx.getLangOpts().CPlusPlus) {
3293  // Check that it is a cast to void*.
3294  if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3295  QualType Pointee = PT->getPointeeType();
3296  // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3297  // has non-default address space it is not treated as nullptr.
3298  // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3299  // since it cannot be assigned to a pointer to constant address space.
3300  bool PointeeHasDefaultAS =
3301  Pointee.getAddressSpace() == LangAS::Default ||
3302  (Ctx.getLangOpts().OpenCLVersion >= 200 &&
3303  Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3304  (Ctx.getLangOpts().OpenCL &&
3305  Ctx.getLangOpts().OpenCLVersion < 200 &&
3307 
3308  if (PointeeHasDefaultAS && Pointee->isVoidType() && // to void*
3309  CE->getSubExpr()->getType()->isIntegerType()) // from int.
3310  return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3311  }
3312  }
3313  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3314  // Ignore the ImplicitCastExpr type entirely.
3315  return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3316  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3317  // Accept ((void*)0) as a null pointer constant, as many other
3318  // implementations do.
3319  return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3320  } else if (const GenericSelectionExpr *GE =
3321  dyn_cast<GenericSelectionExpr>(this)) {
3322  if (GE->isResultDependent())
3323  return NPCK_NotNull;
3324  return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3325  } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3326  if (CE->isConditionDependent())
3327  return NPCK_NotNull;
3328  return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3329  } else if (const CXXDefaultArgExpr *DefaultArg
3330  = dyn_cast<CXXDefaultArgExpr>(this)) {
3331  // See through default argument expressions.
3332  return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3333  } else if (const CXXDefaultInitExpr *DefaultInit
3334  = dyn_cast<CXXDefaultInitExpr>(this)) {
3335  // See through default initializer expressions.
3336  return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3337  } else if (isa<GNUNullExpr>(this)) {
3338  // The GNU __null extension is always a null pointer constant.
3339  return NPCK_GNUNull;
3340  } else if (const MaterializeTemporaryExpr *M
3341  = dyn_cast<MaterializeTemporaryExpr>(this)) {
3342  return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
3343  } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3344  if (const Expr *Source = OVE->getSourceExpr())
3345  return Source->isNullPointerConstant(Ctx, NPC);
3346  }
3347 
3348  // C++11 nullptr_t is always a null pointer constant.
3349  if (getType()->isNullPtrType())
3350  return NPCK_CXX11_nullptr;
3351 
3352  if (const RecordType *UT = getType()->getAsUnionType())
3353  if (!Ctx.getLangOpts().CPlusPlus11 &&
3354  UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3355  if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3356  const Expr *InitExpr = CLE->getInitializer();
3357  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3358  return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3359  }
3360  // This expression must be an integer type.
3361  if (!getType()->isIntegerType() ||
3362  (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3363  return NPCK_NotNull;
3364 
3365  if (Ctx.getLangOpts().CPlusPlus11) {
3366  // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3367  // value zero or a prvalue of type std::nullptr_t.
3368  // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3369  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3370  if (Lit && !Lit->getValue())
3371  return NPCK_ZeroLiteral;
3372  else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3373  return NPCK_NotNull;
3374  } else {
3375  // If we have an integer constant expression, we need to *evaluate* it and
3376  // test for the value 0.
3377  if (!isIntegerConstantExpr(Ctx))
3378  return NPCK_NotNull;
3379  }
3380 
3381  if (EvaluateKnownConstInt(Ctx) != 0)
3382  return NPCK_NotNull;
3383 
3384  if (isa<IntegerLiteral>(this))
3385  return NPCK_ZeroLiteral;
3386  return NPCK_ZeroExpression;
3387 }
3388 
3389 /// \brief If this expression is an l-value for an Objective C
3390 /// property, find the underlying property reference expression.
3392  const Expr *E = this;
3393  while (true) {
3394  assert((E->getValueKind() == VK_LValue &&
3395  E->getObjectKind() == OK_ObjCProperty) &&
3396  "expression is not a property reference");
3397  E = E->IgnoreParenCasts();
3398  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3399  if (BO->getOpcode() == BO_Comma) {
3400  E = BO->getRHS();
3401  continue;
3402  }
3403  }
3404 
3405  break;
3406  }
3407 
3408  return cast<ObjCPropertyRefExpr>(E);
3409 }
3410 
3411 bool Expr::isObjCSelfExpr() const {
3412  const Expr *E = IgnoreParenImpCasts();
3413 
3414  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3415  if (!DRE)
3416  return false;
3417 
3418  const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3419  if (!Param)
3420  return false;
3421 
3422  const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3423  if (!M)
3424  return false;
3425 
3426  return M->getSelfDecl() == Param;
3427 }
3428 
3430  Expr *E = this->IgnoreParens();
3431 
3432  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3433  if (ICE->getCastKind() == CK_LValueToRValue ||
3434  (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
3435  E = ICE->getSubExpr()->IgnoreParens();
3436  else
3437  break;
3438  }
3439 
3440  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3441  if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3442  if (Field->isBitField())
3443  return Field;
3444 
3445  if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E))
3446  if (FieldDecl *Ivar = dyn_cast<FieldDecl>(IvarRef->getDecl()))
3447  if (Ivar->isBitField())
3448  return Ivar;
3449 
3450  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3451  if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3452  if (Field->isBitField())
3453  return Field;
3454 
3455  if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3456  if (Expr *E = BD->getBinding())
3457  return E->getSourceBitField();
3458  }
3459 
3460  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3461  if (BinOp->isAssignmentOp() && BinOp->getLHS())
3462  return BinOp->getLHS()->getSourceBitField();
3463 
3464  if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3465  return BinOp->getRHS()->getSourceBitField();
3466  }
3467 
3468  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3469  if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3470  return UnOp->getSubExpr()->getSourceBitField();
3471 
3472  return nullptr;
3473 }
3474 
3476  // FIXME: Why do we not just look at the ObjectKind here?
3477  const Expr *E = this->IgnoreParens();
3478 
3479  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3480  if (ICE->getValueKind() != VK_RValue &&
3481  ICE->getCastKind() == CK_NoOp)
3482  E = ICE->getSubExpr()->IgnoreParens();
3483  else
3484  break;
3485  }
3486 
3487  if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3488  return ASE->getBase()->getType()->isVectorType();
3489 
3490  if (isa<ExtVectorElementExpr>(E))
3491  return true;
3492 
3493  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3494  if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3495  if (auto *E = BD->getBinding())
3496  return E->refersToVectorElement();
3497 
3498  return false;
3499 }
3500 
3502  const Expr *E = this->IgnoreParenImpCasts();
3503 
3504  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3505  if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3506  if (VD->getStorageClass() == SC_Register &&
3507  VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3508  return true;
3509 
3510  return false;
3511 }
3512 
3513 /// isArrow - Return true if the base expression is a pointer to vector,
3514 /// return false if the base expression is a vector.
3516  return getBase()->getType()->isPointerType();
3517 }
3518 
3520  if (const VectorType *VT = getType()->getAs<VectorType>())
3521  return VT->getNumElements();
3522  return 1;
3523 }
3524 
3525 /// containsDuplicateElements - Return true if any element access is repeated.
3527  // FIXME: Refactor this code to an accessor on the AST node which returns the
3528  // "type" of component access, and share with code below and in Sema.
3529  StringRef Comp = Accessor->getName();
3530 
3531  // Halving swizzles do not contain duplicate elements.
3532  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
3533  return false;
3534 
3535  // Advance past s-char prefix on hex swizzles.
3536  if (Comp[0] == 's' || Comp[0] == 'S')
3537  Comp = Comp.substr(1);
3538 
3539  for (unsigned i = 0, e = Comp.size(); i != e; ++i)
3540  if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
3541  return true;
3542 
3543  return false;
3544 }
3545 
3546 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
3548  SmallVectorImpl<uint32_t> &Elts) const {
3549  StringRef Comp = Accessor->getName();
3550  bool isNumericAccessor = false;
3551  if (Comp[0] == 's' || Comp[0] == 'S') {
3552  Comp = Comp.substr(1);
3553  isNumericAccessor = true;
3554  }
3555 
3556  bool isHi = Comp == "hi";
3557  bool isLo = Comp == "lo";
3558  bool isEven = Comp == "even";
3559  bool isOdd = Comp == "odd";
3560 
3561  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3562  uint64_t Index;
3563 
3564  if (isHi)
3565  Index = e + i;
3566  else if (isLo)
3567  Index = i;
3568  else if (isEven)
3569  Index = 2 * i;
3570  else if (isOdd)
3571  Index = 2 * i + 1;
3572  else
3573  Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
3574 
3575  Elts.push_back(Index);
3576  }
3577 }
3578 
3580  QualType Type, SourceLocation BLoc,
3581  SourceLocation RP)
3582  : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3583  Type->isDependentType(), Type->isDependentType(),
3584  Type->isInstantiationDependentType(),
3586  BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3587 {
3588  SubExprs = new (C) Stmt*[args.size()];
3589  for (unsigned i = 0; i != args.size(); i++) {
3590  if (args[i]->isTypeDependent())
3591  ExprBits.TypeDependent = true;
3592  if (args[i]->isValueDependent())
3593  ExprBits.ValueDependent = true;
3594  if (args[i]->isInstantiationDependent())
3595  ExprBits.InstantiationDependent = true;
3596  if (args[i]->containsUnexpandedParameterPack())
3597  ExprBits.ContainsUnexpandedParameterPack = true;
3598 
3599  SubExprs[i] = args[i];
3600  }
3601 }
3602 
3604  if (SubExprs) C.Deallocate(SubExprs);
3605 
3606  this->NumExprs = Exprs.size();
3607  SubExprs = new (C) Stmt*[NumExprs];
3608  memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
3609 }
3610 
3612  SourceLocation GenericLoc, Expr *ControllingExpr,
3613  ArrayRef<TypeSourceInfo*> AssocTypes,
3614  ArrayRef<Expr*> AssocExprs,
3615  SourceLocation DefaultLoc,
3616  SourceLocation RParenLoc,
3617  bool ContainsUnexpandedParameterPack,
3618  unsigned ResultIndex)
3619  : Expr(GenericSelectionExprClass,
3620  AssocExprs[ResultIndex]->getType(),
3621  AssocExprs[ResultIndex]->getValueKind(),
3622  AssocExprs[ResultIndex]->getObjectKind(),
3623  AssocExprs[ResultIndex]->isTypeDependent(),
3624  AssocExprs[ResultIndex]->isValueDependent(),
3625  AssocExprs[ResultIndex]->isInstantiationDependent(),
3626  ContainsUnexpandedParameterPack),
3627  AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3628  SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3629  NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3630  GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3631  SubExprs[CONTROLLING] = ControllingExpr;
3632  assert(AssocTypes.size() == AssocExprs.size());
3633  std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3634  std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
3635 }
3636 
3638  SourceLocation GenericLoc, Expr *ControllingExpr,
3639  ArrayRef<TypeSourceInfo*> AssocTypes,
3640  ArrayRef<Expr*> AssocExprs,
3641  SourceLocation DefaultLoc,
3642  SourceLocation RParenLoc,
3643  bool ContainsUnexpandedParameterPack)
3644  : Expr(GenericSelectionExprClass,
3645  Context.DependentTy,
3646  VK_RValue,
3647  OK_Ordinary,
3648  /*isTypeDependent=*/true,
3649  /*isValueDependent=*/true,
3650  /*isInstantiationDependent=*/true,
3651  ContainsUnexpandedParameterPack),
3652  AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3653  SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3654  NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3655  DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3656  SubExprs[CONTROLLING] = ControllingExpr;
3657  assert(AssocTypes.size() == AssocExprs.size());
3658  std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3659  std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
3660 }
3661 
3662 //===----------------------------------------------------------------------===//
3663 // DesignatedInitExpr
3664 //===----------------------------------------------------------------------===//
3665 
3667  assert(Kind == FieldDesignator && "Only valid on a field designator");
3668  if (Field.NameOrField & 0x01)
3669  return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3670  else
3671  return getField()->getIdentifier();
3672 }
3673 
3674 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
3675  llvm::ArrayRef<Designator> Designators,
3676  SourceLocation EqualOrColonLoc,
3677  bool GNUSyntax,
3678  ArrayRef<Expr*> IndexExprs,
3679  Expr *Init)
3680  : Expr(DesignatedInitExprClass, Ty,
3681  Init->getValueKind(), Init->getObjectKind(),
3682  Init->isTypeDependent(), Init->isValueDependent(),
3683  Init->isInstantiationDependent(),
3685  EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
3686  NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
3687  this->Designators = new (C) Designator[NumDesignators];
3688 
3689  // Record the initializer itself.
3690  child_iterator Child = child_begin();
3691  *Child++ = Init;
3692 
3693  // Copy the designators and their subexpressions, computing
3694  // value-dependence along the way.
3695  unsigned IndexIdx = 0;
3696  for (unsigned I = 0; I != NumDesignators; ++I) {
3697  this->Designators[I] = Designators[I];
3698 
3699  if (this->Designators[I].isArrayDesignator()) {
3700  // Compute type- and value-dependence.
3701  Expr *Index = IndexExprs[IndexIdx];
3702  if (Index->isTypeDependent() || Index->isValueDependent())
3703  ExprBits.TypeDependent = ExprBits.ValueDependent = true;
3704  if (Index->isInstantiationDependent())
3705  ExprBits.InstantiationDependent = true;
3706  // Propagate unexpanded parameter packs.
3708  ExprBits.ContainsUnexpandedParameterPack = true;
3709 
3710  // Copy the index expressions into permanent storage.
3711  *Child++ = IndexExprs[IndexIdx++];
3712  } else if (this->Designators[I].isArrayRangeDesignator()) {
3713  // Compute type- and value-dependence.
3714  Expr *Start = IndexExprs[IndexIdx];
3715  Expr *End = IndexExprs[IndexIdx + 1];
3716  if (Start->isTypeDependent() || Start->isValueDependent() ||
3717  End->isTypeDependent() || End->isValueDependent()) {
3718  ExprBits.TypeDependent = ExprBits.ValueDependent = true;
3719  ExprBits.InstantiationDependent = true;
3720  } else if (Start->isInstantiationDependent() ||
3721  End->isInstantiationDependent()) {
3722  ExprBits.InstantiationDependent = true;
3723  }
3724 
3725  // Propagate unexpanded parameter packs.
3726  if (Start->containsUnexpandedParameterPack() ||
3728  ExprBits.ContainsUnexpandedParameterPack = true;
3729 
3730  // Copy the start/end expressions into permanent storage.
3731  *Child++ = IndexExprs[IndexIdx++];
3732  *Child++ = IndexExprs[IndexIdx++];
3733  }
3734  }
3735 
3736  assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
3737 }
3738 
3741  llvm::ArrayRef<Designator> Designators,
3742  ArrayRef<Expr*> IndexExprs,
3743  SourceLocation ColonOrEqualLoc,
3744  bool UsesColonSyntax, Expr *Init) {
3745  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
3746  alignof(DesignatedInitExpr));
3747  return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
3748  ColonOrEqualLoc, UsesColonSyntax,
3749  IndexExprs, Init);
3750 }
3751 
3753  unsigned NumIndexExprs) {
3754  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
3755  alignof(DesignatedInitExpr));
3756  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3757 }
3758 
3760  const Designator *Desigs,
3761  unsigned NumDesigs) {
3762  Designators = new (C) Designator[NumDesigs];
3763  NumDesignators = NumDesigs;
3764  for (unsigned I = 0; I != NumDesigs; ++I)
3765  Designators[I] = Desigs[I];
3766 }
3767 
3769  DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3770  if (size() == 1)
3771  return DIE->getDesignator(0)->getSourceRange();
3772  return SourceRange(DIE->getDesignator(0)->getLocStart(),
3773  DIE->getDesignator(size()-1)->getLocEnd());
3774 }
3775 
3777  SourceLocation StartLoc;
3778  auto *DIE = const_cast<DesignatedInitExpr *>(this);
3779  Designator &First = *DIE->getDesignator(0);
3780  if (First.isFieldDesignator()) {
3781  if (GNUSyntax)
3783  else
3785  } else
3786  StartLoc =
3788  return StartLoc;
3789 }
3790 
3792  return getInit()->getLocEnd();
3793 }
3794 
3796  assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
3797  return getSubExpr(D.ArrayOrRange.Index + 1);
3798 }
3799 
3801  assert(D.Kind == Designator::ArrayRangeDesignator &&
3802  "Requires array range designator");
3803  return getSubExpr(D.ArrayOrRange.Index + 1);
3804 }
3805 
3807  assert(D.Kind == Designator::ArrayRangeDesignator &&
3808  "Requires array range designator");
3809  return getSubExpr(D.ArrayOrRange.Index + 2);
3810 }
3811 
3812 /// \brief Replaces the designator at index @p Idx with the series
3813 /// of designators in [First, Last).
3815  const Designator *First,
3816  const Designator *Last) {
3817  unsigned NumNewDesignators = Last - First;
3818  if (NumNewDesignators == 0) {
3819  std::copy_backward(Designators + Idx + 1,
3820  Designators + NumDesignators,
3821  Designators + Idx);
3822  --NumNewDesignators;
3823  return;
3824  } else if (NumNewDesignators == 1) {
3825  Designators[Idx] = *First;
3826  return;
3827  }
3828 
3829  Designator *NewDesignators
3830  = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
3831  std::copy(Designators, Designators + Idx, NewDesignators);
3832  std::copy(First, Last, NewDesignators + Idx);
3833  std::copy(Designators + Idx + 1, Designators + NumDesignators,
3834  NewDesignators + Idx + NumNewDesignators);
3835  Designators = NewDesignators;
3836  NumDesignators = NumDesignators - 1 + NumNewDesignators;
3837 }
3838 
3840  SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3841  : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3843  BaseAndUpdaterExprs[0] = baseExpr;
3844 
3845  InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3846  ILE->setType(baseExpr->getType());
3847  BaseAndUpdaterExprs[1] = ILE;
3848 }
3849 
3851  return getBase()->getLocStart();
3852 }
3853 
3855  return getBase()->getLocEnd();
3856 }
3857 
3859  ArrayRef<Expr*> exprs,
3860  SourceLocation rparenloc)
3861  : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
3862  false, false, false, false),
3863  NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3864  Exprs = new (C) Stmt*[exprs.size()];
3865  for (unsigned i = 0; i != exprs.size(); ++i) {
3866  if (exprs[i]->isTypeDependent())
3867  ExprBits.TypeDependent = true;
3868  if (exprs[i]->isValueDependent())
3869  ExprBits.ValueDependent = true;
3870  if (exprs[i]->isInstantiationDependent())
3871  ExprBits.InstantiationDependent = true;
3872  if (exprs[i]->containsUnexpandedParameterPack())
3873  ExprBits.ContainsUnexpandedParameterPack = true;
3874 
3875  Exprs[i] = exprs[i];
3876  }
3877 }
3878 
3880  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3881  e = ewc->getSubExpr();
3882  if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3883  e = m->GetTemporaryExpr();
3884  e = cast<CXXConstructExpr>(e)->getArg(0);
3885  while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3886  e = ice->getSubExpr();
3887  return cast<OpaqueValueExpr>(e);
3888 }
3889 
3891  EmptyShell sh,
3892  unsigned numSemanticExprs) {
3893  void *buffer =
3894  Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
3895  alignof(PseudoObjectExpr));
3896  return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3897 }
3898 
3899 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3900  : Expr(PseudoObjectExprClass, shell) {
3901  PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3902 }
3903 
3905  ArrayRef<Expr*> semantics,
3906  unsigned resultIndex) {
3907  assert(syntax && "no syntactic expression!");
3908  assert(semantics.size() && "no semantic expressions!");
3909 
3910  QualType type;
3911  ExprValueKind VK;
3912  if (resultIndex == NoResult) {
3913  type = C.VoidTy;
3914  VK = VK_RValue;
3915  } else {
3916  assert(resultIndex < semantics.size());
3917  type = semantics[resultIndex]->getType();
3918  VK = semantics[resultIndex]->getValueKind();
3919  assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3920  }
3921 
3922  void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
3923  alignof(PseudoObjectExpr));
3924  return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3925  resultIndex);
3926 }
3927 
3928 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3929  Expr *syntax, ArrayRef<Expr*> semantics,
3930  unsigned resultIndex)
3931  : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3932  /*filled in at end of ctor*/ false, false, false, false) {
3933  PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3934  PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3935 
3936  for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3937  Expr *E = (i == 0 ? syntax : semantics[i-1]);
3938  getSubExprsBuffer()[i] = E;
3939 
3940  if (E->isTypeDependent())
3941  ExprBits.TypeDependent = true;
3942  if (E->isValueDependent())
3943  ExprBits.ValueDependent = true;
3945  ExprBits.InstantiationDependent = true;
3947  ExprBits.ContainsUnexpandedParameterPack = true;
3948 
3949  if (isa<OpaqueValueExpr>(E))
3950  assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
3951  "opaque-value semantic expressions for pseudo-object "
3952  "operations must have sources");
3953  }
3954 }
3955 
3956 //===----------------------------------------------------------------------===//
3957 // Child Iterators for iterating over subexpressions/substatements
3958 //===----------------------------------------------------------------------===//
3959 
3960 // UnaryExprOrTypeTraitExpr
3962  const_child_range CCR =
3963  const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
3964  return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
3965 }
3966 
3968  // If this is of a type and the type is a VLA type (and not a typedef), the
3969  // size expression of the VLA needs to be treated as an executable expression.
3970  // Why isn't this weirdness documented better in StmtIterator?
3971  if (isArgumentType()) {
3972  if (const VariableArrayType *T =
3973  dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
3976  }
3977  return const_child_range(&Argument.Ex, &Argument.Ex + 1);
3978 }
3979 
3981  QualType t, AtomicOp op, SourceLocation RP)
3982  : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3983  false, false, false, false),
3984  NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
3985 {
3986  assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
3987  for (unsigned i = 0; i != args.size(); i++) {
3988  if (args[i]->isTypeDependent())
3989  ExprBits.TypeDependent = true;
3990  if (args[i]->isValueDependent())
3991  ExprBits.ValueDependent = true;
3992  if (args[i]->isInstantiationDependent())
3993  ExprBits.InstantiationDependent = true;
3994  if (args[i]->containsUnexpandedParameterPack())
3995  ExprBits.ContainsUnexpandedParameterPack = true;
3996 
3997  SubExprs[i] = args[i];
3998  }
3999 }
4000 
4002  switch (Op) {
4003  case AO__c11_atomic_init:
4004  case AO__opencl_atomic_init:
4005  case AO__c11_atomic_load:
4006  case AO__atomic_load_n:
4007  return 2;
4008 
4009  case AO__opencl_atomic_load:
4010  case AO__c11_atomic_store:
4011  case AO__c11_atomic_exchange:
4012  case AO__atomic_load:
4013  case AO__atomic_store:
4014  case AO__atomic_store_n:
4015  case AO__atomic_exchange_n:
4016  case AO__c11_atomic_fetch_add:
4017  case AO__c11_atomic_fetch_sub:
4018  case AO__c11_atomic_fetch_and:
4019  case AO__c11_atomic_fetch_or:
4020  case AO__c11_atomic_fetch_xor:
4021  case AO__atomic_fetch_add:
4022  case AO__atomic_fetch_sub:
4023  case AO__atomic_fetch_and:
4024  case AO__atomic_fetch_or:
4025  case AO__atomic_fetch_xor:
4026  case AO__atomic_fetch_nand:
4027  case AO__atomic_add_fetch:
4028  case AO__atomic_sub_fetch:
4029  case AO__atomic_and_fetch:
4030  case AO__atomic_or_fetch:
4031  case AO__atomic_xor_fetch:
4032  case AO__atomic_nand_fetch:
4033  return 3;
4034 
4035  case AO__opencl_atomic_store:
4036  case AO__opencl_atomic_exchange:
4037  case AO__opencl_atomic_fetch_add:
4038  case AO__opencl_atomic_fetch_sub:
4039  case AO__opencl_atomic_fetch_and:
4040  case AO__opencl_atomic_fetch_or:
4041  case AO__opencl_atomic_fetch_xor:
4042  case AO__opencl_atomic_fetch_min:
4043  case AO__opencl_atomic_fetch_max:
4044  case AO__atomic_exchange:
4045  return 4;
4046 
4047  case AO__c11_atomic_compare_exchange_strong:
4048  case AO__c11_atomic_compare_exchange_weak:
4049  return 5;
4050 
4051  case AO__opencl_atomic_compare_exchange_strong:
4052  case AO__opencl_atomic_compare_exchange_weak:
4053  case AO__atomic_compare_exchange:
4054  case AO__atomic_compare_exchange_n:
4055  return 6;
4056  }
4057  llvm_unreachable("unknown atomic op");
4058 }
4059 
4061  auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4062  if (auto AT = T->getAs<AtomicType>())
4063  return AT->getValueType();
4064  return T;
4065 }
4066 
4068  unsigned ArraySectionCount = 0;
4069  while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4070  Base = OASE->getBase();
4071  ++ArraySectionCount;
4072  }
4073  while (auto *ASE =
4074  dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4075  Base = ASE->getBase();
4076  ++ArraySectionCount;
4077  }
4078  Base = Base->IgnoreParenImpCasts();
4079  auto OriginalTy = Base->getType();
4080  if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4081  if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4082  OriginalTy = PVD->getOriginalType().getNonReferenceType();
4083 
4084  for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4085  if (OriginalTy->isAnyPointerType())
4086  OriginalTy = OriginalTy->getPointeeType();
4087  else {
4088  assert (OriginalTy->isArrayType());
4089  OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4090  }
4091  }
4092  return OriginalTy;
4093 }
child_iterator child_begin()
Definition: Stmt.h:431
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:539
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:52
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:3977
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
Represents a single C99 designator.
Definition: Expr.h:4182
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setValueDependent(bool VD)
Set whether this expression is value-dependent or not.
Definition: Expr.h:152
Defines the clang::ASTContext interface.
static std::string ComputeName(IdentType IT, const Decl *CurrentDecl)
Definition: Expr.cpp:495
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1114
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1631
Expr * getArrayIndex(const Designator &D) const
Definition: Expr.cpp:3795
Stmt * body_back()
Definition: Stmt.h:609
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:537
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Definition: ASTMatchers.h:1538
static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, QualType T, bool &TypeDependent, bool &ValueDependent, bool &InstantiationDependent)
Compute the type-, value-, and instantiation-dependence of a declaration reference based on the decla...
Definition: Expr.cpp:236
Expr * getLHS() const
Definition: Expr.h:3315
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
Definition: Expr.h:5014
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:63
SourceLocation getRParenLoc() const
Definition: Expr.h:2345
void setArrayFiller(Expr *filler)
Definition: Expr.cpp:1907
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition: Expr.cpp:2003
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2222
QualType getPointeeType() const
Definition: Type.h:2236
A (possibly-)qualified type.
Definition: Type.h:614
unsigned getOffsetOfStringByte(const Token &TheTok, unsigned ByteNo) const
getOffsetOfStringByte - This function returns the offset of the specified byte of the string data rep...
bool isArrayType() const
Definition: Type.h:5805
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2278
static StringLiteral * CreateEmpty(const ASTContext &C, unsigned NumStrs)
Construct an empty string literal.
Definition: Expr.cpp:879
const DeclarationNameLoc & getInfo() const
capture_iterator capture_end() const
Retrieve an iterator pointing past the end of the sequence of lambda captures.
Definition: ExprCXX.cpp:960
Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK, bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
Definition: Expr.h:110
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
Definition: opencl-c.h:60
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:812
unsigned FieldLoc
The location of the field name in the designated initializer.
Definition: Expr.h:4159
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.h:4289
const Expr * getInit(unsigned Init) const
Definition: Expr.h:3921
Stmt - This represents one statement.
Definition: Stmt.h:60
DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, Expr *baseExprs, SourceLocation rBraceLoc)
Definition: Expr.cpp:3839
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2266
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2964
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition: Expr.cpp:1040
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:435
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:472
Defines the SourceManager interface.
bool hasNonTrivialCall(const ASTContext &Ctx) const
Determine whether this expression involves a call to any function that is not trivial.
Definition: Expr.cpp:3260
bool isRecordType() const
Definition: Type.h:5823
reverse_iterator rbegin()
Definition: ASTVector.h:98
Expr * getBase() const
Definition: Expr.h:2477
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:253
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:5950
void setSemantics(const llvm::fltSemantics &Sem)
Set the APFloat semantics this literal uses.
Definition: Expr.cpp:802
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:81
bool hasUnusedResultAttr() const
Returns true if this function or its return type has the warn_unused_result attribute.
Definition: Decl.h:2148
FloatingLiteralBitfields FloatingLiteralBits
Definition: Stmt.h:270
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition: Expr.cpp:3547
void setType(QualType t)
Definition: Expr.h:129
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic, and whose semantics are that of the sole contained initializer)?
Definition: Expr.cpp:1931
Defines the C++ template declaration subclasses.
Opcode getOpcode() const
Definition: Expr.h:3027
StringRef P
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:377
iterator insert(const ASTContext &C, iterator I, const T &Elt)
Definition: ASTVector.h:216
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1665
NamedDecl * getDecl() const
The base class of the type hierarchy.
Definition: Type.h:1300
bool isSemanticForm() const
Definition: Expr.h:4023
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2495
DeclRefExprBitfields DeclRefExprBits
Definition: Stmt.h:272
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1177
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:112
SourceLocation getLParenLoc() const
Definition: Expr.h:2949
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:645
A container of type source information.
Definition: Decl.h:62
bool containsDuplicateElements() const
containsDuplicateElements - Return true if any element access is repeated.
Definition: Expr.cpp:3526
static StringLiteral * Create(const ASTContext &C, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumStrs)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:854
CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef< Expr *> preargs, ArrayRef< Expr *> args, QualType t, ExprValueKind VK, SourceLocation rparenloc)
Definition: Expr.cpp:1160
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:26
unsigned getCharWidth() const
Definition: TargetInfo.h:333
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2344
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:3951
Expr * ignoreParenBaseCasts() LLVM_READONLY
Ignore parentheses and derived-to-base casts.
Definition: Expr.cpp:2532
QualType getElementType() const
Definition: Type.h:2529
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
bool EvaluateAsInt(llvm::APSInt &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...
static OffsetOfExpr * CreateEmpty(const ASTContext &C, unsigned NumComps, unsigned NumExprs)
Definition: Expr.cpp:1358
static const OpaqueValueExpr * findInCopyConstruct(const Expr *expr)
Given an expression which invokes a copy constructor — i.e.
Definition: Expr.cpp:3879
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:771
const ObjCPropertyRefExpr * getObjCProperty() const
If this expression is an l-value for an Objective C property, find the underlying property reference ...
Definition: Expr.cpp:3391
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2637
bool isEnumeralType() const
Definition: Type.h:5826
QualType getCXXNameType() const
getCXXNameType - If this name is one of the C++ names (of a constructor, destructor, or conversion function), return the type associated with that name.
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6099
MangleContext * createMangleContext()
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type...
Definition: Type.h:6171
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition: Expr.cpp:1891
void setInit(unsigned Init, Expr *expr)
Definition: Expr.h:3931
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:113
PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT, StringLiteral *SL)
Definition: Expr.cpp:461
size_type size() const
Definition: ASTVector.h:104
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition: Expr.cpp:1954
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:50
static DeclRefExpr * CreateEmpty(const ASTContext &Context, bool HasQualifier, bool HasFoundDecl, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs)
Construct an empty declaration reference expression.
Definition: Expr.cpp:435
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Definition: ExprCXX.h:2920
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3109
Defines the clang::Expr interface and subclasses for C++ expressions.
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:3429
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
LabelStmt - Represents a label, which has a substatement.
Definition: Stmt.h:813
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3384
Represents a C99 designated initializer expression.
Definition: Expr.h:4107
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
One of these records is kept for each identifier that is lexed.
Represents a class template specialization, which refers to a class template with a given set of temp...
unsigned GetStringLength() const
const Expr * getBestDynamicClassTypeExpr() const
Get the inner expression that determines the best dynamic class.
Definition: Expr.cpp:38
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:238
StmtIterator cast_away_const(const ConstStmtIterator &RHS)
Definition: StmtIterator.h:155
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
A C++ nested-name-specifier augmented with source location information.
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
unsigned getChar32Width() const
getChar32Width/Align - Return the size of &#39;char32_t&#39; for this target, in bits.
Definition: TargetInfo.h:400
bool isCharType() const
Definition: Type.cpp:1715
field_range fields() const
Definition: Decl.h:3513
static SourceLocation getFromRawEncoding(unsigned Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2382
void setNumArgs(const ASTContext &C, unsigned NumArgs)
setNumArgs - This changes the number of arguments present in this call.
Definition: Expr.cpp:1251
static DesignatedInitExpr * Create(const ASTContext &C, llvm::ArrayRef< Designator > Designators, ArrayRef< Expr *> IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition: Expr.cpp:3740
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:95
bool isReferenceType() const
Definition: Type.h:5775
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
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:391
Expr * getSubExpr()
Definition: Expr.h:2762
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition: Expr.cpp:3515
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6013
NestedNameSpecifierLoc QualifierLoc
The nested-name-specifier that qualifies the name, including source-location information.
Definition: Expr.h:2378
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:107
struct FieldDesignator Field
A field designator, e.g., ".x".
Definition: Expr.h:4192
const Expr *const * const_semantics_iterator
Definition: Expr.h:5037
ShuffleVectorExpr(const ASTContext &C, ArrayRef< Expr *> args, QualType Type, SourceLocation BLoc, SourceLocation RP)
Definition: Expr.cpp:3579
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:494
StringRef getOpcodeStr() const
Definition: Expr.h:3046
bool isGLValue() const
Definition: Expr.h:252
Describes an C or C++ initializer list.
Definition: Expr.h:3873
const TemplateArgumentList * TemplateArguments
The template arguments used to produce the function template specialization from the function templat...
Definition: DeclTemplate.h:527
void setValue(const ASTContext &C, const llvm::APInt &Val)
Definition: Expr.h:1280
BinaryOperatorKind
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1259
Base object ctor.
Definition: ABI.h:27
< Capturing the *this object by copy
Definition: Lambda.h:37
A convenient class for passing around template argument information.
Definition: TemplateBase.h:524
uint32_t Offset
Definition: CacheTokens.cpp:43
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
Expr * getPtr() const
Definition: Expr.h:5136
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:6148
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
NullPointerConstantValueDependence
Enumeration used to describe how isNullPointerConstant() should cope with value-dependent expressions...
Definition: Expr.h:696
unsigned getNumPreArgs() const
Definition: Expr.h:2240
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1572
static bool isRecordType(QualType T)
semantics_iterator semantics_end()
Definition: Expr.h:5044
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2986
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5613
child_range children()
Definition: Expr.h:4056
bool isBoundMemberFunction(ASTContext &Ctx) const
Returns true if this expression is a bound member function.
Definition: Expr.cpp:2401
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2462
const char * getCastKindName() const
Definition: Expr.cpp:1636
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
Definition: Type.h:965
field_iterator field_begin() const
Definition: Decl.cpp:3904
SourceLocation getCaretLocation() const
Definition: Expr.cpp:2009
static bool isBooleanType(QualType Ty)
An adjustment to be made to the temporary created when emitting a reference binding, which accesses a particular subobject of that temporary.
Definition: Expr.h:60
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2710
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition: ASTVector.h:83
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1134
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1154
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1519
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1361
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:748
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
An ordinary object is located at an address in memory.
Definition: Specifiers.h:123
This represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:3756
Represents an ObjC class declaration.
Definition: DeclObjC.h:1108
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:1748
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Character, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token...
Definition: Lexer.cpp:694
Expression is a GNU-style __null constant.
Definition: Expr.h:691
StmtClass
Definition: Stmt.h:62
const Stmt * getBody() const
Definition: Expr.cpp:2012
A binding in a decomposition declaration.
Definition: DeclCXX.h:3645
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
bool isUnevaluated(unsigned ID) const
Returns true if this builtin does not perform the side-effects of its arguments.
Definition: Builtins.h:128
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:982
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix)
Retrieve the unary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:1125
void setIntValue(const ASTContext &C, const llvm::APInt &Val)
Definition: Expr.cpp:719
bool isObjCSelfExpr() const
Check if this expression is the ObjC &#39;self&#39; implicit parameter.
Definition: Expr.cpp:3411
ParenListExpr(const ASTContext &C, SourceLocation lparenloc, ArrayRef< Expr *> exprs, SourceLocation rparenloc)
Definition: Expr.cpp:3858
Represents the this expression in C++.
Definition: ExprCXX.h:888
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, Expr *LHS, Expr *RHS)
Definition: Expr.cpp:1832
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:616
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:2912
bool isInstantiationDependent() const
Whether this nested name specifier involves a template parameter.
void print(const PrintingPolicy &Policy, raw_ostream &Out) const
Print this template argument to the given output stream.
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition: Expr.cpp:1301
bool hasAttr() const
Definition: DeclBase.h:521
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3270
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:575
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1569
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3170
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
Expr * IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY
IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the value (including ptr->int ...
Definition: Expr.cpp:2582
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1240
CastKind
CastKind - The kind of operation required for a conversion.
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Stmt.cpp:270
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1718
Specifies that the expression should never be value-dependent.
Definition: Expr.h:698
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:2031
iterator end()
Definition: ASTVector.h:94
InitListExpr * getUpdater() const
Definition: Expr.h:4459
void outputString(raw_ostream &OS) const
Definition: Expr.cpp:891
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
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:2939
Exposes information about the current target.
Definition: TargetInfo.h:55
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:133
void setString(const ASTContext &C, StringRef Str, StringKind Kind, bool IsPascal)
Sets the string data to the given string data.
Definition: Expr.cpp:987
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:410
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:4283
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:593
Expr - This represents one expression.
Definition: Expr.h:106
void setDesignators(const ASTContext &C, const Designator *Desigs, unsigned NumDesigs)
Definition: Expr.cpp:3759
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:3776
SourceLocation End
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:104
std::string Label
IdentifierInfo * getFieldName() const
For a field or identifier offsetof node, returns the name of the field.
Definition: Expr.cpp:1391
const FunctionProtoType * T
ConstStmtIterator const_child_iterator
Definition: Stmt.h:420
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6162
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:455
void setTypeDependent(bool TD)
Set whether this expression is type-dependent or not.
Definition: Expr.h:170
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2566
unsigned getNumInits() const
Definition: Expr.h:3903
const Expr * getCallee() const
Definition: Expr.h:2249
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:1983
const Expr * skipRValueSubobjectAdjustments() const
Definition: Expr.h:847
field_iterator field_end() const
Definition: Decl.h:3516
child_range children()
Definition: Expr.h:4648
DeclContext * getDeclContext()
Definition: DeclBase.h:416
ExprBitfields ExprBits
Definition: Stmt.h:268
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode. ...
Definition: Expr.cpp:1140
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:774
Represents the type decltype(expr) (C++11).
Definition: Type.h:3722
ArrayRef< Expr * > inits()
Definition: Expr.h:3913
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:702
Extra data stored in some MemberExpr objects.
Definition: Expr.h:2375
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type...
Definition: Expr.cpp:2656
Base object dtor.
Definition: ABI.h:37
QualType getType() const
Definition: Expr.h:128
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1303
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:860
InitListExpr(const ASTContext &C, SourceLocation lbraceloc, ArrayRef< Expr *> initExprs, SourceLocation rbraceloc)
Definition: Expr.cpp:1864
Expr * getSubExprAsWritten()
Retrieve the cast subexpression as it was written in the source code, looking through any implicit ca...
Definition: Expr.cpp:1659
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:1717
unsigned Index
Location of the first index expression within the designated initializer expression&#39;s list of subexpr...
Definition: Expr.h:4166
Represents a GCC generic vector type.
Definition: Type.h:2838
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3756
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1008
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition: Expr.h:596
ValueDecl * getDecl()
Definition: Expr.h:1041
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:1309
The result type of a method or function.
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:1922
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr.cast]), which uses the syntax (Type)expr.
Definition: Expr.h:2923
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:408
reverse_iterator rend()
Definition: ASTVector.h:100
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:1511
do v
Definition: arm_acle.h:78
const SourceManager & SM
Definition: Format.cpp:1308
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
Definition: opencl-c.h:82
SourceRange getSourceRange() const
Definition: ExprCXX.h:106
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:412
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1279
unsigned getWCharWidth() const
getWCharWidth/Align - Return the size of &#39;wchar_t&#39; for this target, in bits.
Definition: TargetInfo.h:390
RecordDecl * getDecl() const
Definition: Type.h:3848
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:95
Expr * IgnoreCasts() LLVM_READONLY
Ignore casts. Strip off any CastExprs, returning their operand.
Definition: Expr.cpp:2484
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:1771
const llvm::fltSemantics & getSemantics() const
Return the APFloat semantics this literal uses.
Definition: Expr.cpp:784
Expr * IgnoreConversionOperator() LLVM_READONLY
IgnoreConversionOperator - Ignore conversion operator.
Definition: Expr.cpp:2571
AtomicExpr(SourceLocation BLoc, ArrayRef< Expr *> args, QualType t, AtomicOp op, SourceLocation RP)
Definition: Expr.cpp:3980
unsigned DotLoc
The location of the &#39;.&#39; in the designated initializer.
Definition: Expr.h:4156
UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, QualType resultType, SourceLocation op, SourceLocation rp)
Definition: Expr.h:2039
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:305
void ExpandDesignator(const ASTContext &C, unsigned Idx, const Designator *First, const Designator *Last)
Replaces the designator at index Idx with the series of designators in [First, Last).
Definition: Expr.cpp:3814
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:868
Expr * getBase() const
Definition: Expr.h:4456
#define false
Definition: stdbool.h:33
Kind
QualType getCanonicalType() const
Definition: Type.h:5582
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:4970
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
Definition: Expr.h:191
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:3272
Encodes a location in the source.
QualType getReturnType() const
Definition: Type.h:3106
llvm::iterator_range< child_iterator > child_range
Definition: Stmt.h:422
SourceLocation getOperatorLoc() const
Definition: Expr.h:3024
PseudoObjectExprBitfields PseudoObjectExprBits
Definition: Stmt.h:276
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:5659
Expression is not a Null pointer constant.
Definition: Expr.h:675
Expr * getSubExpr() const
Definition: Expr.h:1744
CastKind getCastKind() const
Definition: Expr.h:2758
static const FieldDecl * getTargetFieldForToUnionCast(QualType unionType, QualType opType)
Definition: Expr.cpp:1698
ObjCMethodFamily getMethodFamily() const
Definition: ExprObjC.h:1270
unsigned getChar16Width() const
getChar16Width/Align - Return the size of &#39;char16_t&#39; for this target, in bits.
Definition: TargetInfo.h:395
Represents a call to a member function that may be written either with member call syntax (e...
Definition: ExprCXX.h:136
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:346
static QualType getUnderlyingType(const SubRegion *R)
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set...
Definition: Decl.h:2515
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:121
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr *> exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1345
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1684
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1918
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2272
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2104
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
Definition: Expr.h:706
CanQualType VoidTy
Definition: ASTContext.h:965
Expr * updateInit(const ASTContext &C, unsigned Init, Expr *expr)
Updates the initializer at index Init with the new expression expr, and returns the old expression at...
Definition: Expr.cpp:1895
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
AccessSpecifier getAccess() const
bool isKnownToHaveBooleanValue() const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:135
StringLiteral * getFunctionName()
Definition: Expr.cpp:469
RefQualifierKind
The kind of C++11 ref-qualifier associated with a function type.
Definition: Type.h:1255
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2823
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:2407
Expr ** getInits()
Retrieve the set of initializers.
Definition: Expr.h:3906
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition: Expr.cpp:3475
static DesignatedInitExpr * CreateEmpty(const ASTContext &C, unsigned NumIndexExprs)
Definition: Expr.cpp:3752
const CXXRecordDecl * getBestDynamicClassType() const
For an expression of class type or pointer to class type, return the most derived class decl the expr...
Definition: Expr.cpp:63
Expr * getArrayRangeStart(const Designator &D) const
Definition: Expr.cpp:3800
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1251
bool isVectorType() const
Definition: Type.h:5832
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1261
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1965
unsigned LBracketLoc
The location of the &#39;[&#39; starting the array range designator.
Definition: Expr.h:4168
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:3967
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:450
void sawArrayRangeDesignator(bool ARD=true)
Definition: Expr.h:4044
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2165
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:1801
static MemberExpr * Create(const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *memberdecl, DeclAccessPair founddecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *targs, QualType ty, ExprValueKind VK, ExprObjectKind OK)
Definition: Expr.cpp:1437
A placeholder type used to construct an empty shell of a type, that will be filled in later (e...
Definition: Stmt.h:308
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
Expr * getLHS() const
Definition: Expr.h:3030
A POD class for pairing a NamedDecl* with an access specifier.
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:625
Represents a C11 generic selection.
Definition: Expr.h:4685
StringRef getName() const
Return the actual identifier string.
SourceRange getDesignatorsSourceRange() const
Definition: Expr.cpp:3768
StreamedQualTypeHelper stream(const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
Definition: Type.h:995
Dataflow Directional Tag Classes.
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
bool isValid() const
Return true if this is a valid SourceLocation object.
UnaryOperatorKind
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1224
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:571
bool hasSideEffects(Expr *E, ASTContext &Ctx)
Definition: Transforms.cpp:168
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition: ExprCXX.h:75
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
Decl * getReferencedDeclOfCallee()
Definition: Expr.cpp:1224
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1216
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:2154
static LLVM_READONLY bool isPrintable(unsigned char c)
Return true if this character is an ASCII printable character; that is, a character that should take ...
Definition: CharInfo.h:140
A field designator, e.g., ".x".
Definition: Expr.h:4146
The same as PrettyFunction, except that the &#39;virtual&#39; keyword is omitted for virtual member functions...
Definition: Expr.h:1199
void setExprs(const ASTContext &C, ArrayRef< Expr *> Exprs)
Definition: Expr.cpp:3603
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
AccessSpecifier getAccess() const
Definition: DeclBase.h:451
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:3253
StmtClass getStmtClass() const
Definition: Stmt.h:361
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2033
bool isBooleanType() const
Definition: Type.h:6026
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:3850
Expression is a Null pointer constant built from a zero integer expression that is not a simple...
Definition: Expr.h:682
void resize(const ASTContext &C, unsigned N, const T &NV)
Definition: ASTVector.h:338
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr *> semantic, unsigned resultIndex)
Definition: Expr.cpp:3904
void setInstantiationDependent(bool ID)
Set whether this expression is instantiation-dependent or not.
Definition: Expr.h:196
Expression is a C++11 nullptr.
Definition: Expr.h:688
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2440
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...
unsigned getNumElements() const
getNumElements - Get the number of components being selected.
Definition: Expr.cpp:3519
semantics_iterator semantics_begin()
Definition: Expr.h:5038
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1307
ConstEvaluatedExprVisitor - This class visits &#39;const Expr *&#39;s.
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:2889
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:1566
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2549
Expr * getArrayRangeEnd(const Designator &D) const
Definition: Expr.cpp:3806
llvm::APInt getValue() const
Definition: Expr.h:1279
unsigned getNumSubExprs() const
Definition: Expr.h:5169
Decl * getCalleeDecl()
Definition: Expr.cpp:1220
Pointer to a block type.
Definition: Type.h:2325
GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo *> AssocTypes, ArrayRef< Expr *> AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Definition: Expr.cpp:3611
bool isStringLiteralInit() const
Definition: Expr.cpp:1917
struct ArrayOrRangeDesignator ArrayOrRange
An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
Definition: Expr.h:4194
unsigned getIntWidth(QualType T) const
Not an overloaded operator.
Definition: OperatorKinds.h:23
bool isIncompleteArrayType() const
Definition: Type.h:5811
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:3839
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:428
bool body_empty() const
Definition: Stmt.h:599
llvm::iterator_range< const_child_iterator > const_child_range
Definition: Stmt.h:423
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2121
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:3791
static StringRef getIdentTypeName(IdentType IT)
Definition: Expr.cpp:473
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:5985
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant...
Definition: Expr.cpp:2750
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition: Expr.cpp:1739
bool isFunctionType() const
Definition: Type.h:5763
static ImplicitCastExpr * CreateEmpty(const ASTContext &Context, unsigned PathSize)
Definition: Expr.cpp:1732
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1326
Expr * IgnoreParenLValueCasts() LLVM_READONLY
Ignore parentheses and lvalue casts.
Definition: Expr.cpp:2509
Opcode getOpcode() const
Definition: Expr.h:1741
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1303
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:1335
UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits
Definition: Stmt.h:271
Represents a base class of a C++ class.
Definition: DeclCXX.h:157
iterator begin()
Definition: ASTVector.h:92
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1961
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:479
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2124
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:505
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1052
A template argument list.
Definition: DeclTemplate.h:195
static CStyleCastExpr * CreateEmpty(const ASTContext &Context, unsigned PathSize)
Definition: Expr.cpp:1754
static const Expr * skipTemporaryBindingsNoOpCastsAndParens(const Expr *E)
Skip over any no-op casts and any temporary-binding expressions.
Definition: Expr.cpp:2630
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:3854
bool refersToGlobalRegisterVar() const
Returns whether this expression refers to a global register variable.
Definition: Expr.cpp:3501
bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc, SourceRange &R1, SourceRange &R2, ASTContext &Ctx) const
isUnusedResultAWarning - Return true if this immediate expression should be warned about if the resul...
Definition: Expr.cpp:2028
void reserve(const ASTContext &C, unsigned N)
Definition: ASTVector.h:168
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:685
void Deallocate(void *Ptr) const
Definition: ASTContext.h:631
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2387
CallingConv getCallConv() const
Definition: Type.h:3114
Represents a C++ struct/union/class.
Definition: DeclCXX.h:266
bool isVoidType() const
Definition: Type.h:5963
bool isSyntacticForm() const
Definition: Expr.h:4027
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2822
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition: Expr.cpp:4067
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:3665
static bool hasAnyTypeDependentArguments(ArrayRef< Expr *> Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:2742
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr.type.conv]).
Definition: ExprCXX.h:1410
Expr * getRHS() const
Definition: Expr.h:3316
bool isPRValue() const
Definition: Expr.h:355
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:517
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...
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:245
bool isImplicitCXXThis() const
Whether this expression is an implicit reference to &#39;this&#39; in C++.
Definition: Expr.cpp:2698
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1509
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2209
Designator * getDesignator(unsigned Idx)
Definition: Expr.h:4318
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:237
void reserveInits(const ASTContext &C, unsigned NumInits)
Reserve space for some number of initializers.
Definition: Expr.cpp:1886
capture_iterator capture_begin() const
Retrieve an iterator pointing to the first lambda capture.
Definition: ExprCXX.cpp:956
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:896
DeclAccessPair FoundDecl
The DeclAccessPair through which the MemberDecl was found due to name qualifiers. ...
Definition: Expr.h:2382
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1795
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
bool isUnion() const
Definition: Decl.h:3058
Expr * getRHS() const
Definition: Expr.h:3032
bool isPointerType() const
Definition: Type.h:5766
CallExprBitfields CallExprBits
Definition: Stmt.h:274
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:1808
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:3985
bool isDefaultArgument() const
Determine whether this expression is a default function argument.
Definition: Expr.cpp:2617
bool isOBJCGCCandidate(ASTContext &Ctx) const
isOBJCGCCandidate - Return true if this expression may be used in a read/ write barrier.
Definition: Expr.cpp:2362
QualType getType() const
Definition: Decl.h:602
#define true
Definition: stdbool.h:32
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:111
unsigned getNumArgs() const
Definition: ExprCXX.h:1300
A trivial tuple used to represent a source range.
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to...
Definition: Expr.cpp:1116
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type, member-designator).
Definition: Expr.h:1926
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2646
static int getAccessorIdx(char c, bool isNumericAccessor)
Definition: Type.h:2941
QualType getValueType() const
Definition: Expr.cpp:4060
double getValueAsApproximateDouble() const
getValueAsApproximateDouble - This returns the value as an inaccurate double.
Definition: Expr.cpp:822
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition: ExprObjC.h:1143
unsigned getNumParams() const
getNumParams - Return the number of parameters this function must have based on its FunctionType...
Definition: Decl.cpp:2877
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:257
const LangOptions & getLangOpts() const
Definition: ASTContext.h:661
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration...
Definition: DeclObjC.h:2396
IdentifierInfo * getFieldName() const
Definition: Expr.cpp:3666
This class handles loading and caching of source files into memory.
InitListExpr * getSyntacticForm() const
Definition: Expr.h:4030
const T * const_iterator
Definition: ASTVector.h:81
Defines enum values for all the target-independent builtin functions.
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant()...
Definition: Expr.h:673
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:70
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2431
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
SourceRange getSourceRange() const LLVM_READONLY
Definition: Expr.h:4292
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1497