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_Spaceship: return BO_Cmp;
1784  case OO_Less: return BO_LT;
1785  case OO_Greater: return BO_GT;
1786  case OO_PlusEqual: return BO_AddAssign;
1787  case OO_MinusEqual: return BO_SubAssign;
1788  case OO_StarEqual: return BO_MulAssign;
1789  case OO_SlashEqual: return BO_DivAssign;
1790  case OO_PercentEqual: return BO_RemAssign;
1791  case OO_CaretEqual: return BO_XorAssign;
1792  case OO_AmpEqual: return BO_AndAssign;
1793  case OO_PipeEqual: return BO_OrAssign;
1794  case OO_LessLess: return BO_Shl;
1795  case OO_GreaterGreater: return BO_Shr;
1796  case OO_LessLessEqual: return BO_ShlAssign;
1797  case OO_GreaterGreaterEqual: return BO_ShrAssign;
1798  case OO_EqualEqual: return BO_EQ;
1799  case OO_ExclaimEqual: return BO_NE;
1800  case OO_LessEqual: return BO_LE;
1801  case OO_GreaterEqual: return BO_GE;
1802  case OO_AmpAmp: return BO_LAnd;
1803  case OO_PipePipe: return BO_LOr;
1804  case OO_Comma: return BO_Comma;
1805  case OO_ArrowStar: return BO_PtrMemI;
1806  }
1807 }
1808 
1810  static const OverloadedOperatorKind OverOps[] = {
1811  /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1812  OO_Star, OO_Slash, OO_Percent,
1813  OO_Plus, OO_Minus,
1814  OO_LessLess, OO_GreaterGreater,
1815  OO_Spaceship,
1816  OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1817  OO_EqualEqual, OO_ExclaimEqual,
1818  OO_Amp,
1819  OO_Caret,
1820  OO_Pipe,
1821  OO_AmpAmp,
1822  OO_PipePipe,
1823  OO_Equal, OO_StarEqual,
1824  OO_SlashEqual, OO_PercentEqual,
1825  OO_PlusEqual, OO_MinusEqual,
1826  OO_LessLessEqual, OO_GreaterGreaterEqual,
1827  OO_AmpEqual, OO_CaretEqual,
1828  OO_PipeEqual,
1829  OO_Comma
1830  };
1831  return OverOps[Opc];
1832 }
1833 
1835  Opcode Opc,
1836  Expr *LHS, Expr *RHS) {
1837  if (Opc != BO_Add)
1838  return false;
1839 
1840  // Check that we have one pointer and one integer operand.
1841  Expr *PExp;
1842  if (LHS->getType()->isPointerType()) {
1843  if (!RHS->getType()->isIntegerType())
1844  return false;
1845  PExp = LHS;
1846  } else if (RHS->getType()->isPointerType()) {
1847  if (!LHS->getType()->isIntegerType())
1848  return false;
1849  PExp = RHS;
1850  } else {
1851  return false;
1852  }
1853 
1854  // Check that the pointer is a nullptr.
1855  if (!PExp->IgnoreParenCasts()
1857  return false;
1858 
1859  // Check that the pointee type is char-sized.
1860  const PointerType *PTy = PExp->getType()->getAs<PointerType>();
1861  if (!PTy || !PTy->getPointeeType()->isCharType())
1862  return false;
1863 
1864  return true;
1865 }
1867  ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
1868  : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1869  false, false),
1870  InitExprs(C, initExprs.size()),
1871  LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
1872 {
1873  sawArrayRangeDesignator(false);
1874  for (unsigned I = 0; I != initExprs.size(); ++I) {
1875  if (initExprs[I]->isTypeDependent())
1876  ExprBits.TypeDependent = true;
1877  if (initExprs[I]->isValueDependent())
1878  ExprBits.ValueDependent = true;
1879  if (initExprs[I]->isInstantiationDependent())
1880  ExprBits.InstantiationDependent = true;
1881  if (initExprs[I]->containsUnexpandedParameterPack())
1882  ExprBits.ContainsUnexpandedParameterPack = true;
1883  }
1884 
1885  InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
1886 }
1887 
1888 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
1889  if (NumInits > InitExprs.size())
1890  InitExprs.reserve(C, NumInits);
1891 }
1892 
1893 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
1894  InitExprs.resize(C, NumInits, nullptr);
1895 }
1896 
1897 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
1898  if (Init >= InitExprs.size()) {
1899  InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
1900  setInit(Init, expr);
1901  return nullptr;
1902  }
1903 
1904  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1905  setInit(Init, expr);
1906  return Result;
1907 }
1908 
1910  assert(!hasArrayFiller() && "Filler already set!");
1911  ArrayFillerOrUnionFieldInit = filler;
1912  // Fill out any "holes" in the array due to designated initializers.
1913  Expr **inits = getInits();
1914  for (unsigned i = 0, e = getNumInits(); i != e; ++i)
1915  if (inits[i] == nullptr)
1916  inits[i] = filler;
1917 }
1918 
1920  if (getNumInits() != 1)
1921  return false;
1922  const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
1923  if (!AT || !AT->getElementType()->isIntegerType())
1924  return false;
1925  // It is possible for getInit() to return null.
1926  const Expr *Init = getInit(0);
1927  if (!Init)
1928  return false;
1929  Init = Init->IgnoreParens();
1930  return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
1931 }
1932 
1934  assert(isSemanticForm() && "syntactic form never semantically transparent");
1935 
1936  // A glvalue InitListExpr is always just sugar.
1937  if (isGLValue()) {
1938  assert(getNumInits() == 1 && "multiple inits in glvalue init list");
1939  return true;
1940  }
1941 
1942  // Otherwise, we're sugar if and only if we have exactly one initializer that
1943  // is of the same type.
1944  if (getNumInits() != 1 || !getInit(0))
1945  return false;
1946 
1947  // Don't confuse aggregate initialization of a struct X { X &x; }; with a
1948  // transparent struct copy.
1949  if (!getInit(0)->isRValue() && getType()->isRecordType())
1950  return false;
1951 
1952  return getType().getCanonicalType() ==
1954 }
1955 
1957  assert(isSyntacticForm() && "only test syntactic form as zero initializer");
1958 
1959  if (LangOpts.CPlusPlus || getNumInits() != 1) {
1960  return false;
1961  }
1962 
1963  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
1964  return Lit && Lit->getValue() == 0;
1965 }
1966 
1968  if (InitListExpr *SyntacticForm = getSyntacticForm())
1969  return SyntacticForm->getLocStart();
1970  SourceLocation Beg = LBraceLoc;
1971  if (Beg.isInvalid()) {
1972  // Find the first non-null initializer.
1973  for (InitExprsTy::const_iterator I = InitExprs.begin(),
1974  E = InitExprs.end();
1975  I != E; ++I) {
1976  if (Stmt *S = *I) {
1977  Beg = S->getLocStart();
1978  break;
1979  }
1980  }
1981  }
1982  return Beg;
1983 }
1984 
1986  if (InitListExpr *SyntacticForm = getSyntacticForm())
1987  return SyntacticForm->getLocEnd();
1988  SourceLocation End = RBraceLoc;
1989  if (End.isInvalid()) {
1990  // Find the first non-null initializer from the end.
1991  for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1992  E = InitExprs.rend();
1993  I != E; ++I) {
1994  if (Stmt *S = *I) {
1995  End = S->getLocEnd();
1996  break;
1997  }
1998  }
1999  }
2000  return End;
2001 }
2002 
2003 /// getFunctionType - Return the underlying function type for this block.
2004 ///
2006  // The block pointer is never sugared, but the function type might be.
2007  return cast<BlockPointerType>(getType())
2008  ->getPointeeType()->castAs<FunctionProtoType>();
2009 }
2010 
2012  return TheBlock->getCaretLocation();
2013 }
2014 const Stmt *BlockExpr::getBody() const {
2015  return TheBlock->getBody();
2016 }
2018  return TheBlock->getBody();
2019 }
2020 
2021 
2022 //===----------------------------------------------------------------------===//
2023 // Generic Expression Routines
2024 //===----------------------------------------------------------------------===//
2025 
2026 /// isUnusedResultAWarning - Return true if this immediate expression should
2027 /// be warned about if the result is unused. If so, fill in Loc and Ranges
2028 /// with location to warn on and the source range[s] to report with the
2029 /// warning.
2031  SourceRange &R1, SourceRange &R2,
2032  ASTContext &Ctx) const {
2033  // Don't warn if the expr is type dependent. The type could end up
2034  // instantiating to void.
2035  if (isTypeDependent())
2036  return false;
2037 
2038  switch (getStmtClass()) {
2039  default:
2040  if (getType()->isVoidType())
2041  return false;
2042  WarnE = this;
2043  Loc = getExprLoc();
2044  R1 = getSourceRange();
2045  return true;
2046  case ParenExprClass:
2047  return cast<ParenExpr>(this)->getSubExpr()->
2048  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2049  case GenericSelectionExprClass:
2050  return cast<GenericSelectionExpr>(this)->getResultExpr()->
2051  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2052  case ChooseExprClass:
2053  return cast<ChooseExpr>(this)->getChosenSubExpr()->
2054  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2055  case UnaryOperatorClass: {
2056  const UnaryOperator *UO = cast<UnaryOperator>(this);
2057 
2058  switch (UO->getOpcode()) {
2059  case UO_Plus:
2060  case UO_Minus:
2061  case UO_AddrOf:
2062  case UO_Not:
2063  case UO_LNot:
2064  case UO_Deref:
2065  break;
2066  case UO_Coawait:
2067  // This is just the 'operator co_await' call inside the guts of a
2068  // dependent co_await call.
2069  case UO_PostInc:
2070  case UO_PostDec:
2071  case UO_PreInc:
2072  case UO_PreDec: // ++/--
2073  return false; // Not a warning.
2074  case UO_Real:
2075  case UO_Imag:
2076  // accessing a piece of a volatile complex is a side-effect.
2077  if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2078  .isVolatileQualified())
2079  return false;
2080  break;
2081  case UO_Extension:
2082  return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2083  }
2084  WarnE = this;
2085  Loc = UO->getOperatorLoc();
2086  R1 = UO->getSubExpr()->getSourceRange();
2087  return true;
2088  }
2089  case BinaryOperatorClass: {
2090  const BinaryOperator *BO = cast<BinaryOperator>(this);
2091  switch (BO->getOpcode()) {
2092  default:
2093  break;
2094  // Consider the RHS of comma for side effects. LHS was checked by
2095  // Sema::CheckCommaOperands.
2096  case BO_Comma:
2097  // ((foo = <blah>), 0) is an idiom for hiding the result (and
2098  // lvalue-ness) of an assignment written in a macro.
2099  if (IntegerLiteral *IE =
2100  dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2101  if (IE->getValue() == 0)
2102  return false;
2103  return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2104  // Consider '||', '&&' to have side effects if the LHS or RHS does.
2105  case BO_LAnd:
2106  case BO_LOr:
2107  if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2108  !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2109  return false;
2110  break;
2111  }
2112  if (BO->isAssignmentOp())
2113  return false;
2114  WarnE = this;
2115  Loc = BO->getOperatorLoc();
2116  R1 = BO->getLHS()->getSourceRange();
2117  R2 = BO->getRHS()->getSourceRange();
2118  return true;
2119  }
2120  case CompoundAssignOperatorClass:
2121  case VAArgExprClass:
2122  case AtomicExprClass:
2123  return false;
2124 
2125  case ConditionalOperatorClass: {
2126  // If only one of the LHS or RHS is a warning, the operator might
2127  // be being used for control flow. Only warn if both the LHS and
2128  // RHS are warnings.
2129  const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
2130  if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2131  return false;
2132  if (!Exp->getLHS())
2133  return true;
2134  return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2135  }
2136 
2137  case MemberExprClass:
2138  WarnE = this;
2139  Loc = cast<MemberExpr>(this)->getMemberLoc();
2140  R1 = SourceRange(Loc, Loc);
2141  R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2142  return true;
2143 
2144  case ArraySubscriptExprClass:
2145  WarnE = this;
2146  Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2147  R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2148  R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2149  return true;
2150 
2151  case CXXOperatorCallExprClass: {
2152  // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2153  // overloads as there is no reasonable way to define these such that they
2154  // have non-trivial, desirable side-effects. See the -Wunused-comparison
2155  // warning: operators == and != are commonly typo'ed, and so warning on them
2156  // provides additional value as well. If this list is updated,
2157  // DiagnoseUnusedComparison should be as well.
2158  const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2159  switch (Op->getOperator()) {
2160  default:
2161  break;
2162  case OO_EqualEqual:
2163  case OO_ExclaimEqual:
2164  case OO_Less:
2165  case OO_Greater:
2166  case OO_GreaterEqual:
2167  case OO_LessEqual:
2168  if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2169  Op->getCallReturnType(Ctx)->isVoidType())
2170  break;
2171  WarnE = this;
2172  Loc = Op->getOperatorLoc();
2173  R1 = Op->getSourceRange();
2174  return true;
2175  }
2176 
2177  // Fallthrough for generic call handling.
2178  LLVM_FALLTHROUGH;
2179  }
2180  case CallExprClass:
2181  case CXXMemberCallExprClass:
2182  case UserDefinedLiteralClass: {
2183  // If this is a direct call, get the callee.
2184  const CallExpr *CE = cast<CallExpr>(this);
2185  if (const Decl *FD = CE->getCalleeDecl()) {
2186  const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2187  bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2188  : FD->hasAttr<WarnUnusedResultAttr>();
2189 
2190  // If the callee has attribute pure, const, or warn_unused_result, warn
2191  // about it. void foo() { strlen("bar"); } should warn.
2192  //
2193  // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2194  // updated to match for QoI.
2195  if (HasWarnUnusedResultAttr ||
2196  FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2197  WarnE = this;
2198  Loc = CE->getCallee()->getLocStart();
2199  R1 = CE->getCallee()->getSourceRange();
2200 
2201  if (unsigned NumArgs = CE->getNumArgs())
2202  R2 = SourceRange(CE->getArg(0)->getLocStart(),
2203  CE->getArg(NumArgs-1)->getLocEnd());
2204  return true;
2205  }
2206  }
2207  return false;
2208  }
2209 
2210  // If we don't know precisely what we're looking at, let's not warn.
2211  case UnresolvedLookupExprClass:
2212  case CXXUnresolvedConstructExprClass:
2213  return false;
2214 
2215  case CXXTemporaryObjectExprClass:
2216  case CXXConstructExprClass: {
2217  if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2218  if (Type->hasAttr<WarnUnusedAttr>()) {
2219  WarnE = this;
2220  Loc = getLocStart();
2221  R1 = getSourceRange();
2222  return true;
2223  }
2224  }
2225  return false;
2226  }
2227 
2228  case ObjCMessageExprClass: {
2229  const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2230  if (Ctx.getLangOpts().ObjCAutoRefCount &&
2231  ME->isInstanceMessage() &&
2232  !ME->getType()->isVoidType() &&
2233  ME->getMethodFamily() == OMF_init) {
2234  WarnE = this;
2235  Loc = getExprLoc();
2236  R1 = ME->getSourceRange();
2237  return true;
2238  }
2239 
2240  if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2241  if (MD->hasAttr<WarnUnusedResultAttr>()) {
2242  WarnE = this;
2243  Loc = getExprLoc();
2244  return true;
2245  }
2246 
2247  return false;
2248  }
2249 
2250  case ObjCPropertyRefExprClass:
2251  WarnE = this;
2252  Loc = getExprLoc();
2253  R1 = getSourceRange();
2254  return true;
2255 
2256  case PseudoObjectExprClass: {
2257  const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2258 
2259  // Only complain about things that have the form of a getter.
2260  if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2261  isa<BinaryOperator>(PO->getSyntacticForm()))
2262  return false;
2263 
2264  WarnE = this;
2265  Loc = getExprLoc();
2266  R1 = getSourceRange();
2267  return true;
2268  }
2269 
2270  case StmtExprClass: {
2271  // Statement exprs don't logically have side effects themselves, but are
2272  // sometimes used in macros in ways that give them a type that is unused.
2273  // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2274  // however, if the result of the stmt expr is dead, we don't want to emit a
2275  // warning.
2276  const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2277  if (!CS->body_empty()) {
2278  if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2279  return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2280  if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2281  if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2282  return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2283  }
2284 
2285  if (getType()->isVoidType())
2286  return false;
2287  WarnE = this;
2288  Loc = cast<StmtExpr>(this)->getLParenLoc();
2289  R1 = getSourceRange();
2290  return true;
2291  }
2292  case CXXFunctionalCastExprClass:
2293  case CStyleCastExprClass: {
2294  // Ignore an explicit cast to void unless the operand is a non-trivial
2295  // volatile lvalue.
2296  const CastExpr *CE = cast<CastExpr>(this);
2297  if (CE->getCastKind() == CK_ToVoid) {
2298  if (CE->getSubExpr()->isGLValue() &&
2299  CE->getSubExpr()->getType().isVolatileQualified()) {
2300  const DeclRefExpr *DRE =
2301  dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2302  if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2303  cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2304  !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
2305  return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2306  R1, R2, Ctx);
2307  }
2308  }
2309  return false;
2310  }
2311 
2312  // If this is a cast to a constructor conversion, check the operand.
2313  // Otherwise, the result of the cast is unused.
2314  if (CE->getCastKind() == CK_ConstructorConversion)
2315  return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2316 
2317  WarnE = this;
2318  if (const CXXFunctionalCastExpr *CXXCE =
2319  dyn_cast<CXXFunctionalCastExpr>(this)) {
2320  Loc = CXXCE->getLocStart();
2321  R1 = CXXCE->getSubExpr()->getSourceRange();
2322  } else {
2323  const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2324  Loc = CStyleCE->getLParenLoc();
2325  R1 = CStyleCE->getSubExpr()->getSourceRange();
2326  }
2327  return true;
2328  }
2329  case ImplicitCastExprClass: {
2330  const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2331 
2332  // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2333  if (ICE->getCastKind() == CK_LValueToRValue &&
2335  return false;
2336 
2337  return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2338  }
2339  case CXXDefaultArgExprClass:
2340  return (cast<CXXDefaultArgExpr>(this)
2341  ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2342  case CXXDefaultInitExprClass:
2343  return (cast<CXXDefaultInitExpr>(this)
2344  ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2345 
2346  case CXXNewExprClass:
2347  // FIXME: In theory, there might be new expressions that don't have side
2348  // effects (e.g. a placement new with an uninitialized POD).
2349  case CXXDeleteExprClass:
2350  return false;
2351  case MaterializeTemporaryExprClass:
2352  return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2353  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2354  case CXXBindTemporaryExprClass:
2355  return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2356  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2357  case ExprWithCleanupsClass:
2358  return cast<ExprWithCleanups>(this)->getSubExpr()
2359  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2360  }
2361 }
2362 
2363 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2364 /// returns true, if it is; false otherwise.
2366  const Expr *E = IgnoreParens();
2367  switch (E->getStmtClass()) {
2368  default:
2369  return false;
2370  case ObjCIvarRefExprClass:
2371  return true;
2372  case Expr::UnaryOperatorClass:
2373  return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2374  case ImplicitCastExprClass:
2375  return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2376  case MaterializeTemporaryExprClass:
2377  return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2378  ->isOBJCGCCandidate(Ctx);
2379  case CStyleCastExprClass:
2380  return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2381  case DeclRefExprClass: {
2382  const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2383 
2384  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2385  if (VD->hasGlobalStorage())
2386  return true;
2387  QualType T = VD->getType();
2388  // dereferencing to a pointer is always a gc'able candidate,
2389  // unless it is __weak.
2390  return T->isPointerType() &&
2391  (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2392  }
2393  return false;
2394  }
2395  case MemberExprClass: {
2396  const MemberExpr *M = cast<MemberExpr>(E);
2397  return M->getBase()->isOBJCGCCandidate(Ctx);
2398  }
2399  case ArraySubscriptExprClass:
2400  return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2401  }
2402 }
2403 
2405  if (isTypeDependent())
2406  return false;
2407  return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2408 }
2409 
2411  assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2412 
2413  // Bound member expressions are always one of these possibilities:
2414  // x->m x.m x->*y x.*y
2415  // (possibly parenthesized)
2416 
2417  expr = expr->IgnoreParens();
2418  if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2419  assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2420  return mem->getMemberDecl()->getType();
2421  }
2422 
2423  if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2424  QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2425  ->getPointeeType();
2426  assert(type->isFunctionType());
2427  return type;
2428  }
2429 
2430  assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
2431  return QualType();
2432 }
2433 
2435  Expr* E = this;
2436  while (true) {
2437  if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2438  E = P->getSubExpr();
2439  continue;
2440  }
2441  if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2442  if (P->getOpcode() == UO_Extension) {
2443  E = P->getSubExpr();
2444  continue;
2445  }
2446  }
2447  if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2448  if (!P->isResultDependent()) {
2449  E = P->getResultExpr();
2450  continue;
2451  }
2452  }
2453  if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2454  if (!P->isConditionDependent()) {
2455  E = P->getChosenSubExpr();
2456  continue;
2457  }
2458  }
2459  return E;
2460  }
2461 }
2462 
2463 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2464 /// or CastExprs or ImplicitCastExprs, returning their operand.
2466  Expr *E = this;
2467  while (true) {
2468  E = E->IgnoreParens();
2469  if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2470  E = P->getSubExpr();
2471  continue;
2472  }
2473  if (MaterializeTemporaryExpr *Materialize
2474  = dyn_cast<MaterializeTemporaryExpr>(E)) {
2475  E = Materialize->GetTemporaryExpr();
2476  continue;
2477  }
2479  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2480  E = NTTP->getReplacement();
2481  continue;
2482  }
2483  return E;
2484  }
2485 }
2486 
2488  Expr *E = this;
2489  while (true) {
2490  if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2491  E = P->getSubExpr();
2492  continue;
2493  }
2494  if (MaterializeTemporaryExpr *Materialize
2495  = dyn_cast<MaterializeTemporaryExpr>(E)) {
2496  E = Materialize->GetTemporaryExpr();
2497  continue;
2498  }
2500  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2501  E = NTTP->getReplacement();
2502  continue;
2503  }
2504  return E;
2505  }
2506 }
2507 
2508 /// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2509 /// casts. This is intended purely as a temporary workaround for code
2510 /// that hasn't yet been rewritten to do the right thing about those
2511 /// casts, and may disappear along with the last internal use.
2513  Expr *E = this;
2514  while (true) {
2515  E = E->IgnoreParens();
2516  if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2517  if (P->getCastKind() == CK_LValueToRValue) {
2518  E = P->getSubExpr();
2519  continue;
2520  }
2521  } else if (MaterializeTemporaryExpr *Materialize
2522  = dyn_cast<MaterializeTemporaryExpr>(E)) {
2523  E = Materialize->GetTemporaryExpr();
2524  continue;
2525  } else if (SubstNonTypeTemplateParmExpr *NTTP
2526  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2527  E = NTTP->getReplacement();
2528  continue;
2529  }
2530  break;
2531  }
2532  return E;
2533 }
2534 
2536  Expr *E = this;
2537  while (true) {
2538  E = E->IgnoreParens();
2539  if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2540  if (CE->getCastKind() == CK_DerivedToBase ||
2541  CE->getCastKind() == CK_UncheckedDerivedToBase ||
2542  CE->getCastKind() == CK_NoOp) {
2543  E = CE->getSubExpr();
2544  continue;
2545  }
2546  }
2547 
2548  return E;
2549  }
2550 }
2551 
2553  Expr *E = this;
2554  while (true) {
2555  E = E->IgnoreParens();
2556  if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
2557  E = P->getSubExpr();
2558  continue;
2559  }
2560  if (MaterializeTemporaryExpr *Materialize
2561  = dyn_cast<MaterializeTemporaryExpr>(E)) {
2562  E = Materialize->GetTemporaryExpr();
2563  continue;
2564  }
2566  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2567  E = NTTP->getReplacement();
2568  continue;
2569  }
2570  return E;
2571  }
2572 }
2573 
2575  if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2576  if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2577  return MCE->getImplicitObjectArgument();
2578  }
2579  return this;
2580 }
2581 
2582 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2583 /// value (including ptr->int casts of the same size). Strip off any
2584 /// ParenExpr or CastExprs, returning their operand.
2586  Expr *E = this;
2587  while (true) {
2588  E = E->IgnoreParens();
2589 
2590  if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2591  // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2592  // ptr<->int casts of the same width. We also ignore all identity casts.
2593  Expr *SE = P->getSubExpr();
2594 
2595  if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2596  E = SE;
2597  continue;
2598  }
2599 
2600  if ((E->getType()->isPointerType() ||
2601  E->getType()->isIntegralType(Ctx)) &&
2602  (SE->getType()->isPointerType() ||
2603  SE->getType()->isIntegralType(Ctx)) &&
2604  Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2605  E = SE;
2606  continue;
2607  }
2608  }
2609 
2611  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2612  E = NTTP->getReplacement();
2613  continue;
2614  }
2615 
2616  return E;
2617  }
2618 }
2619 
2621  const Expr *E = this;
2622  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2623  E = M->GetTemporaryExpr();
2624 
2625  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2626  E = ICE->getSubExprAsWritten();
2627 
2628  return isa<CXXDefaultArgExpr>(E);
2629 }
2630 
2631 /// \brief Skip over any no-op casts and any temporary-binding
2632 /// expressions.
2634  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2635  E = M->GetTemporaryExpr();
2636 
2637  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2638  if (ICE->getCastKind() == CK_NoOp)
2639  E = ICE->getSubExpr();
2640  else
2641  break;
2642  }
2643 
2644  while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2645  E = BE->getSubExpr();
2646 
2647  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2648  if (ICE->getCastKind() == CK_NoOp)
2649  E = ICE->getSubExpr();
2650  else
2651  break;
2652  }
2653 
2654  return E->IgnoreParens();
2655 }
2656 
2657 /// isTemporaryObject - Determines if this expression produces a
2658 /// temporary of the given class type.
2659 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2660  if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2661  return false;
2662 
2664 
2665  // Temporaries are by definition pr-values of class type.
2666  if (!E->Classify(C).isPRValue()) {
2667  // In this context, property reference is a message call and is pr-value.
2668  if (!isa<ObjCPropertyRefExpr>(E))
2669  return false;
2670  }
2671 
2672  // Black-list a few cases which yield pr-values of class type that don't
2673  // refer to temporaries of that type:
2674 
2675  // - implicit derived-to-base conversions
2676  if (isa<ImplicitCastExpr>(E)) {
2677  switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2678  case CK_DerivedToBase:
2679  case CK_UncheckedDerivedToBase:
2680  return false;
2681  default:
2682  break;
2683  }
2684  }
2685 
2686  // - member expressions (all)
2687  if (isa<MemberExpr>(E))
2688  return false;
2689 
2690  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2691  if (BO->isPtrMemOp())
2692  return false;
2693 
2694  // - opaque values (all)
2695  if (isa<OpaqueValueExpr>(E))
2696  return false;
2697 
2698  return true;
2699 }
2700 
2702  const Expr *E = this;
2703 
2704  // Strip away parentheses and casts we don't care about.
2705  while (true) {
2706  if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2707  E = Paren->getSubExpr();
2708  continue;
2709  }
2710 
2711  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2712  if (ICE->getCastKind() == CK_NoOp ||
2713  ICE->getCastKind() == CK_LValueToRValue ||
2714  ICE->getCastKind() == CK_DerivedToBase ||
2715  ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2716  E = ICE->getSubExpr();
2717  continue;
2718  }
2719  }
2720 
2721  if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2722  if (UnOp->getOpcode() == UO_Extension) {
2723  E = UnOp->getSubExpr();
2724  continue;
2725  }
2726  }
2727 
2728  if (const MaterializeTemporaryExpr *M
2729  = dyn_cast<MaterializeTemporaryExpr>(E)) {
2730  E = M->GetTemporaryExpr();
2731  continue;
2732  }
2733 
2734  break;
2735  }
2736 
2737  if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2738  return This->isImplicit();
2739 
2740  return false;
2741 }
2742 
2743 /// hasAnyTypeDependentArguments - Determines if any of the expressions
2744 /// in Exprs is type-dependent.
2746  for (unsigned I = 0; I < Exprs.size(); ++I)
2747  if (Exprs[I]->isTypeDependent())
2748  return true;
2749 
2750  return false;
2751 }
2752 
2753 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2754  const Expr **Culprit) const {
2755  // This function is attempting whether an expression is an initializer
2756  // which can be evaluated at compile-time. It very closely parallels
2757  // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2758  // will lead to unexpected results. Like ConstExprEmitter, it falls back
2759  // to isEvaluatable most of the time.
2760  //
2761  // If we ever capture reference-binding directly in the AST, we can
2762  // kill the second parameter.
2763 
2764  if (IsForRef) {
2766  if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2767  return true;
2768  if (Culprit)
2769  *Culprit = this;
2770  return false;
2771  }
2772 
2773  switch (getStmtClass()) {
2774  default: break;
2775  case StringLiteralClass:
2776  case ObjCEncodeExprClass:
2777  return true;
2778  case CXXTemporaryObjectExprClass:
2779  case CXXConstructExprClass: {
2780  const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2781 
2782  if (CE->getConstructor()->isTrivial() &&
2784  // Trivial default constructor
2785  if (!CE->getNumArgs()) return true;
2786 
2787  // Trivial copy constructor
2788  assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
2789  return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
2790  }
2791 
2792  break;
2793  }
2794  case CompoundLiteralExprClass: {
2795  // This handles gcc's extension that allows global initializers like
2796  // "struct x {int x;} x = (struct x) {};".
2797  // FIXME: This accepts other cases it shouldn't!
2798  const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2799  return Exp->isConstantInitializer(Ctx, false, Culprit);
2800  }
2801  case DesignatedInitUpdateExprClass: {
2802  const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2803  return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2804  DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2805  }
2806  case InitListExprClass: {
2807  const InitListExpr *ILE = cast<InitListExpr>(this);
2808  if (ILE->getType()->isArrayType()) {
2809  unsigned numInits = ILE->getNumInits();
2810  for (unsigned i = 0; i < numInits; i++) {
2811  if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
2812  return false;
2813  }
2814  return true;
2815  }
2816 
2817  if (ILE->getType()->isRecordType()) {
2818  unsigned ElementNo = 0;
2819  RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
2820  for (const auto *Field : RD->fields()) {
2821  // If this is a union, skip all the fields that aren't being initialized.
2822  if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
2823  continue;
2824 
2825  // Don't emit anonymous bitfields, they just affect layout.
2826  if (Field->isUnnamedBitfield())
2827  continue;
2828 
2829  if (ElementNo < ILE->getNumInits()) {
2830  const Expr *Elt = ILE->getInit(ElementNo++);
2831  if (Field->isBitField()) {
2832  // Bitfields have to evaluate to an integer.
2833  llvm::APSInt ResultTmp;
2834  if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
2835  if (Culprit)
2836  *Culprit = Elt;
2837  return false;
2838  }
2839  } else {
2840  bool RefType = Field->getType()->isReferenceType();
2841  if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
2842  return false;
2843  }
2844  }
2845  }
2846  return true;
2847  }
2848 
2849  break;
2850  }
2851  case ImplicitValueInitExprClass:
2852  case NoInitExprClass:
2853  return true;
2854  case ParenExprClass:
2855  return cast<ParenExpr>(this)->getSubExpr()
2856  ->isConstantInitializer(Ctx, IsForRef, Culprit);
2857  case GenericSelectionExprClass:
2858  return cast<GenericSelectionExpr>(this)->getResultExpr()
2859  ->isConstantInitializer(Ctx, IsForRef, Culprit);
2860  case ChooseExprClass:
2861  if (cast<ChooseExpr>(this)->isConditionDependent()) {
2862  if (Culprit)
2863  *Culprit = this;
2864  return false;
2865  }
2866  return cast<ChooseExpr>(this)->getChosenSubExpr()
2867  ->isConstantInitializer(Ctx, IsForRef, Culprit);
2868  case UnaryOperatorClass: {
2869  const UnaryOperator* Exp = cast<UnaryOperator>(this);
2870  if (Exp->getOpcode() == UO_Extension)
2871  return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
2872  break;
2873  }
2874  case CXXFunctionalCastExprClass:
2875  case CXXStaticCastExprClass:
2876  case ImplicitCastExprClass:
2877  case CStyleCastExprClass:
2878  case ObjCBridgedCastExprClass:
2879  case CXXDynamicCastExprClass:
2880  case CXXReinterpretCastExprClass:
2881  case CXXConstCastExprClass: {
2882  const CastExpr *CE = cast<CastExpr>(this);
2883 
2884  // Handle misc casts we want to ignore.
2885  if (CE->getCastKind() == CK_NoOp ||
2886  CE->getCastKind() == CK_LValueToRValue ||
2887  CE->getCastKind() == CK_ToUnion ||
2888  CE->getCastKind() == CK_ConstructorConversion ||
2889  CE->getCastKind() == CK_NonAtomicToAtomic ||
2890  CE->getCastKind() == CK_AtomicToNonAtomic ||
2891  CE->getCastKind() == CK_IntToOCLSampler)
2892  return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
2893 
2894  break;
2895  }
2896  case MaterializeTemporaryExprClass:
2897  return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2898  ->isConstantInitializer(Ctx, false, Culprit);
2899 
2900  case SubstNonTypeTemplateParmExprClass:
2901  return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
2902  ->isConstantInitializer(Ctx, false, Culprit);
2903  case CXXDefaultArgExprClass:
2904  return cast<CXXDefaultArgExpr>(this)->getExpr()
2905  ->isConstantInitializer(Ctx, false, Culprit);
2906  case CXXDefaultInitExprClass:
2907  return cast<CXXDefaultInitExpr>(this)->getExpr()
2908  ->isConstantInitializer(Ctx, false, Culprit);
2909  }
2910  // Allow certain forms of UB in constant initializers: signed integer
2911  // overflow and floating-point division by zero. We'll give a warning on
2912  // these, but they're common enough that we have to accept them.
2914  return true;
2915  if (Culprit)
2916  *Culprit = this;
2917  return false;
2918 }
2919 
2920 namespace {
2921  /// \brief Look for any side effects within a Stmt.
2922  class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
2924  const bool IncludePossibleEffects;
2925  bool HasSideEffects;
2926 
2927  public:
2928  explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
2929  : Inherited(Context),
2930  IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
2931 
2932  bool hasSideEffects() const { return HasSideEffects; }
2933 
2934  void VisitExpr(const Expr *E) {
2935  if (!HasSideEffects &&
2936  E->HasSideEffects(Context, IncludePossibleEffects))
2937  HasSideEffects = true;
2938  }
2939  };
2940 }
2941 
2943  bool IncludePossibleEffects) const {
2944  // In circumstances where we care about definite side effects instead of
2945  // potential side effects, we want to ignore expressions that are part of a
2946  // macro expansion as a potential side effect.
2947  if (!IncludePossibleEffects && getExprLoc().isMacroID())
2948  return false;
2949 
2951  return IncludePossibleEffects;
2952 
2953  switch (getStmtClass()) {
2954  case NoStmtClass:
2955  #define ABSTRACT_STMT(Type)
2956  #define STMT(Type, Base) case Type##Class:
2957  #define EXPR(Type, Base)
2958  #include "clang/AST/StmtNodes.inc"
2959  llvm_unreachable("unexpected Expr kind");
2960 
2961  case DependentScopeDeclRefExprClass:
2962  case CXXUnresolvedConstructExprClass:
2963  case CXXDependentScopeMemberExprClass:
2964  case UnresolvedLookupExprClass:
2965  case UnresolvedMemberExprClass:
2966  case PackExpansionExprClass:
2967  case SubstNonTypeTemplateParmPackExprClass:
2968  case FunctionParmPackExprClass:
2969  case TypoExprClass:
2970  case CXXFoldExprClass:
2971  llvm_unreachable("shouldn't see dependent / unresolved nodes here");
2972 
2973  case DeclRefExprClass:
2974  case ObjCIvarRefExprClass:
2975  case PredefinedExprClass:
2976  case IntegerLiteralClass:
2977  case FloatingLiteralClass:
2978  case ImaginaryLiteralClass:
2979  case StringLiteralClass:
2980  case CharacterLiteralClass:
2981  case OffsetOfExprClass:
2982  case ImplicitValueInitExprClass:
2983  case UnaryExprOrTypeTraitExprClass:
2984  case AddrLabelExprClass:
2985  case GNUNullExprClass:
2986  case ArrayInitIndexExprClass:
2987  case NoInitExprClass:
2988  case CXXBoolLiteralExprClass:
2989  case CXXNullPtrLiteralExprClass:
2990  case CXXThisExprClass:
2991  case CXXScalarValueInitExprClass:
2992  case TypeTraitExprClass:
2993  case ArrayTypeTraitExprClass:
2994  case ExpressionTraitExprClass:
2995  case CXXNoexceptExprClass:
2996  case SizeOfPackExprClass:
2997  case ObjCStringLiteralClass:
2998  case ObjCEncodeExprClass:
2999  case ObjCBoolLiteralExprClass:
3000  case ObjCAvailabilityCheckExprClass:
3001  case CXXUuidofExprClass:
3002  case OpaqueValueExprClass:
3003  // These never have a side-effect.
3004  return false;
3005 
3006  case CallExprClass:
3007  case CXXOperatorCallExprClass:
3008  case CXXMemberCallExprClass:
3009  case CUDAKernelCallExprClass:
3010  case UserDefinedLiteralClass: {
3011  // We don't know a call definitely has side effects, except for calls
3012  // to pure/const functions that definitely don't.
3013  // If the call itself is considered side-effect free, check the operands.
3014  const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3015  bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3016  if (IsPure || !IncludePossibleEffects)
3017  break;
3018  return true;
3019  }
3020 
3021  case BlockExprClass:
3022  case CXXBindTemporaryExprClass:
3023  if (!IncludePossibleEffects)
3024  break;
3025  return true;
3026 
3027  case MSPropertyRefExprClass:
3028  case MSPropertySubscriptExprClass:
3029  case CompoundAssignOperatorClass:
3030  case VAArgExprClass:
3031  case AtomicExprClass:
3032  case CXXThrowExprClass:
3033  case CXXNewExprClass:
3034  case CXXDeleteExprClass:
3035  case CoawaitExprClass:
3036  case DependentCoawaitExprClass:
3037  case CoyieldExprClass:
3038  // These always have a side-effect.
3039  return true;
3040 
3041  case StmtExprClass: {
3042  // StmtExprs have a side-effect if any substatement does.
3043  SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3044  Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3045  return Finder.hasSideEffects();
3046  }
3047 
3048  case ExprWithCleanupsClass:
3049  if (IncludePossibleEffects)
3050  if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3051  return true;
3052  break;
3053 
3054  case ParenExprClass:
3055  case ArraySubscriptExprClass:
3056  case OMPArraySectionExprClass:
3057  case MemberExprClass:
3058  case ConditionalOperatorClass:
3059  case BinaryConditionalOperatorClass:
3060  case CompoundLiteralExprClass:
3061  case ExtVectorElementExprClass:
3062  case DesignatedInitExprClass:
3063  case DesignatedInitUpdateExprClass:
3064  case ArrayInitLoopExprClass:
3065  case ParenListExprClass:
3066  case CXXPseudoDestructorExprClass:
3067  case CXXStdInitializerListExprClass:
3068  case SubstNonTypeTemplateParmExprClass:
3069  case MaterializeTemporaryExprClass:
3070  case ShuffleVectorExprClass:
3071  case ConvertVectorExprClass:
3072  case AsTypeExprClass:
3073  // These have a side-effect if any subexpression does.
3074  break;
3075 
3076  case UnaryOperatorClass:
3077  if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3078  return true;
3079  break;
3080 
3081  case BinaryOperatorClass:
3082  if (cast<BinaryOperator>(this)->isAssignmentOp())
3083  return true;
3084  break;
3085 
3086  case InitListExprClass:
3087  // FIXME: The children for an InitListExpr doesn't include the array filler.
3088  if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3089  if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3090  return true;
3091  break;
3092 
3093  case GenericSelectionExprClass:
3094  return cast<GenericSelectionExpr>(this)->getResultExpr()->
3095  HasSideEffects(Ctx, IncludePossibleEffects);
3096 
3097  case ChooseExprClass:
3098  return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3099  Ctx, IncludePossibleEffects);
3100 
3101  case CXXDefaultArgExprClass:
3102  return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3103  Ctx, IncludePossibleEffects);
3104 
3105  case CXXDefaultInitExprClass: {
3106  const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3107  if (const Expr *E = FD->getInClassInitializer())
3108  return E->HasSideEffects(Ctx, IncludePossibleEffects);
3109  // If we've not yet parsed the initializer, assume it has side-effects.
3110  return true;
3111  }
3112 
3113  case CXXDynamicCastExprClass: {
3114  // A dynamic_cast expression has side-effects if it can throw.
3115  const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3116  if (DCE->getTypeAsWritten()->isReferenceType() &&
3117  DCE->getCastKind() == CK_Dynamic)
3118  return true;
3119  } // Fall through.
3120  case ImplicitCastExprClass:
3121  case CStyleCastExprClass:
3122  case CXXStaticCastExprClass:
3123  case CXXReinterpretCastExprClass:
3124  case CXXConstCastExprClass:
3125  case CXXFunctionalCastExprClass: {
3126  // While volatile reads are side-effecting in both C and C++, we treat them
3127  // as having possible (not definite) side-effects. This allows idiomatic
3128  // code to behave without warning, such as sizeof(*v) for a volatile-
3129  // qualified pointer.
3130  if (!IncludePossibleEffects)
3131  break;
3132 
3133  const CastExpr *CE = cast<CastExpr>(this);
3134  if (CE->getCastKind() == CK_LValueToRValue &&
3136  return true;
3137  break;
3138  }
3139 
3140  case CXXTypeidExprClass:
3141  // typeid might throw if its subexpression is potentially-evaluated, so has
3142  // side-effects in that case whether or not its subexpression does.
3143  return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3144 
3145  case CXXConstructExprClass:
3146  case CXXTemporaryObjectExprClass: {
3147  const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3148  if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3149  return true;
3150  // A trivial constructor does not add any side-effects of its own. Just look
3151  // at its arguments.
3152  break;
3153  }
3154 
3155  case CXXInheritedCtorInitExprClass: {
3156  const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3157  if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3158  return true;
3159  break;
3160  }
3161 
3162  case LambdaExprClass: {
3163  const LambdaExpr *LE = cast<LambdaExpr>(this);
3165  E = LE->capture_end(); I != E; ++I)
3166  if (I->getCaptureKind() == LCK_ByCopy)
3167  // FIXME: Only has a side-effect if the variable is volatile or if
3168  // the copy would invoke a non-trivial copy constructor.
3169  return true;
3170  return false;
3171  }
3172 
3173  case PseudoObjectExprClass: {
3174  // Only look for side-effects in the semantic form, and look past
3175  // OpaqueValueExpr bindings in that form.
3176  const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3178  E = PO->semantics_end();
3179  I != E; ++I) {
3180  const Expr *Subexpr = *I;
3181  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3182  Subexpr = OVE->getSourceExpr();
3183  if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3184  return true;
3185  }
3186  return false;
3187  }
3188 
3189  case ObjCBoxedExprClass:
3190  case ObjCArrayLiteralClass:
3191  case ObjCDictionaryLiteralClass:
3192  case ObjCSelectorExprClass:
3193  case ObjCProtocolExprClass:
3194  case ObjCIsaExprClass:
3195  case ObjCIndirectCopyRestoreExprClass:
3196  case ObjCSubscriptRefExprClass:
3197  case ObjCBridgedCastExprClass:
3198  case ObjCMessageExprClass:
3199  case ObjCPropertyRefExprClass:
3200  // FIXME: Classify these cases better.
3201  if (IncludePossibleEffects)
3202  return true;
3203  break;
3204  }
3205 
3206  // Recurse to children.
3207  for (const Stmt *SubStmt : children())
3208  if (SubStmt &&
3209  cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3210  return true;
3211 
3212  return false;
3213 }
3214 
3215 namespace {
3216  /// \brief Look for a call to a non-trivial function within an expression.
3217  class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3218  {
3220 
3221  bool NonTrivial;
3222 
3223  public:
3224  explicit NonTrivialCallFinder(const ASTContext &Context)
3225  : Inherited(Context), NonTrivial(false) { }
3226 
3227  bool hasNonTrivialCall() const { return NonTrivial; }
3228 
3229  void VisitCallExpr(const CallExpr *E) {
3230  if (const CXXMethodDecl *Method
3231  = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3232  if (Method->isTrivial()) {
3233  // Recurse to children of the call.
3234  Inherited::VisitStmt(E);
3235  return;
3236  }
3237  }
3238 
3239  NonTrivial = true;
3240  }
3241 
3242  void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3243  if (E->getConstructor()->isTrivial()) {
3244  // Recurse to children of the call.
3245  Inherited::VisitStmt(E);
3246  return;
3247  }
3248 
3249  NonTrivial = true;
3250  }
3251 
3252  void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3253  if (E->getTemporary()->getDestructor()->isTrivial()) {
3254  Inherited::VisitStmt(E);
3255  return;
3256  }
3257 
3258  NonTrivial = true;
3259  }
3260  };
3261 }
3262 
3263 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3264  NonTrivialCallFinder Finder(Ctx);
3265  Finder.Visit(this);
3266  return Finder.hasNonTrivialCall();
3267 }
3268 
3269 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3270 /// pointer constant or not, as well as the specific kind of constant detected.
3271 /// Null pointer constants can be integer constant expressions with the
3272 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3273 /// (a GNU extension).
3277  if (isValueDependent() &&
3278  (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3279  switch (NPC) {
3281  llvm_unreachable("Unexpected value dependent expression!");
3283  if (isTypeDependent() || getType()->isIntegralType(Ctx))
3284  return NPCK_ZeroExpression;
3285  else
3286  return NPCK_NotNull;
3287 
3289  return NPCK_NotNull;
3290  }
3291  }
3292 
3293  // Strip off a cast to void*, if it exists. Except in C++.
3294  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3295  if (!Ctx.getLangOpts().CPlusPlus) {
3296  // Check that it is a cast to void*.
3297  if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3298  QualType Pointee = PT->getPointeeType();
3299  // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3300  // has non-default address space it is not treated as nullptr.
3301  // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3302  // since it cannot be assigned to a pointer to constant address space.
3303  bool PointeeHasDefaultAS =
3304  Pointee.getAddressSpace() == LangAS::Default ||
3305  (Ctx.getLangOpts().OpenCLVersion >= 200 &&
3306  Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3307  (Ctx.getLangOpts().OpenCL &&
3308  Ctx.getLangOpts().OpenCLVersion < 200 &&
3310 
3311  if (PointeeHasDefaultAS && Pointee->isVoidType() && // to void*
3312  CE->getSubExpr()->getType()->isIntegerType()) // from int.
3313  return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3314  }
3315  }
3316  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3317  // Ignore the ImplicitCastExpr type entirely.
3318  return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3319  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3320  // Accept ((void*)0) as a null pointer constant, as many other
3321  // implementations do.
3322  return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3323  } else if (const GenericSelectionExpr *GE =
3324  dyn_cast<GenericSelectionExpr>(this)) {
3325  if (GE->isResultDependent())
3326  return NPCK_NotNull;
3327  return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3328  } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3329  if (CE->isConditionDependent())
3330  return NPCK_NotNull;
3331  return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3332  } else if (const CXXDefaultArgExpr *DefaultArg
3333  = dyn_cast<CXXDefaultArgExpr>(this)) {
3334  // See through default argument expressions.
3335  return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3336  } else if (const CXXDefaultInitExpr *DefaultInit
3337  = dyn_cast<CXXDefaultInitExpr>(this)) {
3338  // See through default initializer expressions.
3339  return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3340  } else if (isa<GNUNullExpr>(this)) {
3341  // The GNU __null extension is always a null pointer constant.
3342  return NPCK_GNUNull;
3343  } else if (const MaterializeTemporaryExpr *M
3344  = dyn_cast<MaterializeTemporaryExpr>(this)) {
3345  return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
3346  } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3347  if (const Expr *Source = OVE->getSourceExpr())
3348  return Source->isNullPointerConstant(Ctx, NPC);
3349  }
3350 
3351  // C++11 nullptr_t is always a null pointer constant.
3352  if (getType()->isNullPtrType())
3353  return NPCK_CXX11_nullptr;
3354 
3355  if (const RecordType *UT = getType()->getAsUnionType())
3356  if (!Ctx.getLangOpts().CPlusPlus11 &&
3357  UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3358  if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3359  const Expr *InitExpr = CLE->getInitializer();
3360  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3361  return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3362  }
3363  // This expression must be an integer type.
3364  if (!getType()->isIntegerType() ||
3365  (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3366  return NPCK_NotNull;
3367 
3368  if (Ctx.getLangOpts().CPlusPlus11) {
3369  // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3370  // value zero or a prvalue of type std::nullptr_t.
3371  // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3372  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3373  if (Lit && !Lit->getValue())
3374  return NPCK_ZeroLiteral;
3375  else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3376  return NPCK_NotNull;
3377  } else {
3378  // If we have an integer constant expression, we need to *evaluate* it and
3379  // test for the value 0.
3380  if (!isIntegerConstantExpr(Ctx))
3381  return NPCK_NotNull;
3382  }
3383 
3384  if (EvaluateKnownConstInt(Ctx) != 0)
3385  return NPCK_NotNull;
3386 
3387  if (isa<IntegerLiteral>(this))
3388  return NPCK_ZeroLiteral;
3389  return NPCK_ZeroExpression;
3390 }
3391 
3392 /// \brief If this expression is an l-value for an Objective C
3393 /// property, find the underlying property reference expression.
3395  const Expr *E = this;
3396  while (true) {
3397  assert((E->getValueKind() == VK_LValue &&
3398  E->getObjectKind() == OK_ObjCProperty) &&
3399  "expression is not a property reference");
3400  E = E->IgnoreParenCasts();
3401  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3402  if (BO->getOpcode() == BO_Comma) {
3403  E = BO->getRHS();
3404  continue;
3405  }
3406  }
3407 
3408  break;
3409  }
3410 
3411  return cast<ObjCPropertyRefExpr>(E);
3412 }
3413 
3414 bool Expr::isObjCSelfExpr() const {
3415  const Expr *E = IgnoreParenImpCasts();
3416 
3417  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3418  if (!DRE)
3419  return false;
3420 
3421  const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3422  if (!Param)
3423  return false;
3424 
3425  const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3426  if (!M)
3427  return false;
3428 
3429  return M->getSelfDecl() == Param;
3430 }
3431 
3433  Expr *E = this->IgnoreParens();
3434 
3435  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3436  if (ICE->getCastKind() == CK_LValueToRValue ||
3437  (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
3438  E = ICE->getSubExpr()->IgnoreParens();
3439  else
3440  break;
3441  }
3442 
3443  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3444  if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3445  if (Field->isBitField())
3446  return Field;
3447 
3448  if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E))
3449  if (FieldDecl *Ivar = dyn_cast<FieldDecl>(IvarRef->getDecl()))
3450  if (Ivar->isBitField())
3451  return Ivar;
3452 
3453  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3454  if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3455  if (Field->isBitField())
3456  return Field;
3457 
3458  if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3459  if (Expr *E = BD->getBinding())
3460  return E->getSourceBitField();
3461  }
3462 
3463  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3464  if (BinOp->isAssignmentOp() && BinOp->getLHS())
3465  return BinOp->getLHS()->getSourceBitField();
3466 
3467  if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3468  return BinOp->getRHS()->getSourceBitField();
3469  }
3470 
3471  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3472  if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3473  return UnOp->getSubExpr()->getSourceBitField();
3474 
3475  return nullptr;
3476 }
3477 
3479  // FIXME: Why do we not just look at the ObjectKind here?
3480  const Expr *E = this->IgnoreParens();
3481 
3482  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3483  if (ICE->getValueKind() != VK_RValue &&
3484  ICE->getCastKind() == CK_NoOp)
3485  E = ICE->getSubExpr()->IgnoreParens();
3486  else
3487  break;
3488  }
3489 
3490  if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3491  return ASE->getBase()->getType()->isVectorType();
3492 
3493  if (isa<ExtVectorElementExpr>(E))
3494  return true;
3495 
3496  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3497  if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3498  if (auto *E = BD->getBinding())
3499  return E->refersToVectorElement();
3500 
3501  return false;
3502 }
3503 
3505  const Expr *E = this->IgnoreParenImpCasts();
3506 
3507  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3508  if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3509  if (VD->getStorageClass() == SC_Register &&
3510  VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3511  return true;
3512 
3513  return false;
3514 }
3515 
3516 /// isArrow - Return true if the base expression is a pointer to vector,
3517 /// return false if the base expression is a vector.
3519  return getBase()->getType()->isPointerType();
3520 }
3521 
3523  if (const VectorType *VT = getType()->getAs<VectorType>())
3524  return VT->getNumElements();
3525  return 1;
3526 }
3527 
3528 /// containsDuplicateElements - Return true if any element access is repeated.
3530  // FIXME: Refactor this code to an accessor on the AST node which returns the
3531  // "type" of component access, and share with code below and in Sema.
3532  StringRef Comp = Accessor->getName();
3533 
3534  // Halving swizzles do not contain duplicate elements.
3535  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
3536  return false;
3537 
3538  // Advance past s-char prefix on hex swizzles.
3539  if (Comp[0] == 's' || Comp[0] == 'S')
3540  Comp = Comp.substr(1);
3541 
3542  for (unsigned i = 0, e = Comp.size(); i != e; ++i)
3543  if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
3544  return true;
3545 
3546  return false;
3547 }
3548 
3549 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
3551  SmallVectorImpl<uint32_t> &Elts) const {
3552  StringRef Comp = Accessor->getName();
3553  bool isNumericAccessor = false;
3554  if (Comp[0] == 's' || Comp[0] == 'S') {
3555  Comp = Comp.substr(1);
3556  isNumericAccessor = true;
3557  }
3558 
3559  bool isHi = Comp == "hi";
3560  bool isLo = Comp == "lo";
3561  bool isEven = Comp == "even";
3562  bool isOdd = Comp == "odd";
3563 
3564  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3565  uint64_t Index;
3566 
3567  if (isHi)
3568  Index = e + i;
3569  else if (isLo)
3570  Index = i;
3571  else if (isEven)
3572  Index = 2 * i;
3573  else if (isOdd)
3574  Index = 2 * i + 1;
3575  else
3576  Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
3577 
3578  Elts.push_back(Index);
3579  }
3580 }
3581 
3583  QualType Type, SourceLocation BLoc,
3584  SourceLocation RP)
3585  : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3586  Type->isDependentType(), Type->isDependentType(),
3587  Type->isInstantiationDependentType(),
3589  BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3590 {
3591  SubExprs = new (C) Stmt*[args.size()];
3592  for (unsigned i = 0; i != args.size(); i++) {
3593  if (args[i]->isTypeDependent())
3594  ExprBits.TypeDependent = true;
3595  if (args[i]->isValueDependent())
3596  ExprBits.ValueDependent = true;
3597  if (args[i]->isInstantiationDependent())
3598  ExprBits.InstantiationDependent = true;
3599  if (args[i]->containsUnexpandedParameterPack())
3600  ExprBits.ContainsUnexpandedParameterPack = true;
3601 
3602  SubExprs[i] = args[i];
3603  }
3604 }
3605 
3607  if (SubExprs) C.Deallocate(SubExprs);
3608 
3609  this->NumExprs = Exprs.size();
3610  SubExprs = new (C) Stmt*[NumExprs];
3611  memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
3612 }
3613 
3615  SourceLocation GenericLoc, Expr *ControllingExpr,
3616  ArrayRef<TypeSourceInfo*> AssocTypes,
3617  ArrayRef<Expr*> AssocExprs,
3618  SourceLocation DefaultLoc,
3619  SourceLocation RParenLoc,
3620  bool ContainsUnexpandedParameterPack,
3621  unsigned ResultIndex)
3622  : Expr(GenericSelectionExprClass,
3623  AssocExprs[ResultIndex]->getType(),
3624  AssocExprs[ResultIndex]->getValueKind(),
3625  AssocExprs[ResultIndex]->getObjectKind(),
3626  AssocExprs[ResultIndex]->isTypeDependent(),
3627  AssocExprs[ResultIndex]->isValueDependent(),
3628  AssocExprs[ResultIndex]->isInstantiationDependent(),
3629  ContainsUnexpandedParameterPack),
3630  AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3631  SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3632  NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3633  GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3634  SubExprs[CONTROLLING] = ControllingExpr;
3635  assert(AssocTypes.size() == AssocExprs.size());
3636  std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3637  std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
3638 }
3639 
3641  SourceLocation GenericLoc, Expr *ControllingExpr,
3642  ArrayRef<TypeSourceInfo*> AssocTypes,
3643  ArrayRef<Expr*> AssocExprs,
3644  SourceLocation DefaultLoc,
3645  SourceLocation RParenLoc,
3646  bool ContainsUnexpandedParameterPack)
3647  : Expr(GenericSelectionExprClass,
3648  Context.DependentTy,
3649  VK_RValue,
3650  OK_Ordinary,
3651  /*isTypeDependent=*/true,
3652  /*isValueDependent=*/true,
3653  /*isInstantiationDependent=*/true,
3654  ContainsUnexpandedParameterPack),
3655  AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3656  SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3657  NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3658  DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3659  SubExprs[CONTROLLING] = ControllingExpr;
3660  assert(AssocTypes.size() == AssocExprs.size());
3661  std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3662  std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
3663 }
3664 
3665 //===----------------------------------------------------------------------===//
3666 // DesignatedInitExpr
3667 //===----------------------------------------------------------------------===//
3668 
3670  assert(Kind == FieldDesignator && "Only valid on a field designator");
3671  if (Field.NameOrField & 0x01)
3672  return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3673  else
3674  return getField()->getIdentifier();
3675 }
3676 
3677 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
3678  llvm::ArrayRef<Designator> Designators,
3679  SourceLocation EqualOrColonLoc,
3680  bool GNUSyntax,
3681  ArrayRef<Expr*> IndexExprs,
3682  Expr *Init)
3683  : Expr(DesignatedInitExprClass, Ty,
3684  Init->getValueKind(), Init->getObjectKind(),
3685  Init->isTypeDependent(), Init->isValueDependent(),
3686  Init->isInstantiationDependent(),
3688  EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
3689  NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
3690  this->Designators = new (C) Designator[NumDesignators];
3691 
3692  // Record the initializer itself.
3693  child_iterator Child = child_begin();
3694  *Child++ = Init;
3695 
3696  // Copy the designators and their subexpressions, computing
3697  // value-dependence along the way.
3698  unsigned IndexIdx = 0;
3699  for (unsigned I = 0; I != NumDesignators; ++I) {
3700  this->Designators[I] = Designators[I];
3701 
3702  if (this->Designators[I].isArrayDesignator()) {
3703  // Compute type- and value-dependence.
3704  Expr *Index = IndexExprs[IndexIdx];
3705  if (Index->isTypeDependent() || Index->isValueDependent())
3706  ExprBits.TypeDependent = ExprBits.ValueDependent = true;
3707  if (Index->isInstantiationDependent())
3708  ExprBits.InstantiationDependent = true;
3709  // Propagate unexpanded parameter packs.
3711  ExprBits.ContainsUnexpandedParameterPack = true;
3712 
3713  // Copy the index expressions into permanent storage.
3714  *Child++ = IndexExprs[IndexIdx++];
3715  } else if (this->Designators[I].isArrayRangeDesignator()) {
3716  // Compute type- and value-dependence.
3717  Expr *Start = IndexExprs[IndexIdx];
3718  Expr *End = IndexExprs[IndexIdx + 1];
3719  if (Start->isTypeDependent() || Start->isValueDependent() ||
3720  End->isTypeDependent() || End->isValueDependent()) {
3721  ExprBits.TypeDependent = ExprBits.ValueDependent = true;
3722  ExprBits.InstantiationDependent = true;
3723  } else if (Start->isInstantiationDependent() ||
3724  End->isInstantiationDependent()) {
3725  ExprBits.InstantiationDependent = true;
3726  }
3727 
3728  // Propagate unexpanded parameter packs.
3729  if (Start->containsUnexpandedParameterPack() ||
3731  ExprBits.ContainsUnexpandedParameterPack = true;
3732 
3733  // Copy the start/end expressions into permanent storage.
3734  *Child++ = IndexExprs[IndexIdx++];
3735  *Child++ = IndexExprs[IndexIdx++];
3736  }
3737  }
3738 
3739  assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
3740 }
3741 
3744  llvm::ArrayRef<Designator> Designators,
3745  ArrayRef<Expr*> IndexExprs,
3746  SourceLocation ColonOrEqualLoc,
3747  bool UsesColonSyntax, Expr *Init) {
3748  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
3749  alignof(DesignatedInitExpr));
3750  return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
3751  ColonOrEqualLoc, UsesColonSyntax,
3752  IndexExprs, Init);
3753 }
3754 
3756  unsigned NumIndexExprs) {
3757  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
3758  alignof(DesignatedInitExpr));
3759  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3760 }
3761 
3763  const Designator *Desigs,
3764  unsigned NumDesigs) {
3765  Designators = new (C) Designator[NumDesigs];
3766  NumDesignators = NumDesigs;
3767  for (unsigned I = 0; I != NumDesigs; ++I)
3768  Designators[I] = Desigs[I];
3769 }
3770 
3772  DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3773  if (size() == 1)
3774  return DIE->getDesignator(0)->getSourceRange();
3775  return SourceRange(DIE->getDesignator(0)->getLocStart(),
3776  DIE->getDesignator(size()-1)->getLocEnd());
3777 }
3778 
3780  SourceLocation StartLoc;
3781  auto *DIE = const_cast<DesignatedInitExpr *>(this);
3782  Designator &First = *DIE->getDesignator(0);
3783  if (First.isFieldDesignator()) {
3784  if (GNUSyntax)
3786  else
3788  } else
3789  StartLoc =
3791  return StartLoc;
3792 }
3793 
3795  return getInit()->getLocEnd();
3796 }
3797 
3799  assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
3800  return getSubExpr(D.ArrayOrRange.Index + 1);
3801 }
3802 
3804  assert(D.Kind == Designator::ArrayRangeDesignator &&
3805  "Requires array range designator");
3806  return getSubExpr(D.ArrayOrRange.Index + 1);
3807 }
3808 
3810  assert(D.Kind == Designator::ArrayRangeDesignator &&
3811  "Requires array range designator");
3812  return getSubExpr(D.ArrayOrRange.Index + 2);
3813 }
3814 
3815 /// \brief Replaces the designator at index @p Idx with the series
3816 /// of designators in [First, Last).
3818  const Designator *First,
3819  const Designator *Last) {
3820  unsigned NumNewDesignators = Last - First;
3821  if (NumNewDesignators == 0) {
3822  std::copy_backward(Designators + Idx + 1,
3823  Designators + NumDesignators,
3824  Designators + Idx);
3825  --NumNewDesignators;
3826  return;
3827  } else if (NumNewDesignators == 1) {
3828  Designators[Idx] = *First;
3829  return;
3830  }
3831 
3832  Designator *NewDesignators
3833  = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
3834  std::copy(Designators, Designators + Idx, NewDesignators);
3835  std::copy(First, Last, NewDesignators + Idx);
3836  std::copy(Designators + Idx + 1, Designators + NumDesignators,
3837  NewDesignators + Idx + NumNewDesignators);
3838  Designators = NewDesignators;
3839  NumDesignators = NumDesignators - 1 + NumNewDesignators;
3840 }
3841 
3843  SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3844  : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3846  BaseAndUpdaterExprs[0] = baseExpr;
3847 
3848  InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3849  ILE->setType(baseExpr->getType());
3850  BaseAndUpdaterExprs[1] = ILE;
3851 }
3852 
3854  return getBase()->getLocStart();
3855 }
3856 
3858  return getBase()->getLocEnd();
3859 }
3860 
3862  ArrayRef<Expr*> exprs,
3863  SourceLocation rparenloc)
3864  : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
3865  false, false, false, false),
3866  NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3867  Exprs = new (C) Stmt*[exprs.size()];
3868  for (unsigned i = 0; i != exprs.size(); ++i) {
3869  if (exprs[i]->isTypeDependent())
3870  ExprBits.TypeDependent = true;
3871  if (exprs[i]->isValueDependent())
3872  ExprBits.ValueDependent = true;
3873  if (exprs[i]->isInstantiationDependent())
3874  ExprBits.InstantiationDependent = true;
3875  if (exprs[i]->containsUnexpandedParameterPack())
3876  ExprBits.ContainsUnexpandedParameterPack = true;
3877 
3878  Exprs[i] = exprs[i];
3879  }
3880 }
3881 
3883  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3884  e = ewc->getSubExpr();
3885  if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3886  e = m->GetTemporaryExpr();
3887  e = cast<CXXConstructExpr>(e)->getArg(0);
3888  while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3889  e = ice->getSubExpr();
3890  return cast<OpaqueValueExpr>(e);
3891 }
3892 
3894  EmptyShell sh,
3895  unsigned numSemanticExprs) {
3896  void *buffer =
3897  Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
3898  alignof(PseudoObjectExpr));
3899  return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3900 }
3901 
3902 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3903  : Expr(PseudoObjectExprClass, shell) {
3904  PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3905 }
3906 
3908  ArrayRef<Expr*> semantics,
3909  unsigned resultIndex) {
3910  assert(syntax && "no syntactic expression!");
3911  assert(semantics.size() && "no semantic expressions!");
3912 
3913  QualType type;
3914  ExprValueKind VK;
3915  if (resultIndex == NoResult) {
3916  type = C.VoidTy;
3917  VK = VK_RValue;
3918  } else {
3919  assert(resultIndex < semantics.size());
3920  type = semantics[resultIndex]->getType();
3921  VK = semantics[resultIndex]->getValueKind();
3922  assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3923  }
3924 
3925  void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
3926  alignof(PseudoObjectExpr));
3927  return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3928  resultIndex);
3929 }
3930 
3931 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3932  Expr *syntax, ArrayRef<Expr*> semantics,
3933  unsigned resultIndex)
3934  : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3935  /*filled in at end of ctor*/ false, false, false, false) {
3936  PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3937  PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3938 
3939  for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3940  Expr *E = (i == 0 ? syntax : semantics[i-1]);
3941  getSubExprsBuffer()[i] = E;
3942 
3943  if (E->isTypeDependent())
3944  ExprBits.TypeDependent = true;
3945  if (E->isValueDependent())
3946  ExprBits.ValueDependent = true;
3948  ExprBits.InstantiationDependent = true;
3950  ExprBits.ContainsUnexpandedParameterPack = true;
3951 
3952  if (isa<OpaqueValueExpr>(E))
3953  assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
3954  "opaque-value semantic expressions for pseudo-object "
3955  "operations must have sources");
3956  }
3957 }
3958 
3959 //===----------------------------------------------------------------------===//
3960 // Child Iterators for iterating over subexpressions/substatements
3961 //===----------------------------------------------------------------------===//
3962 
3963 // UnaryExprOrTypeTraitExpr
3965  const_child_range CCR =
3966  const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
3967  return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
3968 }
3969 
3971  // If this is of a type and the type is a VLA type (and not a typedef), the
3972  // size expression of the VLA needs to be treated as an executable expression.
3973  // Why isn't this weirdness documented better in StmtIterator?
3974  if (isArgumentType()) {
3975  if (const VariableArrayType *T =
3976  dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
3979  }
3980  return const_child_range(&Argument.Ex, &Argument.Ex + 1);
3981 }
3982 
3984  QualType t, AtomicOp op, SourceLocation RP)
3985  : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3986  false, false, false, false),
3987  NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
3988 {
3989  assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
3990  for (unsigned i = 0; i != args.size(); i++) {
3991  if (args[i]->isTypeDependent())
3992  ExprBits.TypeDependent = true;
3993  if (args[i]->isValueDependent())
3994  ExprBits.ValueDependent = true;
3995  if (args[i]->isInstantiationDependent())
3996  ExprBits.InstantiationDependent = true;
3997  if (args[i]->containsUnexpandedParameterPack())
3998  ExprBits.ContainsUnexpandedParameterPack = true;
3999 
4000  SubExprs[i] = args[i];
4001  }
4002 }
4003 
4005  switch (Op) {
4006  case AO__c11_atomic_init:
4007  case AO__opencl_atomic_init:
4008  case AO__c11_atomic_load:
4009  case AO__atomic_load_n:
4010  return 2;
4011 
4012  case AO__opencl_atomic_load:
4013  case AO__c11_atomic_store:
4014  case AO__c11_atomic_exchange:
4015  case AO__atomic_load:
4016  case AO__atomic_store:
4017  case AO__atomic_store_n:
4018  case AO__atomic_exchange_n:
4019  case AO__c11_atomic_fetch_add:
4020  case AO__c11_atomic_fetch_sub:
4021  case AO__c11_atomic_fetch_and:
4022  case AO__c11_atomic_fetch_or:
4023  case AO__c11_atomic_fetch_xor:
4024  case AO__atomic_fetch_add:
4025  case AO__atomic_fetch_sub:
4026  case AO__atomic_fetch_and:
4027  case AO__atomic_fetch_or:
4028  case AO__atomic_fetch_xor:
4029  case AO__atomic_fetch_nand:
4030  case AO__atomic_add_fetch:
4031  case AO__atomic_sub_fetch:
4032  case AO__atomic_and_fetch:
4033  case AO__atomic_or_fetch:
4034  case AO__atomic_xor_fetch:
4035  case AO__atomic_nand_fetch:
4036  return 3;
4037 
4038  case AO__opencl_atomic_store:
4039  case AO__opencl_atomic_exchange:
4040  case AO__opencl_atomic_fetch_add:
4041  case AO__opencl_atomic_fetch_sub:
4042  case AO__opencl_atomic_fetch_and:
4043  case AO__opencl_atomic_fetch_or:
4044  case AO__opencl_atomic_fetch_xor:
4045  case AO__opencl_atomic_fetch_min:
4046  case AO__opencl_atomic_fetch_max:
4047  case AO__atomic_exchange:
4048  return 4;
4049 
4050  case AO__c11_atomic_compare_exchange_strong:
4051  case AO__c11_atomic_compare_exchange_weak:
4052  return 5;
4053 
4054  case AO__opencl_atomic_compare_exchange_strong:
4055  case AO__opencl_atomic_compare_exchange_weak:
4056  case AO__atomic_compare_exchange:
4057  case AO__atomic_compare_exchange_n:
4058  return 6;
4059  }
4060  llvm_unreachable("unknown atomic op");
4061 }
4062 
4064  auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4065  if (auto AT = T->getAs<AtomicType>())
4066  return AT->getValueType();
4067  return T;
4068 }
4069 
4071  unsigned ArraySectionCount = 0;
4072  while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4073  Base = OASE->getBase();
4074  ++ArraySectionCount;
4075  }
4076  while (auto *ASE =
4077  dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4078  Base = ASE->getBase();
4079  ++ArraySectionCount;
4080  }
4081  Base = Base->IgnoreParenImpCasts();
4082  auto OriginalTy = Base->getType();
4083  if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4084  if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4085  OriginalTy = PVD->getOriginalType().getNonReferenceType();
4086 
4087  for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4088  if (OriginalTy->isAnyPointerType())
4089  OriginalTy = OriginalTy->getPointeeType();
4090  else {
4091  assert (OriginalTy->isArrayType());
4092  OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4093  }
4094  }
4095  return OriginalTy;
4096 }
child_iterator child_begin()
Definition: Stmt.h:452
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:577
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:3976
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:4181
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
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
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:1175
An instance of this class is created to represent a function declaration or definition.
Definition: Decl.h:1697
Expr * getArrayIndex(const Designator &D) const
Definition: Expr.cpp:3798
Stmt * body_back()
Definition: Stmt.h:628
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:549
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:3314
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
Definition: Expr.h:5013
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:77
SourceLocation getRParenLoc() const
Definition: Expr.h:2345
void setArrayFiller(Expr *filler)
Definition: Expr.cpp:1909
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition: Expr.cpp:2005
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2285
QualType getPointeeType() const
Definition: Type.h:2298
A (possibly-)qualified type.
Definition: Type.h:653
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:5993
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:965
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:831
unsigned FieldLoc
The location of the field name in the designated initializer.
Definition: Expr.h:4158
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.h:4288
const Expr * getInit(unsigned Init) const
Definition: Expr.h:3920
Stmt - This represents one statement.
Definition: Stmt.h:66
DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, Expr *baseExprs, SourceLocation rBraceLoc)
Definition: Expr.cpp:3842
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:3058
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:456
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:3263
bool isRecordType() const
Definition: Type.h:6017
reverse_iterator rbegin()
Definition: ASTVector.h:103
Expr * getBase() const
Definition: Expr.h:2477
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:270
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:6158
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:86
bool hasUnusedResultAttr() const
Returns true if this function or its return type has the warn_unused_result attribute.
Definition: Decl.h:2227
FloatingLiteralBitfields FloatingLiteralBits
Definition: Stmt.h:290
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition: Expr.cpp:3550
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:1933
Defines the C++ template declaration subclasses.
Opcode getOpcode() const
Definition: Expr.h:3026
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:219
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:1353
bool isSemanticForm() const
Definition: Expr.h:4022
llvm::iterator_range< child_iterator > child_range
Definition: Stmt.h:443
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2560
DeclRefExprBitfields DeclRefExprBits
Definition: Stmt.h:292
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1239
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:133
SourceLocation getLParenLoc() const
Definition: Expr.h:2948
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:671
A container of type source information.
Definition: Decl.h:86
bool containsDuplicateElements() const
containsDuplicateElements - Return true if any element access is repeated.
Definition: Expr.cpp:3529
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:2397
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4035
Expr * ignoreParenBaseCasts() LLVM_READONLY
Ignore parentheses and derived-to-base casts.
Definition: Expr.cpp:2535
QualType getElementType() const
Definition: Type.h:2595
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:3882
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:806
const ObjCPropertyRefExpr * getObjCProperty() const
If this expression is an l-value for an Objective C property, find the underlying property reference ...
Definition: Expr.cpp:3394
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2637
bool isEnumeralType() const
Definition: Type.h:6021
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 internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6307
MangleContext * createMangleContext()
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type...
Definition: Type.h:6379
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition: Expr.cpp:1893
void setInit(unsigned Init, Expr *expr)
Definition: Expr.h:3930
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT, StringLiteral *SL)
Definition: Expr.cpp:461
size_type size() const
Definition: ASTVector.h:109
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition: Expr.cpp:1956
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:68
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:3000
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3108
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:3432
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:265
LabelStmt - Represents a label, which has a substatement.
Definition: Stmt.h:839
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3478
Represents a C99 designated initializer expression.
Definition: Expr.h:4106
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:291
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:255
StmtIterator cast_away_const(const ConstStmtIterator &RHS)
Definition: StmtIterator.h:152
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:149
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:1750
field_range fields() const
Definition: Decl.h:3609
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:2457
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:3743
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:96
bool isReferenceType() const
Definition: Type.h:5956
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:2761
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition: Expr.cpp:3518
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:6221
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:4191
const Expr *const * const_semantics_iterator
Definition: Expr.h:5036
ShuffleVectorExpr(const ASTContext &C, ArrayRef< Expr *> args, QualType Type, SourceLocation BLoc, SourceLocation RP)
Definition: Expr.cpp:3582
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:507
StringRef getOpcodeStr() const
Definition: Expr.h:3045
bool isGLValue() const
Definition: Expr.h:252
Describes an C or C++ initializer list.
Definition: Expr.h:3872
const TemplateArgumentList * TemplateArguments
The template arguments used to produce the function template specialization from the function templat...
Definition: DeclTemplate.h:539
void setValue(const ASTContext &C, const llvm::APInt &Val)
Definition: Expr.h:1280
BinaryOperatorKind
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1309
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:546
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:5135
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:6356
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:1635
static bool isRecordType(QualType T)
semantics_iterator semantics_end()
Definition: Expr.h:5043
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2985
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5790
child_range children()
Definition: Expr.h:4055
bool isBoundMemberFunction(ASTContext &Ctx) const
Returns true if this expression is a bound member function.
Definition: Expr.cpp:2404
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2465
const char * getCastKindName() const
Definition: Expr.cpp:1636
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
Definition: Type.h:1008
field_iterator field_begin() const
Definition: Decl.cpp:3937
SourceLocation getCaretLocation() const
Definition: Expr.cpp:2011
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
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1196
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1215
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:1580
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1404
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:3856
Represents an ObjC class declaration.
Definition: DeclObjC.h:1191
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:713
Expression is a GNU-style __null constant.
Definition: Expr.h:691
StmtClass
Definition: Stmt.h:68
const Stmt * getBody() const
Definition: Expr.cpp:2014
A binding in a decomposition declaration.
Definition: DeclCXX.h:3718
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:1042
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:3414
ParenListExpr(const ASTContext &C, SourceLocation lparenloc, ArrayRef< Expr *> exprs, SourceLocation rparenloc)
Definition: Expr.cpp:3861
Represents the this expression in C++.
Definition: ExprCXX.h:945
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, Expr *LHS, Expr *RHS)
Definition: Expr.cpp:1834
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:638
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:2911
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:535
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3269
llvm::iterator_range< const_child_iterator > const_child_range
Definition: Stmt.h:444
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:595
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1590
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3270
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:2585
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1302
CastKind
CastKind - The kind of operation required for a conversion.
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Stmt.cpp:290
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:99
InitListExpr * getUpdater() const
Definition: Expr.h:4458
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.
ConstStmtIterator const_child_iterator
Definition: Stmt.h:441
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:2942
Exposes information about the current target.
Definition: TargetInfo.h:54
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:432
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:4282
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:627
Expr - This represents one expression.
Definition: Expr.h:106
void setDesignators(const ASTContext &C, const Designator *Desigs, unsigned NumDesigs)
Definition: Expr.cpp:3762
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:3779
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
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6370
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:2620
unsigned getNumInits() const
Definition: Expr.h:3902
const Expr * getCallee() const
Definition: Expr.h:2249
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:1985
const Expr * skipRValueSubobjectAdjustments() const
Definition: Expr.h:847
field_iterator field_end() const
Definition: Decl.h:3612
child_range children()
Definition: Expr.h:4647
DeclContext * getDeclContext()
Definition: DeclBase.h:425
ExprBitfields ExprBits
Definition: Stmt.h:288
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:3854
ArrayRef< Expr * > inits()
Definition: Expr.h:3912
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:2659
Base object dtor.
Definition: ABI.h:37
QualType getType() const
Definition: Expr.h:128
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1331
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:903
InitListExpr(const ASTContext &C, SourceLocation lbraceloc, ArrayRef< Expr *> initExprs, SourceLocation rbraceloc)
Definition: Expr.cpp:1866
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:4165
Represents a GCC generic vector type.
Definition: Type.h:2916
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3838
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1026
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:1347
The result type of a method or function.
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2001
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:2922
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:444
reverse_iterator rend()
Definition: ASTVector.h:105
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:1511
do v
Definition: arm_acle.h:78
const SourceManager & SM
Definition: Format.cpp:1337
__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:137
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:3988
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:126
Expr * IgnoreCasts() LLVM_READONLY
Ignore casts. Strip off any CastExprs, returning their operand.
Definition: Expr.cpp:2487
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:2574
AtomicExpr(SourceLocation BLoc, ArrayRef< Expr *> args, QualType t, AtomicOp op, SourceLocation RP)
Definition: Expr.cpp:3983
unsigned DotLoc
The location of the &#39;.&#39; in the designated initializer.
Definition: Expr.h:4155
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:338
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:3817
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:4455
#define false
Definition: stdbool.h:33
Kind
QualType getCanonicalType() const
Definition: Type.h:5759
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:4969
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:3275
Encodes a location in the source.
QualType getReturnType() const
Definition: Type.h:3203
SourceLocation getOperatorLoc() const
Definition: Expr.h:3023
PseudoObjectExprBitfields PseudoObjectExprBits
Definition: Stmt.h:296
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:5836
Expression is not a Null pointer constant.
Definition: Expr.h:675
Expr * getSubExpr() const
Definition: Expr.h:1744
CastKind getCastKind() const
Definition: Expr.h:2757
static const FieldDecl * getTargetFieldForToUnionCast(QualType unionType, QualType opType)
Definition: Expr.cpp:1698
ObjCMethodFamily getMethodFamily() const
Definition: ExprObjC.h:1321
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:164
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:365
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:2594
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:1722
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1964
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2321
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2184
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:996
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:1897
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:1304
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2822
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:2410
Expr ** getInits()
Retrieve the set of initializers.
Definition: Expr.h:3905
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition: Expr.cpp:3478
static DesignatedInitExpr * CreateEmpty(const ASTContext &C, unsigned NumIndexExprs)
Definition: Expr.cpp:3755
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:3803
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1302
bool isVectorType() const
Definition: Type.h:6029
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1312
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1967
unsigned LBracketLoc
The location of the &#39;[&#39; starting the array range designator.
Definition: Expr.h:4167
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:3966
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:450
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
void sawArrayRangeDesignator(bool ARD=true)
Definition: Expr.h:4043
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2214
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:1866
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:325
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:3029
A POD class for pairing a NamedDecl* with an access specifier.
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:650
Represents a C11 generic selection.
Definition: Expr.h:4684
SourceRange getDesignatorsSourceRange() const
Definition: Expr.cpp:3771
StreamedQualTypeHelper stream(const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
Definition: Type.h:1041
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:1252
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:106
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
A field designator, e.g., ".x".
Definition: Expr.h:4145
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:3606
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
AccessSpecifier getAccess() const
Definition: DeclBase.h:460
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:3282
StmtClass getStmtClass() const
Definition: Stmt.h:378
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2085
bool isBooleanType() const
Definition: Type.h:6234
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:3853
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:341
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr *> semantic, unsigned resultIndex)
Definition: Expr.cpp:3907
void setInstantiationDependent(bool ID)
Set whether this expression is instantiation-dependent or not.
Definition: Expr.h:196
const T * const_iterator
Definition: ASTVector.h:86
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:2504
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:3522
semantics_iterator semantics_begin()
Definition: Expr.h:5037
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:2888
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:1596
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2552
Expr * getArrayRangeEnd(const Designator &D) const
Definition: Expr.cpp:3809
llvm::APInt getValue() const
Definition: Expr.h:1279
unsigned getNumSubExprs() const
Definition: Expr.h:5168
Decl * getCalleeDecl()
Definition: Expr.cpp:1220
Pointer to a block type.
Definition: Type.h:2387
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:3614
bool isStringLiteralInit() const
Definition: Expr.cpp:1919
struct ArrayOrRangeDesignator ArrayOrRange
An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
Definition: Expr.h:4193
unsigned getIntWidth(QualType T) const
Not an overloaded operator.
Definition: OperatorKinds.h:23
bool isIncompleteArrayType() const
Definition: Type.h:6001
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:3978
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:450
bool body_empty() const
Definition: Stmt.h:618
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2121
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:3794
static StringRef getIdentTypeName(IdentType IT)
Definition: Expr.cpp:473
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6193
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:2753
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:5940
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:2512
Opcode getOpcode() const
Definition: Expr.h:1741
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1365
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:1335
UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits
Definition: Stmt.h:291
Represents a base class of a C++ class.
Definition: DeclCXX.h:191
iterator begin()
Definition: ASTVector.h:97
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2007
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2174
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:517
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1113
A template argument list.
Definition: DeclTemplate.h:210
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:2633
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:3857
bool refersToGlobalRegisterVar() const
Returns whether this expression refers to a global register variable.
Definition: Expr.cpp:3504
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:2030
void reserve(const ASTContext &C, unsigned N)
Definition: ASTVector.h:173
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:656
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2387
CallingConv getCallConv() const
Definition: Type.h:3213
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
bool isVoidType() const
Definition: Type.h:6171
bool isSyntacticForm() const
Definition: Expr.h:4026
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2852
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition: Expr.cpp:4070
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:3664
static bool hasAnyTypeDependentArguments(ArrayRef< Expr *> Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:2745
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr.type.conv]).
Definition: ExprCXX.h:1471
Expr * getRHS() const
Definition: Expr.h:3315
bool isPRValue() const
Definition: Expr.h:355
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:539
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:265
bool isImplicitCXXThis() const
Whether this expression is an implicit reference to &#39;this&#39; in C++.
Definition: Expr.cpp:2701
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:4317
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:270
void reserveInits(const ASTContext &C, unsigned NumInits)
Reserve space for some number of initializers.
Definition: Expr.cpp:1888
capture_iterator capture_begin() const
Retrieve an iterator pointing to the first lambda capture.
Definition: ExprCXX.cpp:961
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:915
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:1860
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...
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition: ASTVector.h:88
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
bool isUnion() const
Definition: Decl.h:3155
Expr * getRHS() const
Definition: Expr.h:3031
bool isPointerType() const
Definition: Type.h:5944
CallExprBitfields CallExprBits
Definition: Stmt.h:294
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:1809
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:3984
bool isDefaultArgument() const
Determine whether this expression is a default function argument.
Definition: Expr.cpp:2620
bool isOBJCGCCandidate(ASTContext &Ctx) const
isOBJCGCCandidate - Return true if this expression may be used in a read/ write barrier.
Definition: Expr.cpp:2365
QualType getType() const
Definition: Decl.h:638
#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:1362
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:245
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:2719
static int getAccessorIdx(char c, bool isNumericAccessor)
Definition: Type.h:3035
QualType getValueType() const
Definition: Expr.cpp:4063
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:1194
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:2906
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:277
const LangOptions & getLangOpts() const
Definition: ASTContext.h:688
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration...
Definition: DeclObjC.h:2518
IdentifierInfo * getFieldName() const
Definition: Expr.cpp:3669
This class handles loading and caching of source files into memory.
InitListExpr * getSyntacticForm() const
Definition: Expr.h:4029
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:97
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:2434
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:4291
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1497