clang  14.0.0git
Expr.cpp
Go to the documentation of this file.
1 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr class and subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/Expr.h"
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/IgnoreExpr.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/AST/RecordLayout.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/CharInfo.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/Lexer.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cstring>
39 using namespace clang;
40 
42  const Expr *E = this;
43  while (true) {
44  E = E->IgnoreParenBaseCasts();
45 
46  // Follow the RHS of a comma operator.
47  if (auto *BO = dyn_cast<BinaryOperator>(E)) {
48  if (BO->getOpcode() == BO_Comma) {
49  E = BO->getRHS();
50  continue;
51  }
52  }
53 
54  // Step into initializer for materialized temporaries.
55  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
56  E = MTE->getSubExpr();
57  continue;
58  }
59 
60  break;
61  }
62 
63  return E;
64 }
65 
67  const Expr *E = getBestDynamicClassTypeExpr();
68  QualType DerivedType = E->getType();
69  if (const PointerType *PTy = DerivedType->getAs<PointerType>())
70  DerivedType = PTy->getPointeeType();
71 
72  if (DerivedType->isDependentType())
73  return nullptr;
74 
75  const RecordType *Ty = DerivedType->castAs<RecordType>();
76  Decl *D = Ty->getDecl();
77  return cast<CXXRecordDecl>(D);
78 }
79 
82  SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
83  const Expr *E = this;
84  while (true) {
85  E = E->IgnoreParens();
86 
87  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
88  if ((CE->getCastKind() == CK_DerivedToBase ||
89  CE->getCastKind() == CK_UncheckedDerivedToBase) &&
90  E->getType()->isRecordType()) {
91  E = CE->getSubExpr();
92  auto *Derived =
93  cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
94  Adjustments.push_back(SubobjectAdjustment(CE, Derived));
95  continue;
96  }
97 
98  if (CE->getCastKind() == CK_NoOp) {
99  E = CE->getSubExpr();
100  continue;
101  }
102  } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
103  if (!ME->isArrow()) {
104  assert(ME->getBase()->getType()->isRecordType());
105  if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
106  if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
107  E = ME->getBase();
108  Adjustments.push_back(SubobjectAdjustment(Field));
109  continue;
110  }
111  }
112  }
113  } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
114  if (BO->getOpcode() == BO_PtrMemD) {
115  assert(BO->getRHS()->isPRValue());
116  E = BO->getLHS();
117  const MemberPointerType *MPT =
118  BO->getRHS()->getType()->getAs<MemberPointerType>();
119  Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
120  continue;
121  }
122  if (BO->getOpcode() == BO_Comma) {
123  CommaLHSs.push_back(BO->getLHS());
124  E = BO->getRHS();
125  continue;
126  }
127  }
128 
129  // Nothing changed.
130  break;
131  }
132  return E;
133 }
134 
135 bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
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(Semantic);
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  // FIXME: Should we look through any cast expression in !Semantic mode?
157  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
158  return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
159 
160  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
161  switch (BO->getOpcode()) {
162  default: return false;
163  case BO_LT: // Relational operators.
164  case BO_GT:
165  case BO_LE:
166  case BO_GE:
167  case BO_EQ: // Equality operators.
168  case BO_NE:
169  case BO_LAnd: // AND operator.
170  case BO_LOr: // Logical OR operator.
171  return true;
172 
173  case BO_And: // Bitwise AND operator.
174  case BO_Xor: // Bitwise XOR operator.
175  case BO_Or: // Bitwise OR operator.
176  // Handle things like (x==2)|(y==12).
177  return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
178  BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
179 
180  case BO_Comma:
181  case BO_Assign:
182  return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
183  }
184  }
185 
186  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
187  return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
188  CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
189 
190  if (isa<ObjCBoolLiteralExpr>(E))
191  return true;
192 
193  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
194  return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
195 
196  if (const FieldDecl *FD = E->getSourceBitField())
197  if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
198  !FD->getBitWidth()->isValueDependent() &&
199  FD->getBitWidthValue(FD->getASTContext()) == 1)
200  return true;
201 
202  return false;
203 }
204 
205 // Amusing macro metaprogramming hack: check whether a class provides
206 // a more specific implementation of getExprLoc().
207 //
208 // See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
209 namespace {
210  /// This implementation is used when a class provides a custom
211  /// implementation of getExprLoc.
212  template <class E, class T>
213  SourceLocation getExprLocImpl(const Expr *expr,
214  SourceLocation (T::*v)() const) {
215  return static_cast<const E*>(expr)->getExprLoc();
216  }
217 
218  /// This implementation is used when a class doesn't provide
219  /// a custom implementation of getExprLoc. Overload resolution
220  /// should pick it over the implementation above because it's
221  /// more specialized according to function template partial ordering.
222  template <class E>
223  SourceLocation getExprLocImpl(const Expr *expr,
224  SourceLocation (Expr::*v)() const) {
225  return static_cast<const E *>(expr)->getBeginLoc();
226  }
227 }
228 
230  switch (getStmtClass()) {
231  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
232 #define ABSTRACT_STMT(type)
233 #define STMT(type, base) \
234  case Stmt::type##Class: break;
235 #define EXPR(type, base) \
236  case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
237 #include "clang/AST/StmtNodes.inc"
238  }
239  llvm_unreachable("unknown expression kind");
240 }
241 
242 //===----------------------------------------------------------------------===//
243 // Primary Expressions.
244 //===----------------------------------------------------------------------===//
245 
247  assert((Kind == ConstantExpr::RSK_APValue ||
249  "Invalid StorageKind Value");
250  (void)Kind;
251 }
252 
255  switch (Value.getKind()) {
256  case APValue::None:
258  return ConstantExpr::RSK_None;
259  case APValue::Int:
260  if (!Value.getInt().needsCleanup())
262  LLVM_FALLTHROUGH;
263  default:
265  }
266 }
267 
269 ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
270  if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
273 }
274 
275 ConstantExpr::ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
276  bool IsImmediateInvocation)
277  : FullExpr(ConstantExprClass, SubExpr) {
278  ConstantExprBits.ResultKind = StorageKind;
279  ConstantExprBits.APValueKind = APValue::None;
280  ConstantExprBits.IsUnsigned = false;
281  ConstantExprBits.BitWidth = 0;
282  ConstantExprBits.HasCleanup = false;
283  ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
284 
285  if (StorageKind == ConstantExpr::RSK_APValue)
286  ::new (getTrailingObjects<APValue>()) APValue();
287 }
288 
290  ResultStorageKind StorageKind,
291  bool IsImmediateInvocation) {
292  assert(!isa<ConstantExpr>(E));
293  AssertResultStorageKind(StorageKind);
294 
295  unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
296  StorageKind == ConstantExpr::RSK_APValue,
297  StorageKind == ConstantExpr::RSK_Int64);
298  void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
299  return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
300 }
301 
303  const APValue &Result) {
304  ResultStorageKind StorageKind = getStorageKind(Result);
305  ConstantExpr *Self = Create(Context, E, StorageKind);
306  Self->SetResult(Result, Context);
307  return Self;
308 }
309 
310 ConstantExpr::ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind)
311  : FullExpr(ConstantExprClass, Empty) {
312  ConstantExprBits.ResultKind = StorageKind;
313 
314  if (StorageKind == ConstantExpr::RSK_APValue)
315  ::new (getTrailingObjects<APValue>()) APValue();
316 }
317 
319  ResultStorageKind StorageKind) {
320  AssertResultStorageKind(StorageKind);
321 
322  unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
323  StorageKind == ConstantExpr::RSK_APValue,
324  StorageKind == ConstantExpr::RSK_Int64);
325  void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
326  return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
327 }
328 
330  assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
331  "Invalid storage for this value kind");
332  ConstantExprBits.APValueKind = Value.getKind();
333  switch (ConstantExprBits.ResultKind) {
334  case RSK_None:
335  return;
336  case RSK_Int64:
337  Int64Result() = *Value.getInt().getRawData();
338  ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
339  ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
340  return;
341  case RSK_APValue:
342  if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
343  ConstantExprBits.HasCleanup = true;
344  Context.addDestruction(&APValueResult());
345  }
346  APValueResult() = std::move(Value);
347  return;
348  }
349  llvm_unreachable("Invalid ResultKind Bits");
350 }
351 
353  switch (ConstantExprBits.ResultKind) {
355  return APValueResult().getInt();
357  return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
358  ConstantExprBits.IsUnsigned);
359  default:
360  llvm_unreachable("invalid Accessor");
361  }
362 }
363 
365 
366  switch (ConstantExprBits.ResultKind) {
368  return APValueResult();
370  return APValue(
371  llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
372  ConstantExprBits.IsUnsigned));
374  if (ConstantExprBits.APValueKind == APValue::Indeterminate)
376  return APValue();
377  }
378  llvm_unreachable("invalid ResultKind");
379 }
380 
381 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
382  bool RefersToEnclosingVariableOrCapture, QualType T,
384  const DeclarationNameLoc &LocInfo,
385  NonOdrUseReason NOUR)
386  : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
387  DeclRefExprBits.HasQualifier = false;
388  DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
389  DeclRefExprBits.HasFoundDecl = false;
390  DeclRefExprBits.HadMultipleCandidates = false;
391  DeclRefExprBits.RefersToEnclosingVariableOrCapture =
392  RefersToEnclosingVariableOrCapture;
393  DeclRefExprBits.NonOdrUseReason = NOUR;
394  DeclRefExprBits.Loc = L;
395  setDependence(computeDependence(this, Ctx));
396 }
397 
398 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
399  NestedNameSpecifierLoc QualifierLoc,
400  SourceLocation TemplateKWLoc, ValueDecl *D,
401  bool RefersToEnclosingVariableOrCapture,
402  const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
403  const TemplateArgumentListInfo *TemplateArgs,
405  : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
406  DNLoc(NameInfo.getInfo()) {
407  DeclRefExprBits.Loc = NameInfo.getLoc();
408  DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
409  if (QualifierLoc)
410  new (getTrailingObjects<NestedNameSpecifierLoc>())
411  NestedNameSpecifierLoc(QualifierLoc);
412  DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
413  if (FoundD)
414  *getTrailingObjects<NamedDecl *>() = FoundD;
415  DeclRefExprBits.HasTemplateKWAndArgsInfo
416  = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
417  DeclRefExprBits.RefersToEnclosingVariableOrCapture =
418  RefersToEnclosingVariableOrCapture;
419  DeclRefExprBits.NonOdrUseReason = NOUR;
420  if (TemplateArgs) {
422  getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
423  TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
424  Deps);
425  assert(!(Deps & TemplateArgumentDependence::Dependent) &&
426  "built a DeclRefExpr with dependent template args");
427  } else if (TemplateKWLoc.isValid()) {
428  getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
429  TemplateKWLoc);
430  }
431  DeclRefExprBits.HadMultipleCandidates = 0;
432  setDependence(computeDependence(this, Ctx));
433 }
434 
436  NestedNameSpecifierLoc QualifierLoc,
437  SourceLocation TemplateKWLoc, ValueDecl *D,
438  bool RefersToEnclosingVariableOrCapture,
439  SourceLocation NameLoc, QualType T,
440  ExprValueKind VK, NamedDecl *FoundD,
441  const TemplateArgumentListInfo *TemplateArgs,
442  NonOdrUseReason NOUR) {
443  return Create(Context, QualifierLoc, TemplateKWLoc, D,
444  RefersToEnclosingVariableOrCapture,
445  DeclarationNameInfo(D->getDeclName(), NameLoc),
446  T, VK, FoundD, TemplateArgs, NOUR);
447 }
448 
450  NestedNameSpecifierLoc QualifierLoc,
451  SourceLocation TemplateKWLoc, ValueDecl *D,
452  bool RefersToEnclosingVariableOrCapture,
453  const DeclarationNameInfo &NameInfo,
454  QualType T, ExprValueKind VK,
455  NamedDecl *FoundD,
456  const TemplateArgumentListInfo *TemplateArgs,
457  NonOdrUseReason NOUR) {
458  // Filter out cases where the found Decl is the same as the value refenenced.
459  if (D == FoundD)
460  FoundD = nullptr;
461 
462  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
463  std::size_t Size =
464  totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
466  QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
467  HasTemplateKWAndArgsInfo ? 1 : 0,
468  TemplateArgs ? TemplateArgs->size() : 0);
469 
470  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
471  return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
472  RefersToEnclosingVariableOrCapture, NameInfo,
473  FoundD, TemplateArgs, T, VK, NOUR);
474 }
475 
477  bool HasQualifier,
478  bool HasFoundDecl,
479  bool HasTemplateKWAndArgsInfo,
480  unsigned NumTemplateArgs) {
481  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
482  std::size_t Size =
483  totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
485  HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
486  NumTemplateArgs);
487  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
488  return new (Mem) DeclRefExpr(EmptyShell());
489 }
490 
492  D = NewD;
493  if (getType()->isUndeducedType())
494  setType(NewD->getType());
496 }
497 
499  if (hasQualifier())
500  return getQualifierLoc().getBeginLoc();
501  return getNameInfo().getBeginLoc();
502 }
505  return getRAngleLoc();
506  return getNameInfo().getEndLoc();
507 }
508 
509 SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,
510  SourceLocation LParen,
511  SourceLocation RParen,
512  QualType ResultTy,
513  TypeSourceInfo *TSI)
514  : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),
515  OpLoc(OpLoc), LParen(LParen), RParen(RParen) {
516  setTypeSourceInfo(TSI);
518 }
519 
520 SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
521  QualType ResultTy)
522  : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
523 
526  SourceLocation LParen, SourceLocation RParen,
527  TypeSourceInfo *TSI) {
528  QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
529  return new (Ctx)
530  SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);
531 }
532 
535  QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
536  return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
537 }
538 
542 }
543 
545  QualType Ty) {
546  auto MangleCallback = [](ASTContext &Ctx,
547  const NamedDecl *ND) -> llvm::Optional<unsigned> {
548  // This replaces the 'lambda number' in the mangling with a unique number
549  // based on its order in the declaration. To provide some level of visual
550  // notability (actual uniqueness from normal lambdas isn't necessary, as
551  // these are used differently), we add 10,000 to the number.
552  // For example:
553  // _ZTSZ3foovEUlvE10005_
554  // Demangles to: typeinfo name for foo()::'lambda10005'()
555  // Note that the mangler subtracts 2, since with normal lambdas the lambda
556  // mangling number '0' is an anonymous struct mangle, and '1' is omitted.
557  // So 10,002 results in the first number being 10,000.
558  if (Ctx.IsSYCLKernelNamingDecl(ND))
559  return 10'002 + Ctx.GetSYCLKernelNamingIndex(ND);
560  return llvm::None;
561  };
562  std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
563  Context, Context.getDiagnostics(), MangleCallback)};
564 
565  std::string Buffer;
566  Buffer.reserve(128);
567  llvm::raw_string_ostream Out(Buffer);
568  Ctx->mangleTypeName(Ty, Out);
569 
570  return Out.str();
571 }
572 
573 PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
574  StringLiteral *SL)
575  : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
576  PredefinedExprBits.Kind = IK;
577  assert((getIdentKind() == IK) &&
578  "IdentKind do not fit in PredefinedExprBitfields!");
579  bool HasFunctionName = SL != nullptr;
580  PredefinedExprBits.HasFunctionName = HasFunctionName;
581  PredefinedExprBits.Loc = L;
582  if (HasFunctionName)
583  setFunctionName(SL);
584  setDependence(computeDependence(this));
585 }
586 
587 PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
588  : Expr(PredefinedExprClass, Empty) {
589  PredefinedExprBits.HasFunctionName = HasFunctionName;
590 }
591 
592 PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
593  QualType FNTy, IdentKind IK,
594  StringLiteral *SL) {
595  bool HasFunctionName = SL != nullptr;
596  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
597  alignof(PredefinedExpr));
598  return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
599 }
600 
601 PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
602  bool HasFunctionName) {
603  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
604  alignof(PredefinedExpr));
605  return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
606 }
607 
608 StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
609  switch (IK) {
610  case Func:
611  return "__func__";
612  case Function:
613  return "__FUNCTION__";
614  case FuncDName:
615  return "__FUNCDNAME__";
616  case LFunction:
617  return "L__FUNCTION__";
618  case PrettyFunction:
619  return "__PRETTY_FUNCTION__";
620  case FuncSig:
621  return "__FUNCSIG__";
622  case LFuncSig:
623  return "L__FUNCSIG__";
624  case PrettyFunctionNoVirtual:
625  break;
626  }
627  llvm_unreachable("Unknown ident kind for PredefinedExpr");
628 }
629 
630 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
631 // expr" policy instead.
632 std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
633  ASTContext &Context = CurrentDecl->getASTContext();
634 
635  if (IK == PredefinedExpr::FuncDName) {
636  if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
637  std::unique_ptr<MangleContext> MC;
638  MC.reset(Context.createMangleContext());
639 
640  if (MC->shouldMangleDeclName(ND)) {
641  SmallString<256> Buffer;
642  llvm::raw_svector_ostream Out(Buffer);
643  GlobalDecl GD;
644  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
645  GD = GlobalDecl(CD, Ctor_Base);
646  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
647  GD = GlobalDecl(DD, Dtor_Base);
648  else if (ND->hasAttr<CUDAGlobalAttr>())
649  GD = GlobalDecl(cast<FunctionDecl>(ND));
650  else
651  GD = GlobalDecl(ND);
652  MC->mangleName(GD, Out);
653 
654  if (!Buffer.empty() && Buffer.front() == '\01')
655  return std::string(Buffer.substr(1));
656  return std::string(Buffer.str());
657  }
658  return std::string(ND->getIdentifier()->getName());
659  }
660  return "";
661  }
662  if (isa<BlockDecl>(CurrentDecl)) {
663  // For blocks we only emit something if it is enclosed in a function
664  // For top-level block we'd like to include the name of variable, but we
665  // don't have it at this point.
666  auto DC = CurrentDecl->getDeclContext();
667  if (DC->isFileContext())
668  return "";
669 
670  SmallString<256> Buffer;
671  llvm::raw_svector_ostream Out(Buffer);
672  if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
673  // For nested blocks, propagate up to the parent.
674  Out << ComputeName(IK, DCBlock);
675  else if (auto *DCDecl = dyn_cast<Decl>(DC))
676  Out << ComputeName(IK, DCDecl) << "_block_invoke";
677  return std::string(Out.str());
678  }
679  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
680  if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
681  IK != FuncSig && IK != LFuncSig)
682  return FD->getNameAsString();
683 
684  SmallString<256> Name;
685  llvm::raw_svector_ostream Out(Name);
686 
687  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
688  if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
689  Out << "virtual ";
690  if (MD->isStatic())
691  Out << "static ";
692  }
693 
694  PrintingPolicy Policy(Context.getLangOpts());
695  std::string Proto;
696  llvm::raw_string_ostream POut(Proto);
697 
698  const FunctionDecl *Decl = FD;
699  if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
700  Decl = Pattern;
701  const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
702  const FunctionProtoType *FT = nullptr;
703  if (FD->hasWrittenPrototype())
704  FT = dyn_cast<FunctionProtoType>(AFT);
705 
706  if (IK == FuncSig || IK == LFuncSig) {
707  switch (AFT->getCallConv()) {
708  case CC_C: POut << "__cdecl "; break;
709  case CC_X86StdCall: POut << "__stdcall "; break;
710  case CC_X86FastCall: POut << "__fastcall "; break;
711  case CC_X86ThisCall: POut << "__thiscall "; break;
712  case CC_X86VectorCall: POut << "__vectorcall "; break;
713  case CC_X86RegCall: POut << "__regcall "; break;
714  // Only bother printing the conventions that MSVC knows about.
715  default: break;
716  }
717  }
718 
719  FD->printQualifiedName(POut, Policy);
720 
721  POut << "(";
722  if (FT) {
723  for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
724  if (i) POut << ", ";
725  POut << Decl->getParamDecl(i)->getType().stream(Policy);
726  }
727 
728  if (FT->isVariadic()) {
729  if (FD->getNumParams()) POut << ", ";
730  POut << "...";
731  } else if ((IK == FuncSig || IK == LFuncSig ||
732  !Context.getLangOpts().CPlusPlus) &&
733  !Decl->getNumParams()) {
734  POut << "void";
735  }
736  }
737  POut << ")";
738 
739  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
740  assert(FT && "We must have a written prototype in this case.");
741  if (FT->isConst())
742  POut << " const";
743  if (FT->isVolatile())
744  POut << " volatile";
745  RefQualifierKind Ref = MD->getRefQualifier();
746  if (Ref == RQ_LValue)
747  POut << " &";
748  else if (Ref == RQ_RValue)
749  POut << " &&";
750  }
751 
753  SpecsTy Specs;
754  const DeclContext *Ctx = FD->getDeclContext();
755  while (Ctx && isa<NamedDecl>(Ctx)) {
757  = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
758  if (Spec && !Spec->isExplicitSpecialization())
759  Specs.push_back(Spec);
760  Ctx = Ctx->getParent();
761  }
762 
763  std::string TemplateParams;
764  llvm::raw_string_ostream TOut(TemplateParams);
765  for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
766  I != E; ++I) {
767  const TemplateParameterList *Params
768  = (*I)->getSpecializedTemplate()->getTemplateParameters();
769  const TemplateArgumentList &Args = (*I)->getTemplateArgs();
770  assert(Params->size() == Args.size());
771  for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
772  StringRef Param = Params->getParam(i)->getName();
773  if (Param.empty()) continue;
774  TOut << Param << " = ";
775  Args.get(i).print(
776  Policy, TOut,
778  TOut << ", ";
779  }
780  }
781 
783  = FD->getTemplateSpecializationInfo();
784  if (FSI && !FSI->isExplicitSpecialization()) {
785  const TemplateParameterList* Params
787  const TemplateArgumentList* Args = FSI->TemplateArguments;
788  assert(Params->size() == Args->size());
789  for (unsigned i = 0, e = Params->size(); i != e; ++i) {
790  StringRef Param = Params->getParam(i)->getName();
791  if (Param.empty()) continue;
792  TOut << Param << " = ";
793  Args->get(i).print(Policy, TOut, /*IncludeType*/ true);
794  TOut << ", ";
795  }
796  }
797 
798  TOut.flush();
799  if (!TemplateParams.empty()) {
800  // remove the trailing comma and space
801  TemplateParams.resize(TemplateParams.size() - 2);
802  POut << " [" << TemplateParams << "]";
803  }
804 
805  POut.flush();
806 
807  // Print "auto" for all deduced return types. This includes C++1y return
808  // type deduction and lambdas. For trailing return types resolve the
809  // decltype expression. Otherwise print the real type when this is
810  // not a constructor or destructor.
811  if (isa<CXXMethodDecl>(FD) &&
812  cast<CXXMethodDecl>(FD)->getParent()->isLambda())
813  Proto = "auto " + Proto;
814  else if (FT && FT->getReturnType()->getAs<DecltypeType>())
815  FT->getReturnType()
816  ->getAs<DecltypeType>()
818  .getAsStringInternal(Proto, Policy);
819  else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
820  AFT->getReturnType().getAsStringInternal(Proto, Policy);
821 
822  Out << Proto;
823 
824  return std::string(Name);
825  }
826  if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
827  for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
828  // Skip to its enclosing function or method, but not its enclosing
829  // CapturedDecl.
830  if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
831  const Decl *D = Decl::castFromDeclContext(DC);
832  return ComputeName(IK, D);
833  }
834  llvm_unreachable("CapturedDecl not inside a function or method");
835  }
836  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
837  SmallString<256> Name;
838  llvm::raw_svector_ostream Out(Name);
839  Out << (MD->isInstanceMethod() ? '-' : '+');
840  Out << '[';
841 
842  // For incorrect code, there might not be an ObjCInterfaceDecl. Do
843  // a null check to avoid a crash.
844  if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
845  Out << *ID;
846 
847  if (const ObjCCategoryImplDecl *CID =
848  dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
849  Out << '(' << *CID << ')';
850 
851  Out << ' ';
852  MD->getSelector().print(Out);
853  Out << ']';
854 
855  return std::string(Name);
856  }
857  if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
858  // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
859  return "top level";
860  }
861  return "";
862 }
863 
865  const llvm::APInt &Val) {
866  if (hasAllocation())
867  C.Deallocate(pVal);
868 
869  BitWidth = Val.getBitWidth();
870  unsigned NumWords = Val.getNumWords();
871  const uint64_t* Words = Val.getRawData();
872  if (NumWords > 1) {
873  pVal = new (C) uint64_t[NumWords];
874  std::copy(Words, Words + NumWords, pVal);
875  } else if (NumWords == 1)
876  VAL = Words[0];
877  else
878  VAL = 0;
879 }
880 
881 IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
883  : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
884  assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
885  assert(V.getBitWidth() == C.getIntWidth(type) &&
886  "Integer type is not the correct size for constant.");
887  setValue(C, V);
889 }
890 
894  return new (C) IntegerLiteral(C, V, type, l);
895 }
896 
899  return new (C) IntegerLiteral(Empty);
900 }
901 
902 FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
904  unsigned Scale)
905  : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
906  Scale(Scale) {
907  assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
908  assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
909  "Fixed point type is not the correct size for constant.");
910  setValue(C, V);
912 }
913 
915  const llvm::APInt &V,
916  QualType type,
917  SourceLocation l,
918  unsigned Scale) {
919  return new (C) FixedPointLiteral(C, V, type, l, Scale);
920 }
921 
923  EmptyShell Empty) {
924  return new (C) FixedPointLiteral(Empty);
925 }
926 
928  // Currently the longest decimal number that can be printed is the max for an
929  // unsigned long _Accum: 4294967295.99999999976716935634613037109375
930  // which is 43 characters.
931  SmallString<64> S;
933  S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
934  return std::string(S.str());
935 }
936 
938  raw_ostream &OS) {
939  switch (Kind) {
941  break; // no prefix.
943  OS << 'L';
944  break;
946  OS << "u8";
947  break;
949  OS << 'u';
950  break;
952  OS << 'U';
953  break;
954  }
955 
956  switch (Val) {
957  case '\\':
958  OS << "'\\\\'";
959  break;
960  case '\'':
961  OS << "'\\''";
962  break;
963  case '\a':
964  // TODO: K&R: the meaning of '\\a' is different in traditional C
965  OS << "'\\a'";
966  break;
967  case '\b':
968  OS << "'\\b'";
969  break;
970  // Nonstandard escape sequence.
971  /*case '\e':
972  OS << "'\\e'";
973  break;*/
974  case '\f':
975  OS << "'\\f'";
976  break;
977  case '\n':
978  OS << "'\\n'";
979  break;
980  case '\r':
981  OS << "'\\r'";
982  break;
983  case '\t':
984  OS << "'\\t'";
985  break;
986  case '\v':
987  OS << "'\\v'";
988  break;
989  default:
990  // A character literal might be sign-extended, which
991  // would result in an invalid \U escape sequence.
992  // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
993  // are not correctly handled.
994  if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteral::Ascii)
995  Val &= 0xFFu;
996  if (Val < 256 && isPrintable((unsigned char)Val))
997  OS << "'" << (char)Val << "'";
998  else if (Val < 256)
999  OS << "'\\x" << llvm::format("%02x", Val) << "'";
1000  else if (Val <= 0xFFFF)
1001  OS << "'\\u" << llvm::format("%04x", Val) << "'";
1002  else
1003  OS << "'\\U" << llvm::format("%08x", Val) << "'";
1004  }
1005 }
1006 
1007 FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
1008  bool isexact, QualType Type, SourceLocation L)
1009  : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
1010  setSemantics(V.getSemantics());
1011  FloatingLiteralBits.IsExact = isexact;
1012  setValue(C, V);
1014 }
1015 
1016 FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
1017  : Expr(FloatingLiteralClass, Empty) {
1018  setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
1019  FloatingLiteralBits.IsExact = false;
1020 }
1021 
1023 FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
1024  bool isexact, QualType Type, SourceLocation L) {
1025  return new (C) FloatingLiteral(C, V, isexact, Type, L);
1026 }
1027 
1030  return new (C) FloatingLiteral(C, Empty);
1031 }
1032 
1033 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1034 /// double. Note that this may cause loss of precision, but is useful for
1035 /// debugging dumps, etc.
1037  llvm::APFloat V = getValue();
1038  bool ignored;
1039  V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
1040  &ignored);
1041  return V.convertToDouble();
1042 }
1043 
1044 unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1045  StringKind SK) {
1046  unsigned CharByteWidth = 0;
1047  switch (SK) {
1048  case Ascii:
1049  case UTF8:
1050  CharByteWidth = Target.getCharWidth();
1051  break;
1052  case Wide:
1053  CharByteWidth = Target.getWCharWidth();
1054  break;
1055  case UTF16:
1056  CharByteWidth = Target.getChar16Width();
1057  break;
1058  case UTF32:
1059  CharByteWidth = Target.getChar32Width();
1060  break;
1061  }
1062  assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1063  CharByteWidth /= 8;
1064  assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1065  "The only supported character byte widths are 1,2 and 4!");
1066  return CharByteWidth;
1067 }
1068 
1069 StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1070  StringKind Kind, bool Pascal, QualType Ty,
1071  const SourceLocation *Loc,
1072  unsigned NumConcatenated)
1073  : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1074  assert(Ctx.getAsConstantArrayType(Ty) &&
1075  "StringLiteral must be of constant array type!");
1076  unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1077  unsigned ByteLength = Str.size();
1078  assert((ByteLength % CharByteWidth == 0) &&
1079  "The size of the data must be a multiple of CharByteWidth!");
1080 
1081  // Avoid the expensive division. The compiler should be able to figure it
1082  // out by itself. However as of clang 7, even with the appropriate
1083  // llvm_unreachable added just here, it is not able to do so.
1084  unsigned Length;
1085  switch (CharByteWidth) {
1086  case 1:
1087  Length = ByteLength;
1088  break;
1089  case 2:
1090  Length = ByteLength / 2;
1091  break;
1092  case 4:
1093  Length = ByteLength / 4;
1094  break;
1095  default:
1096  llvm_unreachable("Unsupported character width!");
1097  }
1098 
1099  StringLiteralBits.Kind = Kind;
1100  StringLiteralBits.CharByteWidth = CharByteWidth;
1101  StringLiteralBits.IsPascal = Pascal;
1102  StringLiteralBits.NumConcatenated = NumConcatenated;
1103  *getTrailingObjects<unsigned>() = Length;
1104 
1105  // Initialize the trailing array of SourceLocation.
1106  // This is safe since SourceLocation is POD-like.
1107  std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1108  NumConcatenated * sizeof(SourceLocation));
1109 
1110  // Initialize the trailing array of char holding the string data.
1111  std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
1112 
1114 }
1115 
1116 StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1117  unsigned Length, unsigned CharByteWidth)
1118  : Expr(StringLiteralClass, Empty) {
1119  StringLiteralBits.CharByteWidth = CharByteWidth;
1120  StringLiteralBits.NumConcatenated = NumConcatenated;
1121  *getTrailingObjects<unsigned>() = Length;
1122 }
1123 
1125  StringKind Kind, bool Pascal, QualType Ty,
1126  const SourceLocation *Loc,
1127  unsigned NumConcatenated) {
1128  void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1129  1, NumConcatenated, Str.size()),
1130  alignof(StringLiteral));
1131  return new (Mem)
1132  StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1133 }
1134 
1136  unsigned NumConcatenated,
1137  unsigned Length,
1138  unsigned CharByteWidth) {
1139  void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1140  1, NumConcatenated, Length * CharByteWidth),
1141  alignof(StringLiteral));
1142  return new (Mem)
1143  StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1144 }
1145 
1146 void StringLiteral::outputString(raw_ostream &OS) const {
1147  switch (getKind()) {
1148  case Ascii: break; // no prefix.
1149  case Wide: OS << 'L'; break;
1150  case UTF8: OS << "u8"; break;
1151  case UTF16: OS << 'u'; break;
1152  case UTF32: OS << 'U'; break;
1153  }
1154  OS << '"';
1155  static const char Hex[] = "0123456789ABCDEF";
1156 
1157  unsigned LastSlashX = getLength();
1158  for (unsigned I = 0, N = getLength(); I != N; ++I) {
1159  switch (uint32_t Char = getCodeUnit(I)) {
1160  default:
1161  // FIXME: Convert UTF-8 back to codepoints before rendering.
1162 
1163  // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1164  // Leave invalid surrogates alone; we'll use \x for those.
1165  if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
1166  Char <= 0xdbff) {
1167  uint32_t Trail = getCodeUnit(I + 1);
1168  if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1169  Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1170  ++I;
1171  }
1172  }
1173 
1174  if (Char > 0xff) {
1175  // If this is a wide string, output characters over 0xff using \x
1176  // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1177  // codepoint: use \x escapes for invalid codepoints.
1178  if (getKind() == Wide ||
1179  (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1180  // FIXME: Is this the best way to print wchar_t?
1181  OS << "\\x";
1182  int Shift = 28;
1183  while ((Char >> Shift) == 0)
1184  Shift -= 4;
1185  for (/**/; Shift >= 0; Shift -= 4)
1186  OS << Hex[(Char >> Shift) & 15];
1187  LastSlashX = I;
1188  break;
1189  }
1190 
1191  if (Char > 0xffff)
1192  OS << "\\U00"
1193  << Hex[(Char >> 20) & 15]
1194  << Hex[(Char >> 16) & 15];
1195  else
1196  OS << "\\u";
1197  OS << Hex[(Char >> 12) & 15]
1198  << Hex[(Char >> 8) & 15]
1199  << Hex[(Char >> 4) & 15]
1200  << Hex[(Char >> 0) & 15];
1201  break;
1202  }
1203 
1204  // If we used \x... for the previous character, and this character is a
1205  // hexadecimal digit, prevent it being slurped as part of the \x.
1206  if (LastSlashX + 1 == I) {
1207  switch (Char) {
1208  case '0': case '1': case '2': case '3': case '4':
1209  case '5': case '6': case '7': case '8': case '9':
1210  case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1211  case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1212  OS << "\"\"";
1213  }
1214  }
1215 
1216  assert(Char <= 0xff &&
1217  "Characters above 0xff should already have been handled.");
1218 
1219  if (isPrintable(Char))
1220  OS << (char)Char;
1221  else // Output anything hard as an octal escape.
1222  OS << '\\'
1223  << (char)('0' + ((Char >> 6) & 7))
1224  << (char)('0' + ((Char >> 3) & 7))
1225  << (char)('0' + ((Char >> 0) & 7));
1226  break;
1227  // Handle some common non-printable cases to make dumps prettier.
1228  case '\\': OS << "\\\\"; break;
1229  case '"': OS << "\\\""; break;
1230  case '\a': OS << "\\a"; break;
1231  case '\b': OS << "\\b"; break;
1232  case '\f': OS << "\\f"; break;
1233  case '\n': OS << "\\n"; break;
1234  case '\r': OS << "\\r"; break;
1235  case '\t': OS << "\\t"; break;
1236  case '\v': OS << "\\v"; break;
1237  }
1238  }
1239  OS << '"';
1240 }
1241 
1242 /// getLocationOfByte - Return a source location that points to the specified
1243 /// byte of this string literal.
1244 ///
1245 /// Strings are amazingly complex. They can be formed from multiple tokens and
1246 /// can have escape sequences in them in addition to the usual trigraph and
1247 /// escaped newline business. This routine handles this complexity.
1248 ///
1249 /// The *StartToken sets the first token to be searched in this function and
1250 /// the *StartTokenByteOffset is the byte offset of the first token. Before
1251 /// returning, it updates the *StartToken to the TokNo of the token being found
1252 /// and sets *StartTokenByteOffset to the byte offset of the token in the
1253 /// string.
1254 /// Using these two parameters can reduce the time complexity from O(n^2) to
1255 /// O(n) if one wants to get the location of byte for all the tokens in a
1256 /// string.
1257 ///
1260  const LangOptions &Features,
1261  const TargetInfo &Target, unsigned *StartToken,
1262  unsigned *StartTokenByteOffset) const {
1263  assert((getKind() == StringLiteral::Ascii ||
1264  getKind() == StringLiteral::UTF8) &&
1265  "Only narrow string literals are currently supported");
1266 
1267  // Loop over all of the tokens in this string until we find the one that
1268  // contains the byte we're looking for.
1269  unsigned TokNo = 0;
1270  unsigned StringOffset = 0;
1271  if (StartToken)
1272  TokNo = *StartToken;
1273  if (StartTokenByteOffset) {
1274  StringOffset = *StartTokenByteOffset;
1275  ByteNo -= StringOffset;
1276  }
1277  while (1) {
1278  assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1279  SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1280 
1281  // Get the spelling of the string so that we can get the data that makes up
1282  // the string literal, not the identifier for the macro it is potentially
1283  // expanded through.
1284  SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1285 
1286  // Re-lex the token to get its length and original spelling.
1287  std::pair<FileID, unsigned> LocInfo =
1288  SM.getDecomposedLoc(StrTokSpellingLoc);
1289  bool Invalid = false;
1290  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1291  if (Invalid) {
1292  if (StartTokenByteOffset != nullptr)
1293  *StartTokenByteOffset = StringOffset;
1294  if (StartToken != nullptr)
1295  *StartToken = TokNo;
1296  return StrTokSpellingLoc;
1297  }
1298 
1299  const char *StrData = Buffer.data()+LocInfo.second;
1300 
1301  // Create a lexer starting at the beginning of this token.
1302  Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1303  Buffer.begin(), StrData, Buffer.end());
1304  Token TheTok;
1305  TheLexer.LexFromRawLexer(TheTok);
1306 
1307  // Use the StringLiteralParser to compute the length of the string in bytes.
1308  StringLiteralParser SLP(TheTok, SM, Features, Target);
1309  unsigned TokNumBytes = SLP.GetStringLength();
1310 
1311  // If the byte is in this token, return the location of the byte.
1312  if (ByteNo < TokNumBytes ||
1313  (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1314  unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1315 
1316  // Now that we know the offset of the token in the spelling, use the
1317  // preprocessor to get the offset in the original source.
1318  if (StartTokenByteOffset != nullptr)
1319  *StartTokenByteOffset = StringOffset;
1320  if (StartToken != nullptr)
1321  *StartToken = TokNo;
1322  return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1323  }
1324 
1325  // Move to the next string token.
1326  StringOffset += TokNumBytes;
1327  ++TokNo;
1328  ByteNo -= TokNumBytes;
1329  }
1330 }
1331 
1332 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1333 /// corresponds to, e.g. "sizeof" or "[pre]++".
1335  switch (Op) {
1336 #define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1337 #include "clang/AST/OperationKinds.def"
1338  }
1339  llvm_unreachable("Unknown unary operator");
1340 }
1341 
1344  switch (OO) {
1345  default: llvm_unreachable("No unary operator for overloaded function");
1346  case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1347  case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1348  case OO_Amp: return UO_AddrOf;
1349  case OO_Star: return UO_Deref;
1350  case OO_Plus: return UO_Plus;
1351  case OO_Minus: return UO_Minus;
1352  case OO_Tilde: return UO_Not;
1353  case OO_Exclaim: return UO_LNot;
1354  case OO_Coawait: return UO_Coawait;
1355  }
1356 }
1357 
1359  switch (Opc) {
1360  case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1361  case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1362  case UO_AddrOf: return OO_Amp;
1363  case UO_Deref: return OO_Star;
1364  case UO_Plus: return OO_Plus;
1365  case UO_Minus: return OO_Minus;
1366  case UO_Not: return OO_Tilde;
1367  case UO_LNot: return OO_Exclaim;
1368  case UO_Coawait: return OO_Coawait;
1369  default: return OO_None;
1370  }
1371 }
1372 
1373 
1374 //===----------------------------------------------------------------------===//
1375 // Postfix Operators.
1376 //===----------------------------------------------------------------------===//
1377 
1380  SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
1381  unsigned MinNumArgs, ADLCallKind UsesADL)
1382  : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1383  NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1384  unsigned NumPreArgs = PreArgs.size();
1385  CallExprBits.NumPreArgs = NumPreArgs;
1386  assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1387 
1388  unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1389  CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1390  assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1391  "OffsetToTrailingObjects overflow!");
1392 
1393  CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1394 
1395  setCallee(Fn);
1396  for (unsigned I = 0; I != NumPreArgs; ++I)
1397  setPreArg(I, PreArgs[I]);
1398  for (unsigned I = 0; I != Args.size(); ++I)
1399  setArg(I, Args[I]);
1400  for (unsigned I = Args.size(); I != NumArgs; ++I)
1401  setArg(I, nullptr);
1402 
1403  this->computeDependence();
1404 
1405  CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
1406  if (hasStoredFPFeatures())
1407  setStoredFPFeatures(FPFeatures);
1408 }
1409 
1410 CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1411  bool HasFPFeatures, EmptyShell Empty)
1412  : Expr(SC, Empty), NumArgs(NumArgs) {
1413  CallExprBits.NumPreArgs = NumPreArgs;
1414  assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1415 
1416  unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1417  CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1418  assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1419  "OffsetToTrailingObjects overflow!");
1420  CallExprBits.HasFPFeatures = HasFPFeatures;
1421 }
1422 
1425  SourceLocation RParenLoc,
1426  FPOptionsOverride FPFeatures, unsigned MinNumArgs,
1427  ADLCallKind UsesADL) {
1428  unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1429  unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1430  /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
1431  void *Mem =
1432  Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1433  return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1434  RParenLoc, FPFeatures, MinNumArgs, UsesADL);
1435 }
1436 
1438  ExprValueKind VK, SourceLocation RParenLoc,
1439  ADLCallKind UsesADL) {
1440  assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1441  "Misaligned memory in CallExpr::CreateTemporary!");
1442  return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1443  VK, RParenLoc, FPOptionsOverride(),
1444  /*MinNumArgs=*/0, UsesADL);
1445 }
1446 
1447 CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1448  bool HasFPFeatures, EmptyShell Empty) {
1449  unsigned SizeOfTrailingObjects =
1450  CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
1451  void *Mem =
1452  Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1453  return new (Mem)
1454  CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
1455 }
1456 
1457 unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1458  switch (SC) {
1459  case CallExprClass:
1460  return sizeof(CallExpr);
1461  case CXXOperatorCallExprClass:
1462  return sizeof(CXXOperatorCallExpr);
1463  case CXXMemberCallExprClass:
1464  return sizeof(CXXMemberCallExpr);
1465  case UserDefinedLiteralClass:
1466  return sizeof(UserDefinedLiteral);
1467  case CUDAKernelCallExprClass:
1468  return sizeof(CUDAKernelCallExpr);
1469  default:
1470  llvm_unreachable("unexpected class deriving from CallExpr!");
1471  }
1472 }
1473 
1475  Expr *CEE = IgnoreParenImpCasts();
1476 
1477  while (SubstNonTypeTemplateParmExpr *NTTP =
1478  dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1479  CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1480  }
1481 
1482  // If we're calling a dereference, look at the pointer instead.
1483  while (true) {
1484  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1485  if (BO->isPtrMemOp()) {
1486  CEE = BO->getRHS()->IgnoreParenImpCasts();
1487  continue;
1488  }
1489  } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1490  if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1491  UO->getOpcode() == UO_Plus) {
1492  CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1493  continue;
1494  }
1495  }
1496  break;
1497  }
1498 
1499  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
1500  return DRE->getDecl();
1501  if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1502  return ME->getMemberDecl();
1503  if (auto *BE = dyn_cast<BlockExpr>(CEE))
1504  return BE->getBlockDecl();
1505 
1506  return nullptr;
1507 }
1508 
1509 /// If this is a call to a builtin, return the builtin ID. If not, return 0.
1510 unsigned CallExpr::getBuiltinCallee() const {
1511  auto *FDecl =
1512  dyn_cast_or_null<FunctionDecl>(getCallee()->getReferencedDeclOfCallee());
1513  return FDecl ? FDecl->getBuiltinID() : 0;
1514 }
1515 
1517  if (unsigned BI = getBuiltinCallee())
1518  return Ctx.BuiltinInfo.isUnevaluated(BI);
1519  return false;
1520 }
1521 
1523  const Expr *Callee = getCallee();
1524  QualType CalleeType = Callee->getType();
1525  if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1526  CalleeType = FnTypePtr->getPointeeType();
1527  } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1528  CalleeType = BPT->getPointeeType();
1529  } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1530  if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1531  return Ctx.VoidTy;
1532 
1533  if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
1534  return Ctx.DependentTy;
1535 
1536  // This should never be overloaded and so should never return null.
1537  CalleeType = Expr::findBoundMemberType(Callee);
1538  assert(!CalleeType.isNull());
1539  } else if (CalleeType->isDependentType() ||
1540  CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
1541  return Ctx.DependentTy;
1542  }
1543 
1544  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1545  return FnType->getReturnType();
1546 }
1547 
1549  // If the return type is a struct, union, or enum that is marked nodiscard,
1550  // then return the return type attribute.
1551  if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1552  if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1553  return A;
1554 
1555  // Otherwise, see if the callee is marked nodiscard and return that attribute
1556  // instead.
1557  const Decl *D = getCalleeDecl();
1558  return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1559 }
1560 
1562  if (isa<CXXOperatorCallExpr>(this))
1563  return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
1564 
1565  SourceLocation begin = getCallee()->getBeginLoc();
1566  if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1567  begin = getArg(0)->getBeginLoc();
1568  return begin;
1569 }
1571  if (isa<CXXOperatorCallExpr>(this))
1572  return cast<CXXOperatorCallExpr>(this)->getEndLoc();
1573 
1574  SourceLocation end = getRParenLoc();
1575  if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1576  end = getArg(getNumArgs() - 1)->getEndLoc();
1577  return end;
1578 }
1579 
1581  SourceLocation OperatorLoc,
1582  TypeSourceInfo *tsi,
1583  ArrayRef<OffsetOfNode> comps,
1584  ArrayRef<Expr*> exprs,
1585  SourceLocation RParenLoc) {
1586  void *Mem = C.Allocate(
1587  totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1588 
1589  return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1590  RParenLoc);
1591 }
1592 
1594  unsigned numComps, unsigned numExprs) {
1595  void *Mem =
1596  C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1597  return new (Mem) OffsetOfExpr(numComps, numExprs);
1598 }
1599 
1600 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1601  SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1603  SourceLocation RParenLoc)
1604  : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
1605  OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1606  NumComps(comps.size()), NumExprs(exprs.size()) {
1607  for (unsigned i = 0; i != comps.size(); ++i)
1608  setComponent(i, comps[i]);
1609  for (unsigned i = 0; i != exprs.size(); ++i)
1610  setIndexExpr(i, exprs[i]);
1611 
1613 }
1614 
1616  assert(getKind() == Field || getKind() == Identifier);
1617  if (getKind() == Field)
1618  return getField()->getIdentifier();
1619 
1620  return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1621 }
1622 
1624  UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1626  : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
1627  OpLoc(op), RParenLoc(rp) {
1628  assert(ExprKind <= UETT_Last && "invalid enum value!");
1629  UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1630  assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&
1631  "UnaryExprOrTypeTraitExprBits.Kind overflow!");
1632  UnaryExprOrTypeTraitExprBits.IsType = false;
1633  Argument.Ex = E;
1635 }
1636 
1637 MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1638  ValueDecl *MemberDecl,
1639  const DeclarationNameInfo &NameInfo, QualType T,
1641  NonOdrUseReason NOUR)
1642  : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1643  MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1644  assert(!NameInfo.getName() ||
1645  MemberDecl->getDeclName() == NameInfo.getName());
1646  MemberExprBits.IsArrow = IsArrow;
1647  MemberExprBits.HasQualifierOrFoundDecl = false;
1648  MemberExprBits.HasTemplateKWAndArgsInfo = false;
1649  MemberExprBits.HadMultipleCandidates = false;
1650  MemberExprBits.NonOdrUseReason = NOUR;
1651  MemberExprBits.OperatorLoc = OperatorLoc;
1653 }
1654 
1656  const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1657  NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1658  ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1659  DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1661  bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1662  FoundDecl.getAccess() != MemberDecl->getAccess();
1663  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1664  std::size_t Size =
1667  HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1668  TemplateArgs ? TemplateArgs->size() : 0);
1669 
1670  void *Mem = C.Allocate(Size, alignof(MemberExpr));
1671  MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1672  NameInfo, T, VK, OK, NOUR);
1673 
1674  // FIXME: remove remaining dependence computation to computeDependence().
1675  auto Deps = E->getDependence();
1676  if (HasQualOrFound) {
1677  // FIXME: Wrong. We should be looking at the member declaration we found.
1678  if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent())
1679  Deps |= ExprDependence::TypeValueInstantiation;
1680  else if (QualifierLoc &&
1682  Deps |= ExprDependence::Instantiation;
1683 
1684  E->MemberExprBits.HasQualifierOrFoundDecl = true;
1685 
1687  E->getTrailingObjects<MemberExprNameQualifier>();
1688  NQ->QualifierLoc = QualifierLoc;
1689  NQ->FoundDecl = FoundDecl;
1690  }
1691 
1692  E->MemberExprBits.HasTemplateKWAndArgsInfo =
1693  TemplateArgs || TemplateKWLoc.isValid();
1694 
1695  if (TemplateArgs) {
1696  auto TemplateArgDeps = TemplateArgumentDependence::None;
1697  E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1698  TemplateKWLoc, *TemplateArgs,
1699  E->getTrailingObjects<TemplateArgumentLoc>(), TemplateArgDeps);
1700  if (TemplateArgDeps & TemplateArgumentDependence::Instantiation)
1701  Deps |= ExprDependence::Instantiation;
1702  } else if (TemplateKWLoc.isValid()) {
1703  E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1704  TemplateKWLoc);
1705  }
1706  E->setDependence(Deps);
1707 
1708  return E;
1709 }
1710 
1712  bool HasQualifier, bool HasFoundDecl,
1713  bool HasTemplateKWAndArgsInfo,
1714  unsigned NumTemplateArgs) {
1715  assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1716  "template args but no template arg info?");
1717  bool HasQualOrFound = HasQualifier || HasFoundDecl;
1718  std::size_t Size =
1720  TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1721  HasTemplateKWAndArgsInfo ? 1 : 0,
1722  NumTemplateArgs);
1723  void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1724  return new (Mem) MemberExpr(EmptyShell());
1725 }
1726 
1728  MemberDecl = NewD;
1729  if (getType()->isUndeducedType())
1730  setType(NewD->getType());
1732 }
1733 
1735  if (isImplicitAccess()) {
1736  if (hasQualifier())
1737  return getQualifierLoc().getBeginLoc();
1738  return MemberLoc;
1739  }
1740 
1741  // FIXME: We don't want this to happen. Rather, we should be able to
1742  // detect all kinds of implicit accesses more cleanly.
1743  SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1744  if (BaseStartLoc.isValid())
1745  return BaseStartLoc;
1746  return MemberLoc;
1747 }
1751  EndLoc = getRAngleLoc();
1752  else if (EndLoc.isInvalid())
1753  EndLoc = getBase()->getEndLoc();
1754  return EndLoc;
1755 }
1756 
1757 bool CastExpr::CastConsistency() const {
1758  switch (getCastKind()) {
1759  case CK_DerivedToBase:
1760  case CK_UncheckedDerivedToBase:
1761  case CK_DerivedToBaseMemberPointer:
1762  case CK_BaseToDerived:
1763  case CK_BaseToDerivedMemberPointer:
1764  assert(!path_empty() && "Cast kind should have a base path!");
1765  break;
1766 
1767  case CK_CPointerToObjCPointerCast:
1768  assert(getType()->isObjCObjectPointerType());
1769  assert(getSubExpr()->getType()->isPointerType());
1770  goto CheckNoBasePath;
1771 
1772  case CK_BlockPointerToObjCPointerCast:
1773  assert(getType()->isObjCObjectPointerType());
1774  assert(getSubExpr()->getType()->isBlockPointerType());
1775  goto CheckNoBasePath;
1776 
1777  case CK_ReinterpretMemberPointer:
1778  assert(getType()->isMemberPointerType());
1779  assert(getSubExpr()->getType()->isMemberPointerType());
1780  goto CheckNoBasePath;
1781 
1782  case CK_BitCast:
1783  // Arbitrary casts to C pointer types count as bitcasts.
1784  // Otherwise, we should only have block and ObjC pointer casts
1785  // here if they stay within the type kind.
1786  if (!getType()->isPointerType()) {
1787  assert(getType()->isObjCObjectPointerType() ==
1788  getSubExpr()->getType()->isObjCObjectPointerType());
1789  assert(getType()->isBlockPointerType() ==
1790  getSubExpr()->getType()->isBlockPointerType());
1791  }
1792  goto CheckNoBasePath;
1793 
1794  case CK_AnyPointerToBlockPointerCast:
1795  assert(getType()->isBlockPointerType());
1796  assert(getSubExpr()->getType()->isAnyPointerType() &&
1797  !getSubExpr()->getType()->isBlockPointerType());
1798  goto CheckNoBasePath;
1799 
1800  case CK_CopyAndAutoreleaseBlockObject:
1801  assert(getType()->isBlockPointerType());
1802  assert(getSubExpr()->getType()->isBlockPointerType());
1803  goto CheckNoBasePath;
1804 
1805  case CK_FunctionToPointerDecay:
1806  assert(getType()->isPointerType());
1807  assert(getSubExpr()->getType()->isFunctionType());
1808  goto CheckNoBasePath;
1809 
1810  case CK_AddressSpaceConversion: {
1811  auto Ty = getType();
1812  auto SETy = getSubExpr()->getType();
1813  assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1814  if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1815  Ty = Ty->getPointeeType();
1816  SETy = SETy->getPointeeType();
1817  }
1818  assert((Ty->isDependentType() || SETy->isDependentType()) ||
1819  (!Ty.isNull() && !SETy.isNull() &&
1820  Ty.getAddressSpace() != SETy.getAddressSpace()));
1821  goto CheckNoBasePath;
1822  }
1823  // These should not have an inheritance path.
1824  case CK_Dynamic:
1825  case CK_ToUnion:
1826  case CK_ArrayToPointerDecay:
1827  case CK_NullToMemberPointer:
1828  case CK_NullToPointer:
1829  case CK_ConstructorConversion:
1830  case CK_IntegralToPointer:
1831  case CK_PointerToIntegral:
1832  case CK_ToVoid:
1833  case CK_VectorSplat:
1834  case CK_IntegralCast:
1835  case CK_BooleanToSignedIntegral:
1836  case CK_IntegralToFloating:
1837  case CK_FloatingToIntegral:
1838  case CK_FloatingCast:
1839  case CK_ObjCObjectLValueCast:
1840  case CK_FloatingRealToComplex:
1841  case CK_FloatingComplexToReal:
1842  case CK_FloatingComplexCast:
1843  case CK_FloatingComplexToIntegralComplex:
1844  case CK_IntegralRealToComplex:
1845  case CK_IntegralComplexToReal:
1846  case CK_IntegralComplexCast:
1847  case CK_IntegralComplexToFloatingComplex:
1848  case CK_ARCProduceObject:
1849  case CK_ARCConsumeObject:
1850  case CK_ARCReclaimReturnedObject:
1851  case CK_ARCExtendBlockObject:
1852  case CK_ZeroToOCLOpaqueType:
1853  case CK_IntToOCLSampler:
1854  case CK_FloatingToFixedPoint:
1855  case CK_FixedPointToFloating:
1856  case CK_FixedPointCast:
1857  case CK_FixedPointToIntegral:
1858  case CK_IntegralToFixedPoint:
1859  case CK_MatrixCast:
1860  assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1861  goto CheckNoBasePath;
1862 
1863  case CK_Dependent:
1864  case CK_LValueToRValue:
1865  case CK_NoOp:
1866  case CK_AtomicToNonAtomic:
1867  case CK_NonAtomicToAtomic:
1868  case CK_PointerToBoolean:
1869  case CK_IntegralToBoolean:
1870  case CK_FloatingToBoolean:
1871  case CK_MemberPointerToBoolean:
1872  case CK_FloatingComplexToBoolean:
1873  case CK_IntegralComplexToBoolean:
1874  case CK_LValueBitCast: // -> bool&
1875  case CK_LValueToRValueBitCast:
1876  case CK_UserDefinedConversion: // operator bool()
1877  case CK_BuiltinFnToFnPtr:
1878  case CK_FixedPointToBoolean:
1879  CheckNoBasePath:
1880  assert(path_empty() && "Cast kind should not have a base path!");
1881  break;
1882  }
1883  return true;
1884 }
1885 
1887  switch (CK) {
1888 #define CAST_OPERATION(Name) case CK_##Name: return #Name;
1889 #include "clang/AST/OperationKinds.def"
1890  }
1891  llvm_unreachable("Unhandled cast kind!");
1892 }
1893 
1894 namespace {
1895  const Expr *skipImplicitTemporary(const Expr *E) {
1896  // Skip through reference binding to temporary.
1897  if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1898  E = Materialize->getSubExpr();
1899 
1900  // Skip any temporary bindings; they're implicit.
1901  if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1902  E = Binder->getSubExpr();
1903 
1904  return E;
1905  }
1906 }
1907 
1909  const Expr *SubExpr = nullptr;
1910  const CastExpr *E = this;
1911  do {
1912  SubExpr = skipImplicitTemporary(E->getSubExpr());
1913 
1914  // Conversions by constructor and conversion functions have a
1915  // subexpression describing the call; strip it off.
1916  if (E->getCastKind() == CK_ConstructorConversion)
1917  SubExpr =
1918  skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr->IgnoreImplicit())->getArg(0));
1919  else if (E->getCastKind() == CK_UserDefinedConversion) {
1920  SubExpr = SubExpr->IgnoreImplicit();
1921  assert((isa<CXXMemberCallExpr>(SubExpr) ||
1922  isa<BlockExpr>(SubExpr)) &&
1923  "Unexpected SubExpr for CK_UserDefinedConversion.");
1924  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1925  SubExpr = MCE->getImplicitObjectArgument();
1926  }
1927 
1928  // If the subexpression we're left with is an implicit cast, look
1929  // through that, too.
1930  } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1931 
1932  return const_cast<Expr*>(SubExpr);
1933 }
1934 
1936  const Expr *SubExpr = nullptr;
1937 
1938  for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1939  SubExpr = skipImplicitTemporary(E->getSubExpr());
1940 
1941  if (E->getCastKind() == CK_ConstructorConversion)
1942  return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1943 
1944  if (E->getCastKind() == CK_UserDefinedConversion) {
1945  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1946  return MCE->getMethodDecl();
1947  }
1948  }
1949 
1950  return nullptr;
1951 }
1952 
1953 CXXBaseSpecifier **CastExpr::path_buffer() {
1954  switch (getStmtClass()) {
1955 #define ABSTRACT_STMT(x)
1956 #define CASTEXPR(Type, Base) \
1957  case Stmt::Type##Class: \
1958  return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1959 #define STMT(Type, Base)
1960 #include "clang/AST/StmtNodes.inc"
1961  default:
1962  llvm_unreachable("non-cast expressions not possible here");
1963  }
1964 }
1965 
1967  QualType opType) {
1968  auto RD = unionType->castAs<RecordType>()->getDecl();
1969  return getTargetFieldForToUnionCast(RD, opType);
1970 }
1971 
1973  QualType OpType) {
1974  auto &Ctx = RD->getASTContext();
1975  RecordDecl::field_iterator Field, FieldEnd;
1976  for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1977  Field != FieldEnd; ++Field) {
1978  if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1979  !Field->isUnnamedBitfield()) {
1980  return *Field;
1981  }
1982  }
1983  return nullptr;
1984 }
1985 
1987  assert(hasStoredFPFeatures());
1988  switch (getStmtClass()) {
1989  case ImplicitCastExprClass:
1990  return static_cast<ImplicitCastExpr *>(this)
1991  ->getTrailingObjects<FPOptionsOverride>();
1992  case CStyleCastExprClass:
1993  return static_cast<CStyleCastExpr *>(this)
1994  ->getTrailingObjects<FPOptionsOverride>();
1995  case CXXFunctionalCastExprClass:
1996  return static_cast<CXXFunctionalCastExpr *>(this)
1997  ->getTrailingObjects<FPOptionsOverride>();
1998  case CXXStaticCastExprClass:
1999  return static_cast<CXXStaticCastExpr *>(this)
2000  ->getTrailingObjects<FPOptionsOverride>();
2001  default:
2002  llvm_unreachable("Cast does not have FPFeatures");
2003  }
2004 }
2005 
2007  CastKind Kind, Expr *Operand,
2008  const CXXCastPath *BasePath,
2009  ExprValueKind VK,
2010  FPOptionsOverride FPO) {
2011  unsigned PathSize = (BasePath ? BasePath->size() : 0);
2012  void *Buffer =
2013  C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2014  PathSize, FPO.requiresTrailingStorage()));
2015  // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2016  // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2017  assert((Kind != CK_LValueToRValue ||
2018  !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
2019  "invalid type for lvalue-to-rvalue conversion");
2020  ImplicitCastExpr *E =
2021  new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
2022  if (PathSize)
2023  std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2024  E->getTrailingObjects<CXXBaseSpecifier *>());
2025  return E;
2026 }
2027 
2029  unsigned PathSize,
2030  bool HasFPFeatures) {
2031  void *Buffer =
2032  C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2033  PathSize, HasFPFeatures));
2034  return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2035 }
2036 
2038  ExprValueKind VK, CastKind K, Expr *Op,
2039  const CXXCastPath *BasePath,
2040  FPOptionsOverride FPO,
2041  TypeSourceInfo *WrittenTy,
2043  unsigned PathSize = (BasePath ? BasePath->size() : 0);
2044  void *Buffer =
2045  C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2046  PathSize, FPO.requiresTrailingStorage()));
2047  CStyleCastExpr *E =
2048  new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
2049  if (PathSize)
2050  std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2051  E->getTrailingObjects<CXXBaseSpecifier *>());
2052  return E;
2053 }
2054 
2056  unsigned PathSize,
2057  bool HasFPFeatures) {
2058  void *Buffer =
2059  C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2060  PathSize, HasFPFeatures));
2061  return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2062 }
2063 
2064 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2065 /// corresponds to, e.g. "<<=".
2067  switch (Op) {
2068 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2069 #include "clang/AST/OperationKinds.def"
2070  }
2071  llvm_unreachable("Invalid OpCode!");
2072 }
2073 
2076  switch (OO) {
2077  default: llvm_unreachable("Not an overloadable binary operator");
2078  case OO_Plus: return BO_Add;
2079  case OO_Minus: return BO_Sub;
2080  case OO_Star: return BO_Mul;
2081  case OO_Slash: return BO_Div;
2082  case OO_Percent: return BO_Rem;
2083  case OO_Caret: return BO_Xor;
2084  case OO_Amp: return BO_And;
2085  case OO_Pipe: return BO_Or;
2086  case OO_Equal: return BO_Assign;
2087  case OO_Spaceship: return BO_Cmp;
2088  case OO_Less: return BO_LT;
2089  case OO_Greater: return BO_GT;
2090  case OO_PlusEqual: return BO_AddAssign;
2091  case OO_MinusEqual: return BO_SubAssign;
2092  case OO_StarEqual: return BO_MulAssign;
2093  case OO_SlashEqual: return BO_DivAssign;
2094  case OO_PercentEqual: return BO_RemAssign;
2095  case OO_CaretEqual: return BO_XorAssign;
2096  case OO_AmpEqual: return BO_AndAssign;
2097  case OO_PipeEqual: return BO_OrAssign;
2098  case OO_LessLess: return BO_Shl;
2099  case OO_GreaterGreater: return BO_Shr;
2100  case OO_LessLessEqual: return BO_ShlAssign;
2101  case OO_GreaterGreaterEqual: return BO_ShrAssign;
2102  case OO_EqualEqual: return BO_EQ;
2103  case OO_ExclaimEqual: return BO_NE;
2104  case OO_LessEqual: return BO_LE;
2105  case OO_GreaterEqual: return BO_GE;
2106  case OO_AmpAmp: return BO_LAnd;
2107  case OO_PipePipe: return BO_LOr;
2108  case OO_Comma: return BO_Comma;
2109  case OO_ArrowStar: return BO_PtrMemI;
2110  }
2111 }
2112 
2114  static const OverloadedOperatorKind OverOps[] = {
2115  /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2116  OO_Star, OO_Slash, OO_Percent,
2117  OO_Plus, OO_Minus,
2118  OO_LessLess, OO_GreaterGreater,
2119  OO_Spaceship,
2120  OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2121  OO_EqualEqual, OO_ExclaimEqual,
2122  OO_Amp,
2123  OO_Caret,
2124  OO_Pipe,
2125  OO_AmpAmp,
2126  OO_PipePipe,
2127  OO_Equal, OO_StarEqual,
2128  OO_SlashEqual, OO_PercentEqual,
2129  OO_PlusEqual, OO_MinusEqual,
2130  OO_LessLessEqual, OO_GreaterGreaterEqual,
2131  OO_AmpEqual, OO_CaretEqual,
2132  OO_PipeEqual,
2133  OO_Comma
2134  };
2135  return OverOps[Opc];
2136 }
2137 
2139  Opcode Opc,
2140  Expr *LHS, Expr *RHS) {
2141  if (Opc != BO_Add)
2142  return false;
2143 
2144  // Check that we have one pointer and one integer operand.
2145  Expr *PExp;
2146  if (LHS->getType()->isPointerType()) {
2147  if (!RHS->getType()->isIntegerType())
2148  return false;
2149  PExp = LHS;
2150  } else if (RHS->getType()->isPointerType()) {
2151  if (!LHS->getType()->isIntegerType())
2152  return false;
2153  PExp = RHS;
2154  } else {
2155  return false;
2156  }
2157 
2158  // Check that the pointer is a nullptr.
2159  if (!PExp->IgnoreParenCasts()
2161  return false;
2162 
2163  // Check that the pointee type is char-sized.
2164  const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2165  if (!PTy || !PTy->getPointeeType()->isCharType())
2166  return false;
2167 
2168  return true;
2169 }
2170 
2173  switch (Kind) {
2174  case SourceLocExpr::File:
2175  case SourceLocExpr::Function: {
2176  QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2177  return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2178  }
2179  case SourceLocExpr::Line:
2180  case SourceLocExpr::Column:
2181  return Ctx.UnsignedIntTy;
2182  }
2183  llvm_unreachable("unhandled case");
2184 }
2185 
2187  SourceLocation BLoc, SourceLocation RParenLoc,
2188  DeclContext *ParentContext)
2189  : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2191  BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2192  SourceLocExprBits.Kind = Kind;
2194 }
2195 
2196 StringRef SourceLocExpr::getBuiltinStr() const {
2197  switch (getIdentKind()) {
2198  case File:
2199  return "__builtin_FILE";
2200  case Function:
2201  return "__builtin_FUNCTION";
2202  case Line:
2203  return "__builtin_LINE";
2204  case Column:
2205  return "__builtin_COLUMN";
2206  }
2207  llvm_unreachable("unexpected IdentKind!");
2208 }
2209 
2211  const Expr *DefaultExpr) const {
2212  SourceLocation Loc;
2213  const DeclContext *Context;
2214 
2215  std::tie(Loc,
2216  Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2217  if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2218  return {DIE->getUsedLocation(), DIE->getUsedContext()};
2219  if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2220  return {DAE->getUsedLocation(), DAE->getUsedContext()};
2221  return {this->getLocation(), this->getParentContext()};
2222  }();
2223 
2226 
2227  auto MakeStringLiteral = [&](StringRef Tmp) {
2228  using LValuePathEntry = APValue::LValuePathEntry;
2230  // Decay the string to a pointer to the first character.
2231  LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2232  return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2233  };
2234 
2235  switch (getIdentKind()) {
2236  case SourceLocExpr::File: {
2237  SmallString<256> Path(PLoc.getFilename());
2238  Ctx.getLangOpts().remapPathPrefix(Path);
2239  return MakeStringLiteral(Path);
2240  }
2241  case SourceLocExpr::Function: {
2242  const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2243  return MakeStringLiteral(
2245  : std::string(""));
2246  }
2247  case SourceLocExpr::Line:
2248  case SourceLocExpr::Column: {
2249  llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2250  /*isUnsigned=*/true);
2251  IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2252  : PLoc.getColumn();
2253  return APValue(IntVal);
2254  }
2255  }
2256  llvm_unreachable("unhandled case");
2257 }
2258 
2260  ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2261  : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2262  InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2263  RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2264  sawArrayRangeDesignator(false);
2265  InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2266 
2268 }
2269 
2270 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2271  if (NumInits > InitExprs.size())
2272  InitExprs.reserve(C, NumInits);
2273 }
2274 
2275 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2276  InitExprs.resize(C, NumInits, nullptr);
2277 }
2278 
2279 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2280  if (Init >= InitExprs.size()) {
2281  InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2282  setInit(Init, expr);
2283  return nullptr;
2284  }
2285 
2286  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2287  setInit(Init, expr);
2288  return Result;
2289 }
2290 
2292  assert(!hasArrayFiller() && "Filler already set!");
2293  ArrayFillerOrUnionFieldInit = filler;
2294  // Fill out any "holes" in the array due to designated initializers.
2295  Expr **inits = getInits();
2296  for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2297  if (inits[i] == nullptr)
2298  inits[i] = filler;
2299 }
2300 
2302  if (getNumInits() != 1)
2303  return false;
2304  const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2305  if (!AT || !AT->getElementType()->isIntegerType())
2306  return false;
2307  // It is possible for getInit() to return null.
2308  const Expr *Init = getInit(0);
2309  if (!Init)
2310  return false;
2311  Init = Init->IgnoreParenImpCasts();
2312  return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2313 }
2314 
2316  assert(isSemanticForm() && "syntactic form never semantically transparent");
2317 
2318  // A glvalue InitListExpr is always just sugar.
2319  if (isGLValue()) {
2320  assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2321  return true;
2322  }
2323 
2324  // Otherwise, we're sugar if and only if we have exactly one initializer that
2325  // is of the same type.
2326  if (getNumInits() != 1 || !getInit(0))
2327  return false;
2328 
2329  // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2330  // transparent struct copy.
2331  if (!getInit(0)->isPRValue() && getType()->isRecordType())
2332  return false;
2333 
2334  return getType().getCanonicalType() ==
2336 }
2337 
2339  assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2340 
2341  if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2342  return false;
2343  }
2344 
2345  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2346  return Lit && Lit->getValue() == 0;
2347 }
2348 
2350  if (InitListExpr *SyntacticForm = getSyntacticForm())
2351  return SyntacticForm->getBeginLoc();
2352  SourceLocation Beg = LBraceLoc;
2353  if (Beg.isInvalid()) {
2354  // Find the first non-null initializer.
2355  for (InitExprsTy::const_iterator I = InitExprs.begin(),
2356  E = InitExprs.end();
2357  I != E; ++I) {
2358  if (Stmt *S = *I) {
2359  Beg = S->getBeginLoc();
2360  break;
2361  }
2362  }
2363  }
2364  return Beg;
2365 }
2366 
2368  if (InitListExpr *SyntacticForm = getSyntacticForm())
2369  return SyntacticForm->getEndLoc();
2370  SourceLocation End = RBraceLoc;
2371  if (End.isInvalid()) {
2372  // Find the first non-null initializer from the end.
2373  for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
2374  E = InitExprs.rend();
2375  I != E; ++I) {
2376  if (Stmt *S = *I) {
2377  End = S->getEndLoc();
2378  break;
2379  }
2380  }
2381  }
2382  return End;
2383 }
2384 
2385 /// getFunctionType - Return the underlying function type for this block.
2386 ///
2388  // The block pointer is never sugared, but the function type might be.
2389  return cast<BlockPointerType>(getType())
2391 }
2392 
2394  return TheBlock->getCaretLocation();
2395 }
2396 const Stmt *BlockExpr::getBody() const {
2397  return TheBlock->getBody();
2398 }
2400  return TheBlock->getBody();
2401 }
2402 
2403 
2404 //===----------------------------------------------------------------------===//
2405 // Generic Expression Routines
2406 //===----------------------------------------------------------------------===//
2407 
2409  // In C++11, discarded-value expressions of a certain form are special,
2410  // according to [expr]p10:
2411  // The lvalue-to-rvalue conversion (4.1) is applied only if the
2412  // expression is a glvalue of volatile-qualified type and it has
2413  // one of the following forms:
2414  if (!isGLValue() || !getType().isVolatileQualified())
2415  return false;
2416 
2417  const Expr *E = IgnoreParens();
2418 
2419  // - id-expression (5.1.1),
2420  if (isa<DeclRefExpr>(E))
2421  return true;
2422 
2423  // - subscripting (5.2.1),
2424  if (isa<ArraySubscriptExpr>(E))
2425  return true;
2426 
2427  // - class member access (5.2.5),
2428  if (isa<MemberExpr>(E))
2429  return true;
2430 
2431  // - indirection (5.3.1),
2432  if (auto *UO = dyn_cast<UnaryOperator>(E))
2433  if (UO->getOpcode() == UO_Deref)
2434  return true;
2435 
2436  if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2437  // - pointer-to-member operation (5.5),
2438  if (BO->isPtrMemOp())
2439  return true;
2440 
2441  // - comma expression (5.18) where the right operand is one of the above.
2442  if (BO->getOpcode() == BO_Comma)
2443  return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2444  }
2445 
2446  // - conditional expression (5.16) where both the second and the third
2447  // operands are one of the above, or
2448  if (auto *CO = dyn_cast<ConditionalOperator>(E))
2449  return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2450  CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2451  // The related edge case of "*x ?: *x".
2452  if (auto *BCO =
2453  dyn_cast<BinaryConditionalOperator>(E)) {
2454  if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2455  return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2456  BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2457  }
2458 
2459  // Objective-C++ extensions to the rule.
2460  if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
2461  return true;
2462 
2463  return false;
2464 }
2465 
2466 /// isUnusedResultAWarning - Return true if this immediate expression should
2467 /// be warned about if the result is unused. If so, fill in Loc and Ranges
2468 /// with location to warn on and the source range[s] to report with the
2469 /// warning.
2471  SourceRange &R1, SourceRange &R2,
2472  ASTContext &Ctx) const {
2473  // Don't warn if the expr is type dependent. The type could end up
2474  // instantiating to void.
2475  if (isTypeDependent())
2476  return false;
2477 
2478  switch (getStmtClass()) {
2479  default:
2480  if (getType()->isVoidType())
2481  return false;
2482  WarnE = this;
2483  Loc = getExprLoc();
2484  R1 = getSourceRange();
2485  return true;
2486  case ParenExprClass:
2487  return cast<ParenExpr>(this)->getSubExpr()->
2488  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2489  case GenericSelectionExprClass:
2490  return cast<GenericSelectionExpr>(this)->getResultExpr()->
2491  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2492  case CoawaitExprClass:
2493  case CoyieldExprClass:
2494  return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2495  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2496  case ChooseExprClass:
2497  return cast<ChooseExpr>(this)->getChosenSubExpr()->
2498  isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2499  case UnaryOperatorClass: {
2500  const UnaryOperator *UO = cast<UnaryOperator>(this);
2501 
2502  switch (UO->getOpcode()) {
2503  case UO_Plus:
2504  case UO_Minus:
2505  case UO_AddrOf:
2506  case UO_Not:
2507  case UO_LNot:
2508  case UO_Deref:
2509  break;
2510  case UO_Coawait:
2511  // This is just the 'operator co_await' call inside the guts of a
2512  // dependent co_await call.
2513  case UO_PostInc:
2514  case UO_PostDec:
2515  case UO_PreInc:
2516  case UO_PreDec: // ++/--
2517  return false; // Not a warning.
2518  case UO_Real:
2519  case UO_Imag:
2520  // accessing a piece of a volatile complex is a side-effect.
2521  if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2523  return false;
2524  break;
2525  case UO_Extension:
2526  return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2527  }
2528  WarnE = this;
2529  Loc = UO->getOperatorLoc();
2530  R1 = UO->getSubExpr()->getSourceRange();
2531  return true;
2532  }
2533  case BinaryOperatorClass: {
2534  const BinaryOperator *BO = cast<BinaryOperator>(this);
2535  switch (BO->getOpcode()) {
2536  default:
2537  break;
2538  // Consider the RHS of comma for side effects. LHS was checked by
2539  // Sema::CheckCommaOperands.
2540  case BO_Comma:
2541  // ((foo = <blah>), 0) is an idiom for hiding the result (and
2542  // lvalue-ness) of an assignment written in a macro.
2543  if (IntegerLiteral *IE =
2544  dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2545  if (IE->getValue() == 0)
2546  return false;
2547  return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2548  // Consider '||', '&&' to have side effects if the LHS or RHS does.
2549  case BO_LAnd:
2550  case BO_LOr:
2551  if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2552  !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2553  return false;
2554  break;
2555  }
2556  if (BO->isAssignmentOp())
2557  return false;
2558  WarnE = this;
2559  Loc = BO->getOperatorLoc();
2560  R1 = BO->getLHS()->getSourceRange();
2561  R2 = BO->getRHS()->getSourceRange();
2562  return true;
2563  }
2564  case CompoundAssignOperatorClass:
2565  case VAArgExprClass:
2566  case AtomicExprClass:
2567  return false;
2568 
2569  case ConditionalOperatorClass: {
2570  // If only one of the LHS or RHS is a warning, the operator might
2571  // be being used for control flow. Only warn if both the LHS and
2572  // RHS are warnings.
2573  const auto *Exp = cast<ConditionalOperator>(this);
2574  return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2575  Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2576  }
2577  case BinaryConditionalOperatorClass: {
2578  const auto *Exp = cast<BinaryConditionalOperator>(this);
2579  return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2580  }
2581 
2582  case MemberExprClass:
2583  WarnE = this;
2584  Loc = cast<MemberExpr>(this)->getMemberLoc();
2585  R1 = SourceRange(Loc, Loc);
2586  R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2587  return true;
2588 
2589  case ArraySubscriptExprClass:
2590  WarnE = this;
2591  Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2592  R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2593  R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2594  return true;
2595 
2596  case CXXOperatorCallExprClass: {
2597  // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2598  // overloads as there is no reasonable way to define these such that they
2599  // have non-trivial, desirable side-effects. See the -Wunused-comparison
2600  // warning: operators == and != are commonly typo'ed, and so warning on them
2601  // provides additional value as well. If this list is updated,
2602  // DiagnoseUnusedComparison should be as well.
2603  const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2604  switch (Op->getOperator()) {
2605  default:
2606  break;
2607  case OO_EqualEqual:
2608  case OO_ExclaimEqual:
2609  case OO_Less:
2610  case OO_Greater:
2611  case OO_GreaterEqual:
2612  case OO_LessEqual:
2613  if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2614  Op->getCallReturnType(Ctx)->isVoidType())
2615  break;
2616  WarnE = this;
2617  Loc = Op->getOperatorLoc();
2618  R1 = Op->getSourceRange();
2619  return true;
2620  }
2621 
2622  // Fallthrough for generic call handling.
2623  LLVM_FALLTHROUGH;
2624  }
2625  case CallExprClass:
2626  case CXXMemberCallExprClass:
2627  case UserDefinedLiteralClass: {
2628  // If this is a direct call, get the callee.
2629  const CallExpr *CE = cast<CallExpr>(this);
2630  if (const Decl *FD = CE->getCalleeDecl()) {
2631  // If the callee has attribute pure, const, or warn_unused_result, warn
2632  // about it. void foo() { strlen("bar"); } should warn.
2633  //
2634  // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2635  // updated to match for QoI.
2636  if (CE->hasUnusedResultAttr(Ctx) ||
2637  FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2638  WarnE = this;
2639  Loc = CE->getCallee()->getBeginLoc();
2640  R1 = CE->getCallee()->getSourceRange();
2641 
2642  if (unsigned NumArgs = CE->getNumArgs())
2643  R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2644  CE->getArg(NumArgs - 1)->getEndLoc());
2645  return true;
2646  }
2647  }
2648  return false;
2649  }
2650 
2651  // If we don't know precisely what we're looking at, let's not warn.
2652  case UnresolvedLookupExprClass:
2653  case CXXUnresolvedConstructExprClass:
2654  case RecoveryExprClass:
2655  return false;
2656 
2657  case CXXTemporaryObjectExprClass:
2658  case CXXConstructExprClass: {
2659  if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2660  const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2661  if (Type->hasAttr<WarnUnusedAttr>() ||
2662  (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2663  WarnE = this;
2664  Loc = getBeginLoc();
2665  R1 = getSourceRange();
2666  return true;
2667  }
2668  }
2669 
2670  const auto *CE = cast<CXXConstructExpr>(this);
2671  if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2672  const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2673  if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2674  WarnE = this;
2675  Loc = getBeginLoc();
2676  R1 = getSourceRange();
2677 
2678  if (unsigned NumArgs = CE->getNumArgs())
2679  R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2680  CE->getArg(NumArgs - 1)->getEndLoc());
2681  return true;
2682  }
2683  }
2684 
2685  return false;
2686  }
2687 
2688  case ObjCMessageExprClass: {
2689  const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2690  if (Ctx.getLangOpts().ObjCAutoRefCount &&
2691  ME->isInstanceMessage() &&
2692  !ME->getType()->isVoidType() &&
2693  ME->getMethodFamily() == OMF_init) {
2694  WarnE = this;
2695  Loc = getExprLoc();
2696  R1 = ME->getSourceRange();
2697  return true;
2698  }
2699 
2700  if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2701  if (MD->hasAttr<WarnUnusedResultAttr>()) {
2702  WarnE = this;
2703  Loc = getExprLoc();
2704  return true;
2705  }
2706 
2707  return false;
2708  }
2709 
2710  case ObjCPropertyRefExprClass:
2711  WarnE = this;
2712  Loc = getExprLoc();
2713  R1 = getSourceRange();
2714  return true;
2715 
2716  case PseudoObjectExprClass: {
2717  const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2718 
2719  // Only complain about things that have the form of a getter.
2720  if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2721  isa<BinaryOperator>(PO->getSyntacticForm()))
2722  return false;
2723 
2724  WarnE = this;
2725  Loc = getExprLoc();
2726  R1 = getSourceRange();
2727  return true;
2728  }
2729 
2730  case StmtExprClass: {
2731  // Statement exprs don't logically have side effects themselves, but are
2732  // sometimes used in macros in ways that give them a type that is unused.
2733  // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2734  // however, if the result of the stmt expr is dead, we don't want to emit a
2735  // warning.
2736  const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2737  if (!CS->body_empty()) {
2738  if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2739  return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2740  if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2741  if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2742  return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2743  }
2744 
2745  if (getType()->isVoidType())
2746  return false;
2747  WarnE = this;
2748  Loc = cast<StmtExpr>(this)->getLParenLoc();
2749  R1 = getSourceRange();
2750  return true;
2751  }
2752  case CXXFunctionalCastExprClass:
2753  case CStyleCastExprClass: {
2754  // Ignore an explicit cast to void, except in C++98 if the operand is a
2755  // volatile glvalue for which we would trigger an implicit read in any
2756  // other language mode. (Such an implicit read always happens as part of
2757  // the lvalue conversion in C, and happens in C++ for expressions of all
2758  // forms where it seems likely the user intended to trigger a volatile
2759  // load.)
2760  const CastExpr *CE = cast<CastExpr>(this);
2761  const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2762  if (CE->getCastKind() == CK_ToVoid) {
2763  if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2765  // Suppress the "unused value" warning for idiomatic usage of
2766  // '(void)var;' used to suppress "unused variable" warnings.
2767  if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2768  if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2769  if (!VD->isExternallyVisible())
2770  return false;
2771 
2772  // The lvalue-to-rvalue conversion would have no effect for an array.
2773  // It's implausible that the programmer expected this to result in a
2774  // volatile array load, so don't warn.
2775  if (SubE->getType()->isArrayType())
2776  return false;
2777 
2778  return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2779  }
2780  return false;
2781  }
2782 
2783  // If this is a cast to a constructor conversion, check the operand.
2784  // Otherwise, the result of the cast is unused.
2785  if (CE->getCastKind() == CK_ConstructorConversion)
2786  return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2787  if (CE->getCastKind() == CK_Dependent)
2788  return false;
2789 
2790  WarnE = this;
2791  if (const CXXFunctionalCastExpr *CXXCE =
2792  dyn_cast<CXXFunctionalCastExpr>(this)) {
2793  Loc = CXXCE->getBeginLoc();
2794  R1 = CXXCE->getSubExpr()->getSourceRange();
2795  } else {
2796  const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2797  Loc = CStyleCE->getLParenLoc();
2798  R1 = CStyleCE->getSubExpr()->getSourceRange();
2799  }
2800  return true;
2801  }
2802  case ImplicitCastExprClass: {
2803  const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2804 
2805  // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2806  if (ICE->getCastKind() == CK_LValueToRValue &&
2808  return false;
2809 
2810  return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2811  }
2812  case CXXDefaultArgExprClass:
2813  return (cast<CXXDefaultArgExpr>(this)
2814  ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2815  case CXXDefaultInitExprClass:
2816  return (cast<CXXDefaultInitExpr>(this)
2817  ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2818 
2819  case CXXNewExprClass:
2820  // FIXME: In theory, there might be new expressions that don't have side
2821  // effects (e.g. a placement new with an uninitialized POD).
2822  case CXXDeleteExprClass:
2823  return false;
2824  case MaterializeTemporaryExprClass:
2825  return cast<MaterializeTemporaryExpr>(this)
2826  ->getSubExpr()
2827  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2828  case CXXBindTemporaryExprClass:
2829  return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2830  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2831  case ExprWithCleanupsClass:
2832  return cast<ExprWithCleanups>(this)->getSubExpr()
2833  ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2834  }
2835 }
2836 
2837 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2838 /// returns true, if it is; false otherwise.
2840  const Expr *E = IgnoreParens();
2841  switch (E->getStmtClass()) {
2842  default:
2843  return false;
2844  case ObjCIvarRefExprClass:
2845  return true;
2846  case Expr::UnaryOperatorClass:
2847  return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2848  case ImplicitCastExprClass:
2849  return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2850  case MaterializeTemporaryExprClass:
2851  return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2852  Ctx);
2853  case CStyleCastExprClass:
2854  return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2855  case DeclRefExprClass: {
2856  const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2857 
2858  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2859  if (VD->hasGlobalStorage())
2860  return true;
2861  QualType T = VD->getType();
2862  // dereferencing to a pointer is always a gc'able candidate,
2863  // unless it is __weak.
2864  return T->isPointerType() &&
2865  (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2866  }
2867  return false;
2868  }
2869  case MemberExprClass: {
2870  const MemberExpr *M = cast<MemberExpr>(E);
2871  return M->getBase()->isOBJCGCCandidate(Ctx);
2872  }
2873  case ArraySubscriptExprClass:
2874  return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2875  }
2876 }
2877 
2879  if (isTypeDependent())
2880  return false;
2881  return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2882 }
2883 
2885  assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2886 
2887  // Bound member expressions are always one of these possibilities:
2888  // x->m x.m x->*y x.*y
2889  // (possibly parenthesized)
2890 
2891  expr = expr->IgnoreParens();
2892  if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2893  assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2894  return mem->getMemberDecl()->getType();
2895  }
2896 
2897  if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2898  QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2899  ->getPointeeType();
2900  assert(type->isFunctionType());
2901  return type;
2902  }
2903 
2904  assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
2905  return QualType();
2906 }
2907 
2910 }
2911 
2913  return IgnoreExprNodes(this, IgnoreCastsSingleStep);
2914 }
2915 
2918 }
2919 
2922 }
2923 
2926 }
2927 
2931 }
2932 
2935 }
2936 
2938  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2939  if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2940  return MCE->getImplicitObjectArgument();
2941  }
2942  return this;
2943 }
2944 
2948 }
2949 
2953 }
2954 
2956  auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
2957  if (auto *CE = dyn_cast<CastExpr>(E)) {
2958  // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2959  // ptr<->int casts of the same width. We also ignore all identity casts.
2960  Expr *SubExpr = CE->getSubExpr();
2961  bool IsIdentityCast =
2962  Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2963  bool IsSameWidthCast = (E->getType()->isPointerType() ||
2964  E->getType()->isIntegralType(Ctx)) &&
2965  (SubExpr->getType()->isPointerType() ||
2966  SubExpr->getType()->isIntegralType(Ctx)) &&
2967  (Ctx.getTypeSize(E->getType()) ==
2968  Ctx.getTypeSize(SubExpr->getType()));
2969 
2970  if (IsIdentityCast || IsSameWidthCast)
2971  return SubExpr;
2972  } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2973  return NTTP->getReplacement();
2974 
2975  return E;
2976  };
2978  IgnoreNoopCastsSingleStep);
2979 }
2980 
2983  if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
2984  auto *SE = Cast->getSubExpr();
2985  if (SE->getSourceRange() == E->getSourceRange())
2986  return SE;
2987  }
2988 
2989  if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
2990  auto NumArgs = C->getNumArgs();
2991  if (NumArgs == 1 ||
2992  (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
2993  Expr *A = C->getArg(0);
2994  if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
2995  return A;
2996  }
2997  }
2998  return E;
2999  };
3000  auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
3001  if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3002  Expr *ExprNode = C->getImplicitObjectArgument();
3003  if (ExprNode->getSourceRange() == E->getSourceRange()) {
3004  return ExprNode;
3005  }
3006  if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
3007  if (PE->getSourceRange() == C->getSourceRange()) {
3008  return cast<Expr>(PE);
3009  }
3010  }
3011  ExprNode = ExprNode->IgnoreParenImpCasts();
3012  if (ExprNode->getSourceRange() == E->getSourceRange())
3013  return ExprNode;
3014  }
3015  return E;
3016  };
3017  return IgnoreExprNodes(
3020  IgnoreImplicitMemberCallSingleStep);
3021 }
3022 
3024  const Expr *E = this;
3025  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3026  E = M->getSubExpr();
3027 
3028  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3029  E = ICE->getSubExprAsWritten();
3030 
3031  return isa<CXXDefaultArgExpr>(E);
3032 }
3033 
3034 /// Skip over any no-op casts and any temporary-binding
3035 /// expressions.
3037  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3038  E = M->getSubExpr();
3039 
3040  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3041  if (ICE->getCastKind() == CK_NoOp)
3042  E = ICE->getSubExpr();
3043  else
3044  break;
3045  }
3046 
3047  while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3048  E = BE->getSubExpr();
3049 
3050  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3051  if (ICE->getCastKind() == CK_NoOp)
3052  E = ICE->getSubExpr();
3053  else
3054  break;
3055  }
3056 
3057  return E->IgnoreParens();
3058 }
3059 
3060 /// isTemporaryObject - Determines if this expression produces a
3061 /// temporary of the given class type.
3062 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3063  if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3064  return false;
3065 
3067 
3068  // Temporaries are by definition pr-values of class type.
3069  if (!E->Classify(C).isPRValue()) {
3070  // In this context, property reference is a message call and is pr-value.
3071  if (!isa<ObjCPropertyRefExpr>(E))
3072  return false;
3073  }
3074 
3075  // Black-list a few cases which yield pr-values of class type that don't
3076  // refer to temporaries of that type:
3077 
3078  // - implicit derived-to-base conversions
3079  if (isa<ImplicitCastExpr>(E)) {
3080  switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3081  case CK_DerivedToBase:
3082  case CK_UncheckedDerivedToBase:
3083  return false;
3084  default:
3085  break;
3086  }
3087  }
3088 
3089  // - member expressions (all)
3090  if (isa<MemberExpr>(E))
3091  return false;
3092 
3093  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3094  if (BO->isPtrMemOp())
3095  return false;
3096 
3097  // - opaque values (all)
3098  if (isa<OpaqueValueExpr>(E))
3099  return false;
3100 
3101  return true;
3102 }
3103 
3105  const Expr *E = this;
3106 
3107  // Strip away parentheses and casts we don't care about.
3108  while (true) {
3109  if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3110  E = Paren->getSubExpr();
3111  continue;
3112  }
3113 
3114  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3115  if (ICE->getCastKind() == CK_NoOp ||
3116  ICE->getCastKind() == CK_LValueToRValue ||
3117  ICE->getCastKind() == CK_DerivedToBase ||
3118  ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3119  E = ICE->getSubExpr();
3120  continue;
3121  }
3122  }
3123 
3124  if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3125  if (UnOp->getOpcode() == UO_Extension) {
3126  E = UnOp->getSubExpr();
3127  continue;
3128  }
3129  }
3130 
3131  if (const MaterializeTemporaryExpr *M
3132  = dyn_cast<MaterializeTemporaryExpr>(E)) {
3133  E = M->getSubExpr();
3134  continue;
3135  }
3136 
3137  break;
3138  }
3139 
3140  if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3141  return This->isImplicit();
3142 
3143  return false;
3144 }
3145 
3146 /// hasAnyTypeDependentArguments - Determines if any of the expressions
3147 /// in Exprs is type-dependent.
3149  for (unsigned I = 0; I < Exprs.size(); ++I)
3150  if (Exprs[I]->isTypeDependent())
3151  return true;
3152 
3153  return false;
3154 }
3155 
3156 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3157  const Expr **Culprit) const {
3158  assert(!isValueDependent() &&
3159  "Expression evaluator can't be called on a dependent expression.");
3160 
3161  // This function is attempting whether an expression is an initializer
3162  // which can be evaluated at compile-time. It very closely parallels
3163  // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3164  // will lead to unexpected results. Like ConstExprEmitter, it falls back
3165  // to isEvaluatable most of the time.
3166  //
3167  // If we ever capture reference-binding directly in the AST, we can
3168  // kill the second parameter.
3169 
3170  if (IsForRef) {
3171  EvalResult Result;
3172  if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3173  return true;
3174  if (Culprit)
3175  *Culprit = this;
3176  return false;
3177  }
3178 
3179  switch (getStmtClass()) {
3180  default: break;
3181  case Stmt::ExprWithCleanupsClass:
3182  return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3183  Ctx, IsForRef, Culprit);
3184  case StringLiteralClass:
3185  case ObjCEncodeExprClass:
3186  return true;
3187  case CXXTemporaryObjectExprClass:
3188  case CXXConstructExprClass: {
3189  const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3190 
3191  if (CE->getConstructor()->isTrivial() &&
3193  // Trivial default constructor
3194  if (!CE->getNumArgs()) return true;
3195 
3196  // Trivial copy constructor
3197  assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3198  return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3199  }
3200 
3201  break;
3202  }
3203  case ConstantExprClass: {
3204  // FIXME: We should be able to return "true" here, but it can lead to extra
3205  // error messages. E.g. in Sema/array-init.c.
3206  const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3207  return Exp->isConstantInitializer(Ctx, false, Culprit);
3208  }
3209  case CompoundLiteralExprClass: {
3210  // This handles gcc's extension that allows global initializers like
3211  // "struct x {int x;} x = (struct x) {};".
3212  // FIXME: This accepts other cases it shouldn't!
3213  const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3214  return Exp->isConstantInitializer(Ctx, false, Culprit);
3215  }
3216  case DesignatedInitUpdateExprClass: {
3217  const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3218  return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3219  DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3220  }
3221  case InitListExprClass: {
3222  const InitListExpr *ILE = cast<InitListExpr>(this);
3223  assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3224  if (ILE->getType()->isArrayType()) {
3225  unsigned numInits = ILE->getNumInits();
3226  for (unsigned i = 0; i < numInits; i++) {
3227  if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3228  return false;
3229  }
3230  return true;
3231  }
3232 
3233  if (ILE->getType()->isRecordType()) {
3234  unsigned ElementNo = 0;
3235  RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3236  for (const auto *Field : RD->fields()) {
3237  // If this is a union, skip all the fields that aren't being initialized.
3238  if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3239  continue;
3240 
3241  // Don't emit anonymous bitfields, they just affect layout.
3242  if (Field->isUnnamedBitfield())
3243  continue;
3244 
3245  if (ElementNo < ILE->getNumInits()) {
3246  const Expr *Elt = ILE->getInit(ElementNo++);
3247  if (Field->isBitField()) {
3248  // Bitfields have to evaluate to an integer.
3249  EvalResult Result;
3250  if (!Elt->EvaluateAsInt(Result, Ctx)) {
3251  if (Culprit)
3252  *Culprit = Elt;
3253  return false;
3254  }
3255  } else {
3256  bool RefType = Field->getType()->isReferenceType();
3257  if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3258  return false;
3259  }
3260  }
3261  }
3262  return true;
3263  }
3264 
3265  break;
3266  }
3267  case ImplicitValueInitExprClass:
3268  case NoInitExprClass:
3269  return true;
3270  case ParenExprClass:
3271  return cast<ParenExpr>(this)->getSubExpr()
3272  ->isConstantInitializer(Ctx, IsForRef, Culprit);
3273  case GenericSelectionExprClass:
3274  return cast<GenericSelectionExpr>(this)->getResultExpr()
3275  ->isConstantInitializer(Ctx, IsForRef, Culprit);
3276  case ChooseExprClass:
3277  if (cast<ChooseExpr>(this)->isConditionDependent()) {
3278  if (Culprit)
3279  *Culprit = this;
3280  return false;
3281  }
3282  return cast<ChooseExpr>(this)->getChosenSubExpr()
3283  ->isConstantInitializer(Ctx, IsForRef, Culprit);
3284  case UnaryOperatorClass: {
3285  const UnaryOperator* Exp = cast<UnaryOperator>(this);
3286  if (Exp->getOpcode() == UO_Extension)
3287  return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3288  break;
3289  }
3290  case CXXFunctionalCastExprClass:
3291  case CXXStaticCastExprClass:
3292  case ImplicitCastExprClass:
3293  case CStyleCastExprClass:
3294  case ObjCBridgedCastExprClass:
3295  case CXXDynamicCastExprClass:
3296  case CXXReinterpretCastExprClass:
3297  case CXXAddrspaceCastExprClass:
3298  case CXXConstCastExprClass: {
3299  const CastExpr *CE = cast<CastExpr>(this);
3300 
3301  // Handle misc casts we want to ignore.
3302  if (CE->getCastKind() == CK_NoOp ||
3303  CE->getCastKind() == CK_LValueToRValue ||
3304  CE->getCastKind() == CK_ToUnion ||
3305  CE->getCastKind() == CK_ConstructorConversion ||
3306  CE->getCastKind() == CK_NonAtomicToAtomic ||
3307  CE->getCastKind() == CK_AtomicToNonAtomic ||
3308  CE->getCastKind() == CK_IntToOCLSampler)
3309  return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3310 
3311  break;
3312  }
3313  case MaterializeTemporaryExprClass:
3314  return cast<MaterializeTemporaryExpr>(this)
3315  ->getSubExpr()
3316  ->isConstantInitializer(Ctx, false, Culprit);
3317 
3318  case SubstNonTypeTemplateParmExprClass:
3319  return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3320  ->isConstantInitializer(Ctx, false, Culprit);
3321  case CXXDefaultArgExprClass:
3322  return cast<CXXDefaultArgExpr>(this)->getExpr()
3323  ->isConstantInitializer(Ctx, false, Culprit);
3324  case CXXDefaultInitExprClass:
3325  return cast<CXXDefaultInitExpr>(this)->getExpr()
3326  ->isConstantInitializer(Ctx, false, Culprit);
3327  }
3328  // Allow certain forms of UB in constant initializers: signed integer
3329  // overflow and floating-point division by zero. We'll give a warning on
3330  // these, but they're common enough that we have to accept them.
3332  return true;
3333  if (Culprit)
3334  *Culprit = this;
3335  return false;
3336 }
3337 
3339  const FunctionDecl* FD = getDirectCallee();
3340  if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3341  FD->getBuiltinID() != Builtin::BI__builtin_assume))
3342  return false;
3343 
3344  const Expr* Arg = getArg(0);
3345  bool ArgVal;
3346  return !Arg->isValueDependent() &&
3347  Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3348 }
3349 
3350 namespace {
3351  /// Look for any side effects within a Stmt.
3352  class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3354  const bool IncludePossibleEffects;
3355  bool HasSideEffects;
3356 
3357  public:
3358  explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3359  : Inherited(Context),
3360  IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3361 
3362  bool hasSideEffects() const { return HasSideEffects; }
3363 
3364  void VisitDecl(const Decl *D) {
3365  if (!D)
3366  return;
3367 
3368  // We assume the caller checks subexpressions (eg, the initializer, VLA
3369  // bounds) for side-effects on our behalf.
3370  if (auto *VD = dyn_cast<VarDecl>(D)) {
3371  // Registering a destructor is a side-effect.
3372  if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3373  VD->needsDestruction(Context))
3374  HasSideEffects = true;
3375  }
3376  }
3377 
3378  void VisitDeclStmt(const DeclStmt *DS) {
3379  for (auto *D : DS->decls())
3380  VisitDecl(D);
3381  Inherited::VisitDeclStmt(DS);
3382  }
3383 
3384  void VisitExpr(const Expr *E) {
3385  if (!HasSideEffects &&
3386  E->HasSideEffects(Context, IncludePossibleEffects))
3387  HasSideEffects = true;
3388  }
3389  };
3390 }
3391 
3393  bool IncludePossibleEffects) const {
3394  // In circumstances where we care about definite side effects instead of
3395  // potential side effects, we want to ignore expressions that are part of a
3396  // macro expansion as a potential side effect.
3397  if (!IncludePossibleEffects && getExprLoc().isMacroID())
3398  return false;
3399 
3400  switch (getStmtClass()) {
3401  case NoStmtClass:
3402  #define ABSTRACT_STMT(Type)
3403  #define STMT(Type, Base) case Type##Class:
3404  #define EXPR(Type, Base)
3405  #include "clang/AST/StmtNodes.inc"
3406  llvm_unreachable("unexpected Expr kind");
3407 
3408  case DependentScopeDeclRefExprClass:
3409  case CXXUnresolvedConstructExprClass:
3410  case CXXDependentScopeMemberExprClass:
3411  case UnresolvedLookupExprClass:
3412  case UnresolvedMemberExprClass:
3413  case PackExpansionExprClass:
3414  case SubstNonTypeTemplateParmPackExprClass:
3415  case FunctionParmPackExprClass:
3416  case TypoExprClass:
3417  case RecoveryExprClass:
3418  case CXXFoldExprClass:
3419  // Make a conservative assumption for dependent nodes.
3420  return IncludePossibleEffects;
3421 
3422  case DeclRefExprClass:
3423  case ObjCIvarRefExprClass:
3424  case PredefinedExprClass:
3425  case IntegerLiteralClass:
3426  case FixedPointLiteralClass:
3427  case FloatingLiteralClass:
3428  case ImaginaryLiteralClass:
3429  case StringLiteralClass:
3430  case CharacterLiteralClass:
3431  case OffsetOfExprClass:
3432  case ImplicitValueInitExprClass:
3433  case UnaryExprOrTypeTraitExprClass:
3434  case AddrLabelExprClass:
3435  case GNUNullExprClass:
3436  case ArrayInitIndexExprClass:
3437  case NoInitExprClass:
3438  case CXXBoolLiteralExprClass:
3439  case CXXNullPtrLiteralExprClass:
3440  case CXXThisExprClass:
3441  case CXXScalarValueInitExprClass:
3442  case TypeTraitExprClass:
3443  case ArrayTypeTraitExprClass:
3444  case ExpressionTraitExprClass:
3445  case CXXNoexceptExprClass:
3446  case SizeOfPackExprClass:
3447  case ObjCStringLiteralClass:
3448  case ObjCEncodeExprClass:
3449  case ObjCBoolLiteralExprClass:
3450  case ObjCAvailabilityCheckExprClass:
3451  case CXXUuidofExprClass:
3452  case OpaqueValueExprClass:
3453  case SourceLocExprClass:
3454  case ConceptSpecializationExprClass:
3455  case RequiresExprClass:
3456  case SYCLUniqueStableNameExprClass:
3457  // These never have a side-effect.
3458  return false;
3459 
3460  case ConstantExprClass:
3461  // FIXME: Move this into the "return false;" block above.
3462  return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3463  Ctx, IncludePossibleEffects);
3464 
3465  case CallExprClass:
3466  case CXXOperatorCallExprClass:
3467  case CXXMemberCallExprClass:
3468  case CUDAKernelCallExprClass:
3469  case UserDefinedLiteralClass: {
3470  // We don't know a call definitely has side effects, except for calls
3471  // to pure/const functions that definitely don't.
3472  // If the call itself is considered side-effect free, check the operands.
3473  const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3474  bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3475  if (IsPure || !IncludePossibleEffects)
3476  break;
3477  return true;
3478  }
3479 
3480  case BlockExprClass:
3481  case CXXBindTemporaryExprClass:
3482  if (!IncludePossibleEffects)
3483  break;
3484  return true;
3485 
3486  case MSPropertyRefExprClass:
3487  case MSPropertySubscriptExprClass:
3488  case CompoundAssignOperatorClass:
3489  case VAArgExprClass:
3490  case AtomicExprClass:
3491  case CXXThrowExprClass:
3492  case CXXNewExprClass:
3493  case CXXDeleteExprClass:
3494  case CoawaitExprClass:
3495  case DependentCoawaitExprClass:
3496  case CoyieldExprClass:
3497  // These always have a side-effect.
3498  return true;
3499 
3500  case StmtExprClass: {
3501  // StmtExprs have a side-effect if any substatement does.
3502  SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3503  Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3504  return Finder.hasSideEffects();
3505  }
3506 
3507  case ExprWithCleanupsClass:
3508  if (IncludePossibleEffects)
3509  if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3510  return true;
3511  break;
3512 
3513  case ParenExprClass:
3514  case ArraySubscriptExprClass:
3515  case MatrixSubscriptExprClass:
3516  case OMPArraySectionExprClass:
3517  case OMPArrayShapingExprClass:
3518  case OMPIteratorExprClass:
3519  case MemberExprClass:
3520  case ConditionalOperatorClass:
3521  case BinaryConditionalOperatorClass:
3522  case CompoundLiteralExprClass:
3523  case ExtVectorElementExprClass:
3524  case DesignatedInitExprClass:
3525  case DesignatedInitUpdateExprClass:
3526  case ArrayInitLoopExprClass:
3527  case ParenListExprClass:
3528  case CXXPseudoDestructorExprClass:
3529  case CXXRewrittenBinaryOperatorClass:
3530  case CXXStdInitializerListExprClass:
3531  case SubstNonTypeTemplateParmExprClass:
3532  case MaterializeTemporaryExprClass:
3533  case ShuffleVectorExprClass:
3534  case ConvertVectorExprClass:
3535  case AsTypeExprClass:
3536  // These have a side-effect if any subexpression does.
3537  break;
3538 
3539  case UnaryOperatorClass:
3540  if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3541  return true;
3542  break;
3543 
3544  case BinaryOperatorClass:
3545  if (cast<BinaryOperator>(this)->isAssignmentOp())
3546  return true;
3547  break;
3548 
3549  case InitListExprClass:
3550  // FIXME: The children for an InitListExpr doesn't include the array filler.
3551  if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3552  if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3553  return true;
3554  break;
3555 
3556  case GenericSelectionExprClass:
3557  return cast<GenericSelectionExpr>(this)->getResultExpr()->
3558  HasSideEffects(Ctx, IncludePossibleEffects);
3559 
3560  case ChooseExprClass:
3561  return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3562  Ctx, IncludePossibleEffects);
3563 
3564  case CXXDefaultArgExprClass:
3565  return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3566  Ctx, IncludePossibleEffects);
3567 
3568  case CXXDefaultInitExprClass: {
3569  const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3570  if (const Expr *E = FD->getInClassInitializer())
3571  return E->HasSideEffects(Ctx, IncludePossibleEffects);
3572  // If we've not yet parsed the initializer, assume it has side-effects.
3573  return true;
3574  }
3575 
3576  case CXXDynamicCastExprClass: {
3577  // A dynamic_cast expression has side-effects if it can throw.
3578  const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3579  if (DCE->getTypeAsWritten()->isReferenceType() &&
3580  DCE->getCastKind() == CK_Dynamic)
3581  return true;
3582  }
3583  LLVM_FALLTHROUGH;
3584  case ImplicitCastExprClass:
3585  case CStyleCastExprClass:
3586  case CXXStaticCastExprClass:
3587  case CXXReinterpretCastExprClass:
3588  case CXXConstCastExprClass:
3589  case CXXAddrspaceCastExprClass:
3590  case CXXFunctionalCastExprClass:
3591  case BuiltinBitCastExprClass: {
3592  // While volatile reads are side-effecting in both C and C++, we treat them
3593  // as having possible (not definite) side-effects. This allows idiomatic
3594  // code to behave without warning, such as sizeof(*v) for a volatile-
3595  // qualified pointer.
3596  if (!IncludePossibleEffects)
3597  break;
3598 
3599  const CastExpr *CE = cast<CastExpr>(this);
3600  if (CE->getCastKind() == CK_LValueToRValue &&
3602  return true;
3603  break;
3604  }
3605 
3606  case CXXTypeidExprClass:
3607  // typeid might throw if its subexpression is potentially-evaluated, so has
3608  // side-effects in that case whether or not its subexpression does.
3609  return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3610 
3611  case CXXConstructExprClass:
3612  case CXXTemporaryObjectExprClass: {
3613  const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3614  if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3615  return true;
3616  // A trivial constructor does not add any side-effects of its own. Just look
3617  // at its arguments.
3618  break;
3619  }
3620 
3621  case CXXInheritedCtorInitExprClass: {
3622  const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3623  if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3624  return true;
3625  break;
3626  }
3627 
3628  case LambdaExprClass: {
3629  const LambdaExpr *LE = cast<LambdaExpr>(this);
3630  for (Expr *E : LE->capture_inits())
3631  if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3632  return true;
3633  return false;
3634  }
3635 
3636  case PseudoObjectExprClass: {
3637  // Only look for side-effects in the semantic form, and look past
3638  // OpaqueValueExpr bindings in that form.
3639  const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3641  E = PO->semantics_end();
3642  I != E; ++I) {
3643  const Expr *Subexpr = *I;
3644  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3645  Subexpr = OVE->getSourceExpr();
3646  if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3647  return true;
3648  }
3649  return false;
3650  }
3651 
3652  case ObjCBoxedExprClass:
3653  case ObjCArrayLiteralClass:
3654  case ObjCDictionaryLiteralClass:
3655  case ObjCSelectorExprClass:
3656  case ObjCProtocolExprClass:
3657  case ObjCIsaExprClass:
3658  case ObjCIndirectCopyRestoreExprClass:
3659  case ObjCSubscriptRefExprClass:
3660  case ObjCBridgedCastExprClass:
3661  case ObjCMessageExprClass:
3662  case ObjCPropertyRefExprClass:
3663  // FIXME: Classify these cases better.
3664  if (IncludePossibleEffects)
3665  return true;
3666  break;
3667  }
3668 
3669  // Recurse to children.
3670  for (const Stmt *SubStmt : children())
3671  if (SubStmt &&
3672  cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3673  return true;
3674 
3675  return false;
3676 }
3677 
3679  if (auto Call = dyn_cast<CallExpr>(this))
3680  return Call->getFPFeaturesInEffect(LO);
3681  if (auto UO = dyn_cast<UnaryOperator>(this))
3682  return UO->getFPFeaturesInEffect(LO);
3683  if (auto BO = dyn_cast<BinaryOperator>(this))
3684  return BO->getFPFeaturesInEffect(LO);
3685  if (auto Cast = dyn_cast<CastExpr>(this))
3686  return Cast->getFPFeaturesInEffect(LO);
3688 }
3689 
3690 namespace {
3691  /// Look for a call to a non-trivial function within an expression.
3692  class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3693  {
3695 
3696  bool NonTrivial;
3697 
3698  public:
3699  explicit NonTrivialCallFinder(const ASTContext &Context)
3700  : Inherited(Context), NonTrivial(false) { }
3701 
3702  bool hasNonTrivialCall() const { return NonTrivial; }
3703 
3704  void VisitCallExpr(const CallExpr *E) {
3705  if (const CXXMethodDecl *Method
3706  = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3707  if (Method->isTrivial()) {
3708  // Recurse to children of the call.
3709  Inherited::VisitStmt(E);
3710  return;
3711  }
3712  }
3713 
3714  NonTrivial = true;
3715  }
3716 
3717  void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3718  if (E->getConstructor()->isTrivial()) {
3719  // Recurse to children of the call.
3720  Inherited::VisitStmt(E);
3721  return;
3722  }
3723 
3724  NonTrivial = true;
3725  }
3726 
3727  void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3728  if (E->getTemporary()->getDestructor()->isTrivial()) {
3729  Inherited::VisitStmt(E);
3730  return;
3731  }
3732 
3733  NonTrivial = true;
3734  }
3735  };
3736 }
3737 
3738 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3739  NonTrivialCallFinder Finder(Ctx);
3740  Finder.Visit(this);
3741  return Finder.hasNonTrivialCall();
3742 }
3743 
3744 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3745 /// pointer constant or not, as well as the specific kind of constant detected.
3746 /// Null pointer constants can be integer constant expressions with the
3747 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3748 /// (a GNU extension).
3752  if (isValueDependent() &&
3753  (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3754  // Error-dependent expr should never be a null pointer.
3755  if (containsErrors())
3756  return NPCK_NotNull;
3757  switch (NPC) {
3759  llvm_unreachable("Unexpected value dependent expression!");
3761  if (isTypeDependent() || getType()->isIntegralType(Ctx))
3762  return NPCK_ZeroExpression;
3763  else
3764  return NPCK_NotNull;
3765 
3767  return NPCK_NotNull;
3768  }
3769  }
3770 
3771  // Strip off a cast to void*, if it exists. Except in C++.
3772  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3773  if (!Ctx.getLangOpts().CPlusPlus) {
3774  // Check that it is a cast to void*.
3775  if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3776  QualType Pointee = PT->getPointeeType();
3777  Qualifiers Qs = Pointee.getQualifiers();
3778  // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3779  // has non-default address space it is not treated as nullptr.
3780  // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3781  // since it cannot be assigned to a pointer to constant address space.
3782  if (Ctx.getLangOpts().OpenCL &&
3784  Qs.removeAddressSpace();
3785 
3786  if (Pointee->isVoidType() && Qs.empty() && // to void*
3787  CE->getSubExpr()->getType()->isIntegerType()) // from int
3788  return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3789  }
3790  }
3791  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3792  // Ignore the ImplicitCastExpr type entirely.
3793  return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3794  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3795  // Accept ((void*)0) as a null pointer constant, as many other
3796  // implementations do.
3797  return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3798  } else if (const GenericSelectionExpr *GE =
3799  dyn_cast<GenericSelectionExpr>(this)) {
3800  if (GE->isResultDependent())
3801  return NPCK_NotNull;
3802  return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3803  } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3804  if (CE->isConditionDependent())
3805  return NPCK_NotNull;
3806  return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3807  } else if (const CXXDefaultArgExpr *DefaultArg
3808  = dyn_cast<CXXDefaultArgExpr>(this)) {
3809  // See through default argument expressions.
3810  return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3811  } else if (const CXXDefaultInitExpr *DefaultInit
3812  = dyn_cast<CXXDefaultInitExpr>(this)) {
3813  // See through default initializer expressions.
3814  return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3815  } else if (isa<GNUNullExpr>(this)) {
3816  // The GNU __null extension is always a null pointer constant.
3817  return NPCK_GNUNull;
3818  } else if (const MaterializeTemporaryExpr *M
3819  = dyn_cast<MaterializeTemporaryExpr>(this)) {
3820  return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3821  } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3822  if (const Expr *Source = OVE->getSourceExpr())
3823  return Source->isNullPointerConstant(Ctx, NPC);
3824  }
3825 
3826  // If the expression has no type information, it cannot be a null pointer
3827  // constant.
3828  if (getType().isNull())
3829  return NPCK_NotNull;
3830 
3831  // C++11 nullptr_t is always a null pointer constant.
3832  if (getType()->isNullPtrType())
3833  return NPCK_CXX11_nullptr;
3834 
3835  if (const RecordType *UT = getType()->getAsUnionType())
3836  if (!Ctx.getLangOpts().CPlusPlus11 &&
3837  UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3838  if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3839  const Expr *InitExpr = CLE->getInitializer();
3840  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3841  return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3842  }
3843  // This expression must be an integer type.
3844  if (!getType()->isIntegerType() ||
3845  (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3846  return NPCK_NotNull;
3847 
3848  if (Ctx.getLangOpts().CPlusPlus11) {
3849  // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3850  // value zero or a prvalue of type std::nullptr_t.
3851  // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3852  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3853  if (Lit && !Lit->getValue())
3854  return NPCK_ZeroLiteral;
3855  if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3856  return NPCK_NotNull;
3857  } else {
3858  // If we have an integer constant expression, we need to *evaluate* it and
3859  // test for the value 0.
3860  if (!isIntegerConstantExpr(Ctx))
3861  return NPCK_NotNull;
3862  }
3863 
3864  if (EvaluateKnownConstInt(Ctx) != 0)
3865  return NPCK_NotNull;
3866 
3867  if (isa<IntegerLiteral>(this))
3868  return NPCK_ZeroLiteral;
3869  return NPCK_ZeroExpression;
3870 }
3871 
3872 /// If this expression is an l-value for an Objective C
3873 /// property, find the underlying property reference expression.
3875  const Expr *E = this;
3876  while (true) {
3877  assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
3878  "expression is not a property reference");
3879  E = E->IgnoreParenCasts();
3880  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3881  if (BO->getOpcode() == BO_Comma) {
3882  E = BO->getRHS();
3883  continue;
3884  }
3885  }
3886 
3887  break;
3888  }
3889 
3890  return cast<ObjCPropertyRefExpr>(E);
3891 }
3892 
3893 bool Expr::isObjCSelfExpr() const {
3894  const Expr *E = IgnoreParenImpCasts();
3895 
3896  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3897  if (!DRE)
3898  return false;
3899 
3900  const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3901  if (!Param)
3902  return false;
3903 
3904  const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3905  if (!M)
3906  return false;
3907 
3908  return M->getSelfDecl() == Param;
3909 }
3910 
3912  Expr *E = this->IgnoreParens();
3913 
3914  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3915  if (ICE->getCastKind() == CK_LValueToRValue ||
3916  (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
3917  E = ICE->getSubExpr()->IgnoreParens();
3918  else
3919  break;
3920  }
3921 
3922  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3923  if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3924  if (Field->isBitField())
3925  return Field;
3926 
3927  if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3928  FieldDecl *Ivar = IvarRef->getDecl();
3929  if (Ivar->isBitField())
3930  return Ivar;
3931  }
3932 
3933  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3934  if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3935  if (Field->isBitField())
3936  return Field;
3937 
3938  if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3939  if (Expr *E = BD->getBinding())
3940  return E->getSourceBitField();
3941  }
3942 
3943  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3944  if (BinOp->isAssignmentOp() && BinOp->getLHS())
3945  return BinOp->getLHS()->getSourceBitField();
3946 
3947  if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3948  return BinOp->getRHS()->getSourceBitField();
3949  }
3950 
3951  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3952  if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3953  return UnOp->getSubExpr()->getSourceBitField();
3954 
3955  return nullptr;
3956 }
3957 
3959  // FIXME: Why do we not just look at the ObjectKind here?
3960  const Expr *E = this->IgnoreParens();
3961 
3962  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3963  if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
3964  E = ICE->getSubExpr()->IgnoreParens();
3965  else
3966  break;
3967  }
3968 
3969  if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3970  return ASE->getBase()->getType()->isVectorType();
3971 
3972  if (isa<ExtVectorElementExpr>(E))
3973  return true;
3974 
3975  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3976  if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3977  if (auto *E = BD->getBinding())
3978  return E->refersToVectorElement();
3979 
3980  return false;
3981 }
3982 
3984  const Expr *E = this->IgnoreParenImpCasts();
3985 
3986  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3987  if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3988  if (VD->getStorageClass() == SC_Register &&
3989  VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3990  return true;
3991 
3992  return false;
3993 }
3994 
3995 bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
3996  E1 = E1->IgnoreParens();
3997  E2 = E2->IgnoreParens();
3998 
3999  if (E1->getStmtClass() != E2->getStmtClass())
4000  return false;
4001 
4002  switch (E1->getStmtClass()) {
4003  default:
4004  return false;
4005  case CXXThisExprClass:
4006  return true;
4007  case DeclRefExprClass: {
4008  // DeclRefExpr without an ImplicitCastExpr can happen for integral
4009  // template parameters.
4010  const auto *DRE1 = cast<DeclRefExpr>(E1);
4011  const auto *DRE2 = cast<DeclRefExpr>(E2);
4012  return DRE1->isPRValue() && DRE2->isPRValue() &&
4013  DRE1->getDecl() == DRE2->getDecl();
4014  }
4015  case ImplicitCastExprClass: {
4016  // Peel off implicit casts.
4017  while (true) {
4018  const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4019  const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4020  if (!ICE1 || !ICE2)
4021  return false;
4022  if (ICE1->getCastKind() != ICE2->getCastKind())
4023  return false;
4024  E1 = ICE1->getSubExpr()->IgnoreParens();
4025  E2 = ICE2->getSubExpr()->IgnoreParens();
4026  // The final cast must be one of these types.
4027  if (ICE1->getCastKind() == CK_LValueToRValue ||
4028  ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4029  ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4030  break;
4031  }
4032  }
4033 
4034  const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4035  const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4036  if (DRE1 && DRE2)
4037  return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4038 
4039  const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4040  const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4041  if (Ivar1 && Ivar2) {
4042  return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4043  declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4044  }
4045 
4046  const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4047  const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4048  if (Array1 && Array2) {
4049  if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4050  return false;
4051 
4052  auto Idx1 = Array1->getIdx();
4053  auto Idx2 = Array2->getIdx();
4054  const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4055  const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4056  if (Integer1 && Integer2) {
4057  if (!llvm::APInt::isSameValue(Integer1->getValue(),
4058  Integer2->getValue()))
4059  return false;
4060  } else {
4061  if (!isSameComparisonOperand(Idx1, Idx2))
4062  return false;
4063  }
4064 
4065  return true;
4066  }
4067 
4068  // Walk the MemberExpr chain.
4069  while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4070  const auto *ME1 = cast<MemberExpr>(E1);
4071  const auto *ME2 = cast<MemberExpr>(E2);
4072  if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4073  return false;
4074  if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4075  if (D->isStaticDataMember())
4076  return true;
4077  E1 = ME1->getBase()->IgnoreParenImpCasts();
4078  E2 = ME2->getBase()->IgnoreParenImpCasts();
4079  }
4080 
4081  if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4082  return true;
4083 
4084  // A static member variable can end the MemberExpr chain with either
4085  // a MemberExpr or a DeclRefExpr.
4086  auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4087  if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4088  return DRE->getDecl();
4089  if (const auto *ME = dyn_cast<MemberExpr>(E))
4090  return ME->getMemberDecl();
4091  return nullptr;
4092  };
4093 
4094  const ValueDecl *VD1 = getAnyDecl(E1);
4095  const ValueDecl *VD2 = getAnyDecl(E2);
4096  return declaresSameEntity(VD1, VD2);
4097  }
4098  }
4099 }
4100 
4101 /// isArrow - Return true if the base expression is a pointer to vector,
4102 /// return false if the base expression is a vector.
4104  return getBase()->getType()->isPointerType();
4105 }
4106 
4108  if (const VectorType *VT = getType()->getAs<VectorType>())
4109  return VT->getNumElements();
4110  return 1;
4111 }
4112 
4113 /// containsDuplicateElements - Return true if any element access is repeated.
4115  // FIXME: Refactor this code to an accessor on the AST node which returns the
4116  // "type" of component access, and share with code below and in Sema.
4117  StringRef Comp = Accessor->getName();
4118 
4119  // Halving swizzles do not contain duplicate elements.
4120  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4121  return false;
4122 
4123  // Advance past s-char prefix on hex swizzles.
4124  if (Comp[0] == 's' || Comp[0] == 'S')
4125  Comp = Comp.substr(1);
4126 
4127  for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4128  if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
4129  return true;
4130 
4131  return false;
4132 }
4133 
4134 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4136  SmallVectorImpl<uint32_t> &Elts) const {
4137  StringRef Comp = Accessor->getName();
4138  bool isNumericAccessor = false;
4139  if (Comp[0] == 's' || Comp[0] == 'S') {
4140  Comp = Comp.substr(1);
4141  isNumericAccessor = true;
4142  }
4143 
4144  bool isHi = Comp == "hi";
4145  bool isLo = Comp == "lo";
4146  bool isEven = Comp == "even";
4147  bool isOdd = Comp == "odd";
4148 
4149  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4150  uint64_t Index;
4151 
4152  if (isHi)
4153  Index = e + i;
4154  else if (isLo)
4155  Index = i;
4156  else if (isEven)
4157  Index = 2 * i;
4158  else if (isOdd)
4159  Index = 2 * i + 1;
4160  else
4161  Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4162 
4163  Elts.push_back(Index);
4164  }
4165 }
4166 
4169  SourceLocation RP)
4170  : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4171  BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
4172  SubExprs = new (C) Stmt*[args.size()];
4173  for (unsigned i = 0; i != args.size(); i++)
4174  SubExprs[i] = args[i];
4175 
4177 }
4178 
4180  if (SubExprs) C.Deallocate(SubExprs);
4181 
4182  this->NumExprs = Exprs.size();
4183  SubExprs = new (C) Stmt*[NumExprs];
4184  memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4185 }
4186 
4187 GenericSelectionExpr::GenericSelectionExpr(
4188  const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4189  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4190  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4191  bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4192  : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4193  AssocExprs[ResultIndex]->getValueKind(),
4194  AssocExprs[ResultIndex]->getObjectKind()),
4195  NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4196  DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4197  assert(AssocTypes.size() == AssocExprs.size() &&
4198  "Must have the same number of association expressions"
4199  " and TypeSourceInfo!");
4200  assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4201 
4202  GenericSelectionExprBits.GenericLoc = GenericLoc;
4203  getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4204  std::copy(AssocExprs.begin(), AssocExprs.end(),
4205  getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4206  std::copy(AssocTypes.begin(), AssocTypes.end(),
4207  getTrailingObjects<TypeSourceInfo *>());
4208 
4209  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4210 }
4211 
4212 GenericSelectionExpr::GenericSelectionExpr(
4213  const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4214  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4215  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4216  bool ContainsUnexpandedParameterPack)
4217  : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4218  OK_Ordinary),
4219  NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4220  DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4221  assert(AssocTypes.size() == AssocExprs.size() &&
4222  "Must have the same number of association expressions"
4223  " and TypeSourceInfo!");
4224 
4225  GenericSelectionExprBits.GenericLoc = GenericLoc;
4226  getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4227  std::copy(AssocExprs.begin(), AssocExprs.end(),
4228  getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4229  std::copy(AssocTypes.begin(), AssocTypes.end(),
4230  getTrailingObjects<TypeSourceInfo *>());
4231 
4232  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4233 }
4234 
4235 GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4236  : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4237 
4239  const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4240  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4241  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4242  bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4243  unsigned NumAssocs = AssocExprs.size();
4244  void *Mem = Context.Allocate(
4245  totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4246  alignof(GenericSelectionExpr));
4247  return new (Mem) GenericSelectionExpr(
4248  Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4249  RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4250 }
4251 
4253  const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4254  ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4255  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4256  bool ContainsUnexpandedParameterPack) {
4257  unsigned NumAssocs = AssocExprs.size();
4258  void *Mem = Context.Allocate(
4259  totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4260  alignof(GenericSelectionExpr));
4261  return new (Mem) GenericSelectionExpr(
4262  Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4263  RParenLoc, ContainsUnexpandedParameterPack);
4264 }
4265 
4268  unsigned NumAssocs) {
4269  void *Mem = Context.Allocate(
4270  totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4271  alignof(GenericSelectionExpr));
4272  return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4273 }
4274 
4275 //===----------------------------------------------------------------------===//
4276 // DesignatedInitExpr
4277 //===----------------------------------------------------------------------===//
4278 
4280  assert(Kind == FieldDesignator && "Only valid on a field designator");
4281  if (Field.NameOrField & 0x01)
4282  return reinterpret_cast<IdentifierInfo *>(Field.NameOrField & ~0x01);
4283  return getField()->getIdentifier();
4284 }
4285 
4286 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4287  llvm::ArrayRef<Designator> Designators,
4288  SourceLocation EqualOrColonLoc,
4289  bool GNUSyntax,
4290  ArrayRef<Expr *> IndexExprs, Expr *Init)
4291  : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4292  Init->getObjectKind()),
4293  EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4294  NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4295  this->Designators = new (C) Designator[NumDesignators];
4296 
4297  // Record the initializer itself.
4298  child_iterator Child = child_begin();
4299  *Child++ = Init;
4300 
4301  // Copy the designators and their subexpressions, computing
4302  // value-dependence along the way.
4303  unsigned IndexIdx = 0;
4304  for (unsigned I = 0; I != NumDesignators; ++I) {
4305  this->Designators[I] = Designators[I];
4306  if (this->Designators[I].isArrayDesignator()) {
4307  // Copy the index expressions into permanent storage.
4308  *Child++ = IndexExprs[IndexIdx++];
4309  } else if (this->Designators[I].isArrayRangeDesignator()) {
4310  // Copy the start/end expressions into permanent storage.
4311  *Child++ = IndexExprs[IndexIdx++];
4312  *Child++ = IndexExprs[IndexIdx++];
4313  }
4314  }
4315 
4316  assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4318 }
4319 
4322  llvm::ArrayRef<Designator> Designators,
4323  ArrayRef<Expr*> IndexExprs,
4324  SourceLocation ColonOrEqualLoc,
4325  bool UsesColonSyntax, Expr *Init) {
4326  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4327  alignof(DesignatedInitExpr));
4328  return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4329  ColonOrEqualLoc, UsesColonSyntax,
4330  IndexExprs, Init);
4331 }
4332 
4334  unsigned NumIndexExprs) {
4335  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4336  alignof(DesignatedInitExpr));
4337  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4338 }
4339 
4341  const Designator *Desigs,
4342  unsigned NumDesigs) {
4343  Designators = new (C) Designator[NumDesigs];
4344  NumDesignators = NumDesigs;
4345  for (unsigned I = 0; I != NumDesigs; ++I)
4346  Designators[I] = Desigs[I];
4347 }
4348 
4350  DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4351  if (size() == 1)
4352  return DIE->getDesignator(0)->getSourceRange();
4353  return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4354  DIE->getDesignator(size() - 1)->getEndLoc());
4355 }
4356 
4358  SourceLocation StartLoc;
4359  auto *DIE = const_cast<DesignatedInitExpr *>(this);
4360  Designator &First = *DIE->getDesignator(0);
4361  if (First.isFieldDesignator())
4362  StartLoc = GNUSyntax ? First.Field.FieldLoc : First.Field.DotLoc;
4363  else
4364  StartLoc = First.ArrayOrRange.LBracketLoc;
4365  return StartLoc;
4366 }
4367 
4369  return getInit()->getEndLoc();
4370 }
4371 
4373  assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
4374  return getSubExpr(D.ArrayOrRange.Index + 1);
4375 }
4376 
4378  assert(D.Kind == Designator::ArrayRangeDesignator &&
4379  "Requires array range designator");
4380  return getSubExpr(D.ArrayOrRange.Index + 1);
4381 }
4382 
4384  assert(D.Kind == Designator::ArrayRangeDesignator &&
4385  "Requires array range designator");
4386  return getSubExpr(D.ArrayOrRange.Index + 2);
4387 }
4388 
4389 /// Replaces the designator at index @p Idx with the series
4390 /// of designators in [First, Last).
4392  const Designator *First,
4393  const Designator *Last) {
4394  unsigned NumNewDesignators = Last - First;
4395  if (NumNewDesignators == 0) {
4396  std::copy_backward(Designators + Idx + 1,
4397  Designators + NumDesignators,
4398  Designators + Idx);
4399  --NumNewDesignators;
4400  return;
4401  }
4402  if (NumNewDesignators == 1) {
4403  Designators[Idx] = *First;
4404  return;
4405  }
4406 
4407  Designator *NewDesignators
4408  = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4409  std::copy(Designators, Designators + Idx, NewDesignators);
4410  std::copy(First, Last, NewDesignators + Idx);
4411  std::copy(Designators + Idx + 1, Designators + NumDesignators,
4412  NewDesignators + Idx + NumNewDesignators);
4413  Designators = NewDesignators;
4414  NumDesignators = NumDesignators - 1 + NumNewDesignators;
4415 }
4416 
4418  SourceLocation lBraceLoc,
4419  Expr *baseExpr,
4420  SourceLocation rBraceLoc)
4421  : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4422  OK_Ordinary) {
4423  BaseAndUpdaterExprs[0] = baseExpr;
4424 
4425  InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4426  ILE->setType(baseExpr->getType());
4427  BaseAndUpdaterExprs[1] = ILE;
4428 
4429  // FIXME: this is wrong, set it correctly.
4431 }
4432 
4434  return getBase()->getBeginLoc();
4435 }
4436 
4438  return getBase()->getEndLoc();
4439 }
4440 
4441 ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4442  SourceLocation RParenLoc)
4443  : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
4444  LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4445  ParenListExprBits.NumExprs = Exprs.size();
4446 
4447  for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
4448  getTrailingObjects<Stmt *>()[I] = Exprs[I];
4450 }
4451 
4452 ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4453  : Expr(ParenListExprClass, Empty) {
4454  ParenListExprBits.NumExprs = NumExprs;
4455 }
4456 
4458  SourceLocation LParenLoc,
4459  ArrayRef<Expr *> Exprs,
4460  SourceLocation RParenLoc) {
4461  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4462  alignof(ParenListExpr));
4463  return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4464 }
4465 
4467  unsigned NumExprs) {
4468  void *Mem =
4469  Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4470  return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4471 }
4472 
4474  Opcode opc, QualType ResTy, ExprValueKind VK,
4475  ExprObjectKind OK, SourceLocation opLoc,
4476  FPOptionsOverride FPFeatures)
4477  : Expr(BinaryOperatorClass, ResTy, VK, OK) {
4478  BinaryOperatorBits.Opc = opc;
4479  assert(!isCompoundAssignmentOp() &&
4480  "Use CompoundAssignOperator for compound assignments");
4481  BinaryOperatorBits.OpLoc = opLoc;
4482  SubExprs[LHS] = lhs;
4483  SubExprs[RHS] = rhs;
4484  BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4485  if (hasStoredFPFeatures())
4486  setStoredFPFeatures(FPFeatures);
4488 }
4489 
4491  Opcode opc, QualType ResTy, ExprValueKind VK,
4492  ExprObjectKind OK, SourceLocation opLoc,
4493  FPOptionsOverride FPFeatures, bool dead2)
4494  : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
4495  BinaryOperatorBits.Opc = opc;
4496  assert(isCompoundAssignmentOp() &&
4497  "Use CompoundAssignOperator for compound assignments");
4498  BinaryOperatorBits.OpLoc = opLoc;
4499  SubExprs[LHS] = lhs;
4500  SubExprs[RHS] = rhs;
4501  BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4502  if (hasStoredFPFeatures())
4503  setStoredFPFeatures(FPFeatures);
4505 }
4506 
4508  bool HasFPFeatures) {
4509  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4510  void *Mem =
4511  C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4512  return new (Mem) BinaryOperator(EmptyShell());
4513 }
4514 
4516  Expr *rhs, Opcode opc, QualType ResTy,
4518  SourceLocation opLoc,
4519  FPOptionsOverride FPFeatures) {
4520  bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4521  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4522  void *Mem =
4523  C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4524  return new (Mem)
4525  BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
4526 }
4527 
4529 CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {
4530  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4531  void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4532  alignof(CompoundAssignOperator));
4533  return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
4534 }
4535 
4538  Opcode opc, QualType ResTy, ExprValueKind VK,
4539  ExprObjectKind OK, SourceLocation opLoc,
4540  FPOptionsOverride FPFeatures,
4541  QualType CompLHSType, QualType CompResultType) {
4542  bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4543  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4544  void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4545  alignof(CompoundAssignOperator));
4546  return new (Mem)
4547  CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
4548  CompLHSType, CompResultType);
4549 }
4550 
4552  bool hasFPFeatures) {
4553  void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
4554  alignof(UnaryOperator));
4555  return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
4556 }
4557 
4560  SourceLocation l, bool CanOverflow,
4561  FPOptionsOverride FPFeatures)
4562  : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
4563  UnaryOperatorBits.Opc = opc;
4564  UnaryOperatorBits.CanOverflow = CanOverflow;
4565  UnaryOperatorBits.Loc = l;
4566  UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4567  if (hasStoredFPFeatures())
4568  setStoredFPFeatures(FPFeatures);
4569  setDependence(computeDependence(this, Ctx));
4570 }
4571 
4573  Opcode opc, QualType type,
4575  SourceLocation l, bool CanOverflow,
4576  FPOptionsOverride FPFeatures) {
4577  bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4578  unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
4579  void *Mem = C.Allocate(Size, alignof(UnaryOperator));
4580  return new (Mem)
4581  UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
4582 }
4583 
4585  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4586  e = ewc->getSubExpr();
4587  if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4588  e = m->getSubExpr();
4589  e = cast<CXXConstructExpr>(e)->getArg(0);
4590  while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4591  e = ice->getSubExpr();
4592  return cast<OpaqueValueExpr>(e);
4593 }
4594 
4596  EmptyShell sh,
4597  unsigned numSemanticExprs) {
4598  void *buffer =
4599  Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4600  alignof(PseudoObjectExpr));
4601  return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4602 }
4603 
4604 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4605  : Expr(PseudoObjectExprClass, shell) {
4606  PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4607 }
4608 
4610  ArrayRef<Expr*> semantics,
4611  unsigned resultIndex) {
4612  assert(syntax && "no syntactic expression!");
4613  assert(semantics.size() && "no semantic expressions!");
4614 
4615  QualType type;
4616  ExprValueKind VK;
4617  if (resultIndex == NoResult) {
4618  type = C.VoidTy;
4619  VK = VK_PRValue;
4620  } else {
4621  assert(resultIndex < semantics.size());
4622  type = semantics[resultIndex]->getType();
4623  VK = semantics[resultIndex]->getValueKind();
4624  assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4625  }
4626 
4627  void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4628  alignof(PseudoObjectExpr));
4629  return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4630  resultIndex);
4631 }
4632 
4633 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4634  Expr *syntax, ArrayRef<Expr *> semantics,
4635  unsigned resultIndex)
4636  : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
4637  PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4638  PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4639 
4640  for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4641  Expr *E = (i == 0 ? syntax : semantics[i-1]);
4642  getSubExprsBuffer()[i] = E;
4643 
4644  if (isa<OpaqueValueExpr>(E))
4645  assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
4646  "opaque-value semantic expressions for pseudo-object "
4647  "operations must have sources");
4648  }
4649 
4651 }
4652 
4653 //===----------------------------------------------------------------------===//
4654 // Child Iterators for iterating over subexpressions/substatements
4655 //===----------------------------------------------------------------------===//
4656 
4657 // UnaryExprOrTypeTraitExpr
4659  const_child_range CCR =
4660  const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4661  return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4662 }
4663 
4665  // If this is of a type and the type is a VLA type (and not a typedef), the
4666  // size expression of the VLA needs to be treated as an executable expression.
4667  // Why isn't this weirdness documented better in StmtIterator?
4668  if (isArgumentType()) {
4669  if (const VariableArrayType *T =
4670  dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4673  }
4674  return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4675 }
4676 
4678  AtomicOp op, SourceLocation RP)
4679  : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
4680  NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
4681  assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4682  for (unsigned i = 0; i != args.size(); i++)
4683  SubExprs[i] = args[i];
4685 }
4686 
4688  switch (Op) {
4689  case AO__c11_atomic_init:
4690  case AO__opencl_atomic_init:
4691  case AO__c11_atomic_load:
4692  case AO__atomic_load_n:
4693  return 2;
4694 
4695  case AO__opencl_atomic_load:
4696  case AO__c11_atomic_store:
4697  case AO__c11_atomic_exchange:
4698  case AO__atomic_load:
4699  case AO__atomic_store:
4700  case AO__atomic_store_n:
4701  case AO__atomic_exchange_n:
4702  case AO__c11_atomic_fetch_add:
4703  case AO__c11_atomic_fetch_sub:
4704  case AO__c11_atomic_fetch_and:
4705  case AO__c11_atomic_fetch_or:
4706  case AO__c11_atomic_fetch_xor:
4707  case AO__c11_atomic_fetch_max:
4708  case AO__c11_atomic_fetch_min:
4709  case AO__atomic_fetch_add:
4710  case AO__atomic_fetch_sub:
4711  case AO__atomic_fetch_and:
4712  case AO__atomic_fetch_or:
4713  case AO__atomic_fetch_xor:
4714  case AO__atomic_fetch_nand:
4715  case AO__atomic_add_fetch:
4716  case AO__atomic_sub_fetch:
4717  case AO__atomic_and_fetch:
4718  case AO__atomic_or_fetch:
4719  case AO__atomic_xor_fetch:
4720  case AO__atomic_nand_fetch:
4721  case AO__atomic_min_fetch:
4722  case AO__atomic_max_fetch:
4723  case AO__atomic_fetch_min:
4724  case AO__atomic_fetch_max:
4725  return 3;
4726 
4727  case AO__opencl_atomic_store:
4728  case AO__opencl_atomic_exchange:
4729  case AO__opencl_atomic_fetch_add:
4730  case AO__opencl_atomic_fetch_sub:
4731  case AO__opencl_atomic_fetch_and:
4732  case AO__opencl_atomic_fetch_or:
4733  case AO__opencl_atomic_fetch_xor:
4734  case AO__opencl_atomic_fetch_min:
4735  case AO__opencl_atomic_fetch_max:
4736  case AO__atomic_exchange:
4737  return 4;
4738 
4739  case AO__c11_atomic_compare_exchange_strong:
4740  case AO__c11_atomic_compare_exchange_weak:
4741  return 5;
4742 
4743  case AO__opencl_atomic_compare_exchange_strong:
4744  case AO__opencl_atomic_compare_exchange_weak:
4745  case AO__atomic_compare_exchange:
4746  case AO__atomic_compare_exchange_n:
4747  return 6;
4748  }
4749  llvm_unreachable("unknown atomic op");
4750 }
4751 
4753  auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4754  if (auto AT = T->getAs<AtomicType>())
4755  return AT->getValueType();
4756  return T;
4757 }
4758 
4760  unsigned ArraySectionCount = 0;
4761  while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4762  Base = OASE->getBase();
4763  ++ArraySectionCount;
4764  }
4765  while (auto *ASE =
4766  dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4767  Base = ASE->getBase();
4768  ++ArraySectionCount;
4769  }
4770  Base = Base->IgnoreParenImpCasts();
4771  auto OriginalTy = Base->getType();
4772  if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4773  if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4774  OriginalTy = PVD->getOriginalType().getNonReferenceType();
4775 
4776  for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4777  if (OriginalTy->isAnyPointerType())
4778  OriginalTy = OriginalTy->getPointeeType();
4779  else {
4780  assert (OriginalTy->isArrayType());
4781  OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4782  }
4783  }
4784  return OriginalTy;
4785 }
4786 
4787 RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
4788  SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
4789  : Expr(RecoveryExprClass, T.getNonReferenceType(),
4790  T->isDependentType() ? VK_LValue : getValueKindForType(T),
4791  OK_Ordinary),
4792  BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
4793  assert(!T.isNull());
4794  assert(llvm::all_of(SubExprs, [](Expr* E) { return E != nullptr; }));
4795 
4796  llvm::copy(SubExprs, getTrailingObjects<Expr *>());
4798 }
4799 
4801  SourceLocation BeginLoc,
4802  SourceLocation EndLoc,
4803  ArrayRef<Expr *> SubExprs) {
4804  void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
4805  alignof(RecoveryExpr));
4806  return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
4807 }
4808 
4809 RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
4810  void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),
4811  alignof(RecoveryExpr));
4812  return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
4813 }
4814 
4815 void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
4816  assert(
4817  NumDims == Dims.size() &&
4818  "Preallocated number of dimensions is different from the provided one.");
4819  llvm::copy(Dims, getTrailingObjects<Expr *>());
4820 }
4821 
4822 void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
4823  assert(
4824  NumDims == BR.size() &&
4825  "Preallocated number of dimensions is different from the provided one.");
4826  llvm::copy(BR, getTrailingObjects<SourceRange>());
4827 }
4828 
4829 OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
4831  ArrayRef<Expr *> Dims)
4832  : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
4833  RPLoc(R), NumDims(Dims.size()) {
4834  setBase(Op);
4835  setDimensions(Dims);
4837 }
4838 
4842  ArrayRef<Expr *> Dims,
4843  ArrayRef<SourceRange> BracketRanges) {
4844  assert(Dims.size() == BracketRanges.size() &&
4845  "Different number of dimensions and brackets ranges.");
4846  void *Mem = Context.Allocate(
4847  totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),
4848  alignof(OMPArrayShapingExpr));
4849  auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
4850  E->setBracketsRanges(BracketRanges);
4851  return E;
4852 }
4853 
4855  unsigned NumDims) {
4856  void *Mem = Context.Allocate(
4857  totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),
4858  alignof(OMPArrayShapingExpr));
4859  return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
4860 }
4861 
4862 void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
4863  assert(I < NumIterators &&
4864  "Idx is greater or equal the number of iterators definitions.");
4865  getTrailingObjects<Decl *>()[I] = D;
4866 }
4867 
4868 void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
4869  assert(I < NumIterators &&
4870  "Idx is greater or equal the number of iterators definitions.");
4871  getTrailingObjects<
4872  SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4873  static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
4874 }
4875 
4876 void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
4877  SourceLocation ColonLoc, Expr *End,
4878  SourceLocation SecondColonLoc,
4879  Expr *Step) {
4880  assert(I < NumIterators &&
4881  "Idx is greater or equal the number of iterators definitions.");
4882  getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4883  static_cast<int>(RangeExprOffset::Begin)] =
4884  Begin;
4885  getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4886  static_cast<int>(RangeExprOffset::End)] = End;
4887  getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4888  static_cast<int>(RangeExprOffset::Step)] = Step;
4889  getTrailingObjects<
4890  SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4891  static_cast<int>(RangeLocOffset::FirstColonLoc)] =
4892  ColonLoc;
4893  getTrailingObjects<
4894  SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4895  static_cast<int>(RangeLocOffset::SecondColonLoc)] =
4896  SecondColonLoc;
4897 }
4898 
4900  return getTrailingObjects<Decl *>()[I];
4901 }
4902 
4904  IteratorRange Res;
4905  Res.Begin =
4906  getTrailingObjects<Expr *>()[I * static_cast<int>(
4907  RangeExprOffset::Total) +
4908  static_cast<int>(RangeExprOffset::Begin)];
4909  Res.End =
4910  getTrailingObjects<Expr *>()[I * static_cast<int>(
4911  RangeExprOffset::Total) +
4912  static_cast<int>(RangeExprOffset::End)];
4913  Res.Step =
4914  getTrailingObjects<Expr *>()[I * static_cast<int>(
4915  RangeExprOffset::Total) +
4916  static_cast<int>(RangeExprOffset::Step)];
4917  return Res;
4918 }
4919 
4921  return getTrailingObjects<
4922  SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4923  static_cast<int>(RangeLocOffset::AssignLoc)];
4924 }
4925 
4927  return getTrailingObjects<
4928  SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4929  static_cast<int>(RangeLocOffset::FirstColonLoc)];
4930 }
4931 
4933  return getTrailingObjects<
4934  SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4935  static_cast<int>(RangeLocOffset::SecondColonLoc)];
4936 }
4937 
4938 void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
4939  getTrailingObjects<OMPIteratorHelperData>()[I] = D;
4940 }
4941 
4943  return getTrailingObjects<OMPIteratorHelperData>()[I];
4944 }
4945 
4947  return getTrailingObjects<OMPIteratorHelperData>()[I];
4948 }
4949 
4950 OMPIteratorExpr::OMPIteratorExpr(
4951  QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
4954  : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
4955  IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
4956  NumIterators(Data.size()) {
4957  for (unsigned I = 0, E = Data.size(); I < E; ++I) {
4958  const IteratorDefinition &D = Data[I];
4959  setIteratorDeclaration(I, D.IteratorDecl);
4960  setAssignmentLoc(I, D.AssignmentLoc);
4961  setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,
4962  D.SecondColonLoc, D.Range.Step);
4963  setHelper(I, Helpers[I]);
4964  }
4966 }
4967 
4970  SourceLocation IteratorKwLoc, SourceLocation L,
4971  SourceLocation R,
4974  assert(Data.size() == Helpers.size() &&
4975  "Data and helpers must have the same size.");
4976  void *Mem = Context.Allocate(
4977  totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
4978  Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),
4979  Data.size() * static_cast<int>(RangeLocOffset::Total),
4980  Helpers.size()),
4981  alignof(OMPIteratorExpr));
4982  return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
4983 }
4984 
4986  unsigned NumIterators) {
4987  void *Mem = Context.Allocate(
4988  totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
4989  NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),
4990  NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),
4991  alignof(OMPIteratorExpr));
4992  return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);
4993 }
clang::Type::isIntegralType
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1918
clang::TemplateParameterList::shouldIncludeTypeForArgument
static bool shouldIncludeTypeForArgument(const TemplateParameterList *TPL, unsigned Idx)
Definition: DeclTemplate.cpp:204
clang::LabelStmt
LabelStmt - Represents a label, which has a substatement.
Definition: Stmt.h:1798
clang::CanQual::isVolatileQualified
bool isVolatileQualified() const
Definition: CanonicalType.h:141
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1148
clang::InitListExpr::setInit
void setInit(unsigned Init, Expr *expr)
Definition: Expr.h:4844
clang::NonOdrUseReason
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:149
clang::OMPIteratorExpr
OpenMP 5.0 [2.1.6 Iterators] Iterators are identifiers that expand to multiple values in the clause o...
Definition: ExprOpenMP.h:272
clang::SubstNonTypeTemplateParmExpr
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4245
clang::Expr::getValueKind
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:430
clang::Expr::getDependence
ExprDependence getDependence() const
Definition: Expr.h:155
clang::InitListExpr::getSyntacticForm
InitListExpr * getSyntacticForm() const
Definition: Expr.h:4947
clang::AtomicExpr::getPtr
Expr * getPtr() const
Definition: Expr.h:6261
clang::IgnoreLValueCastsSingleStep
Expr * IgnoreLValueCastsSingleStep(Expr *E)
Definition: IgnoreExpr.h:90
Builtins.h
clang::ObjCMessageExpr::isInstanceMessage
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition: ExprObjC.h:1238
clang::Type::isRecordType
bool isRecordType() const
Definition: Type.h:6763
clang::Decl::getASTContext
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:414
clang::Type::getAsArrayTypeUnsafe
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:7213
clang::RecordDecl::field_begin
field_iterator field_begin() const
Definition: Decl.cpp:4583
clang::StringLiteral::getCodeUnit
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1859
clang::CXXConstructorDecl
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2401
clang::BinaryOperator::isAssignmentOp
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3938
clang::CallExpr::setPreArg
void setPreArg(unsigned I, Stmt *PreArg)
Definition: Expr.h:2883
clang::CC_X86FastCall
@ CC_X86FastCall
Definition: Specifiers.h:257
clang::StringLiteral::UTF16
@ UTF16
Definition: Expr.h:1783
clang::CharacterLiteral::CharacterKind
CharacterKind
Definition: Expr.h:1580
clang::DesignatedInitExpr::Designator::isArrayRangeDesignator
bool isArrayRangeDesignator() const
Definition: Expr.h:5152
clang::Type::hasAttr
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition: Type.cpp:1770
clang::OffsetOfExpr::setComponent
void setComponent(unsigned Idx, OffsetOfNode ON)
Definition: Expr.h:2492
clang::OffsetOfExpr
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition: Expr.h:2438
clang::AtomicExpr::AtomicExpr
AtomicExpr(SourceLocation BLoc, ArrayRef< Expr * > args, QualType t, AtomicOp op, SourceLocation RP)
Definition: Expr.cpp:4677
clang::isPrintable
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:144
clang::DesignatedInitExpr::Designator::isArrayDesignator
bool isArrayDesignator() const
Definition: Expr.h:5151
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:27
clang::BinaryOperator::isCompoundAssignmentOp
bool isCompoundAssignmentOp() const
Definition: Expr.h:3946
clang::OK_Ordinary
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:127
clang::DeclContext::specific_decl_iterator
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2135
clang::OffsetOfExpr::Create
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1580
clang::ASTVector::rend
reverse_iterator rend()
Definition: ASTVector.h:105
type
clang::SYCLUniqueStableNameExpr::CreateEmpty
static SYCLUniqueStableNameExpr * CreateEmpty(const ASTContext &Ctx)
Definition: Expr.cpp:534
clang::DesignatedInitExpr::getSubExpr
Expr * getSubExpr(unsigned Idx) const
Definition: Expr.h:5279
clang::PseudoObjectExpr::semantics_begin
semantics_iterator semantics_begin()
Definition: Expr.h:6163
clang::SourceLocExpr::IdentKind
IdentKind
Definition: Expr.h:4683
clang::SourceLocExpr::SourceLocExpr
SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc, SourceLocation RParenLoc, DeclContext *Context)
Definition: Expr.cpp:2186
clang::CallExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1561
clang::Expr::isLValue
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:270
clang::Stmt::ParenListExprBits
ParenListExprBitfields ParenListExprBits
Definition: Stmt.h:1036
clang::DeclarationNameLoc
DeclarationNameLoc - Additional source/type location info for a declaration name.
Definition: DeclarationName.h:650
clang::FPOptionsOverride::requiresTrailingStorage
bool requiresTrailingStorage() const
Definition: LangOptions.h:624
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:212
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::Stmt::PseudoObjectExprBits
PseudoObjectExprBitfields PseudoObjectExprBits
Definition: Stmt.h:1038
clang::DeclContext
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1347
clang::DesignatedInitExpr::FieldDesignator
A field designator, e.g., ".x".
Definition: Expr.h:5063
clang::OMPArrayShapingExpr::CreateEmpty
static OMPArrayShapingExpr * CreateEmpty(const ASTContext &Context, unsigned NumDims)
Definition: Expr.cpp:4854
clang::PresumedLoc::getLine
unsigned getLine() const
Return the presumed line number of this location.
Definition: SourceLocation.h:339
clang::SourceLocExpr::getParentContext
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition: Expr.h:4718
clang::DeclRefExpr::getRAngleLoc
SourceLocation getRAngleLoc() const
Retrieve the location of the right angle bracket ending the explicit template argument list following...
Definition: Expr.h:1358
clang::StringLiteral::CreateEmpty
static StringLiteral * CreateEmpty(const ASTContext &Ctx, unsigned NumConcatenated, unsigned Length, unsigned CharByteWidth)
Construct an empty string literal.
Definition: Expr.cpp:1135
clang::Decl::hasAttr
bool hasAttr() const
Definition: DeclBase.h:547
clang::InitListExpr::hasArrayFiller
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:4892
clang::AtomicExpr::getValueType
QualType getValueType() const
Definition: Expr.cpp:4752
clang::CXXConstructExpr::getNumArgs
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1608
clang::ASTVector::resize
void resize(const ASTContext &C, unsigned N, const T &NV)
Definition: ASTVector.h:341
clang::SourceLocExpr::Column
@ Column
Definition: Expr.h:4683
clang::NestedNameSpecifier::isDependent
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
Definition: NestedNameSpecifier.cpp:234
clang::FunctionTemplateSpecializationInfo::TemplateArguments
const TemplateArgumentList * TemplateArguments
The template arguments used to produce the function template specialization from the function templat...
Definition: DeclTemplate.h:484
DependenceFlags.h
clang::FloatingLiteral::getValue
llvm::APFloat getValue() const
Definition: Expr.h:1647
clang::DesignatedInitUpdateExpr::getBase
Expr * getBase() const
Definition: Expr.h:5381
clang::UnaryOperator::Create
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4572
clang::OMPIteratorHelperData
Helper expressions and declaration for OMPIteratorExpr class for each iteration space.
Definition: ExprOpenMP.h:235
clang::BindingDecl
A binding in a decomposition declaration.
Definition: DeclCXX.h:3959
clang::DesignatedInitExpr
Represents a C99 designated initializer expression.
Definition: Expr.h:5024
include
include(CheckIncludeFiles) set(LLVM_LINK_COMPONENTS support) set(DIRECTORY_WATCHER_SOURCES DirectoryScanner.cpp) set(DIRECTORY_WATCHER_LINK_LIBS "") if(APPLE) check_include_files("CoreServices/CoreServices.h" HAVE_CORESERVICES) if(HAVE_CORESERVICES) list(APPEND DIRECTORY_WATCHER_SOURCES mac/DirectoryWatcher-mac.cpp) set(DIRECTORY_WATCHER_LINK_LIBS "-framework CoreServices") endif() elseif(CMAKE_SYSTEM_NAME MATCHES "Linux") check_include_files("sys/inotify.h" HAVE_INOTIFY) if(HAVE_INOTIFY) list(APPEND DIRECTORY_WATCHER_SOURCES linux/DirectoryWatcher-linux.cpp) find_package(Threads REQUIRED) endif() elseif(CMAKE_SYSTEM_NAME MATCHES "Windows") list(APPEND DIRECTORY_WATCHER_SOURCES windows/DirectoryWatcher-windows.cpp) else() list(APPEND DIRECTORY_WATCHER_SOURCES default/DirectoryWatcher-not-implemented.cpp) endif() add_clang_library(clangDirectoryWatcher $
Definition: CMakeLists.txt:1
clang::Expr::IgnoreImplicit
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:2916
clang::ASTContext::VoidTy
CanQualType VoidTy
Definition: ASTContext.h:1067
clang::Type::isCharType
bool isCharType() const
Definition: Type.cpp:1949
llvm::SmallVector
Definition: LLVM.h:38
clang::APValue::getInt
APSInt & getInt()
Definition: APValue.h:415
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:88
clang::OMPIteratorExpr::getIteratorRange
IteratorRange getIteratorRange(unsigned I)
Gets the iterator range for the given iterator.
Definition: Expr.cpp:4903
clang::CallExpr::hasStoredFPFeatures
bool hasStoredFPFeatures() const
Definition: Expr.h:2957
clang::Qualifiers::removeAddressSpace
void removeAddressSpace()
Definition: Type.h:386
clang::QualType::getQualifiers
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6452
clang::ASTContext::getIntWidth
unsigned getIntWidth(QualType T) const
Definition: ASTContext.cpp:10209
clang::Stmt::GenericSelectionExprBits
GenericSelectionExprBitfields GenericSelectionExprBits
Definition: Stmt.h:1037
clang::OpaqueValueExpr::findInCopyConstruct
static const OpaqueValueExpr * findInCopyConstruct(const Expr *expr)
Given an expression which invokes a copy constructor — i.e.
Definition: Expr.cpp:4584
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:249
clang::ASTContext::BuiltinInfo
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:649
clang::ParenListExpr
Definition: Expr.h:5532
clang::OffsetOfNode::getKind
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:2388
clang::OffsetOfExpr::CreateEmpty
static OffsetOfExpr * CreateEmpty(const ASTContext &C, unsigned NumComps, unsigned NumExprs)
Definition: Expr.cpp:1593
clang::Stmt::StmtClass
StmtClass
Definition: Stmt.h:70
EvaluatedExprVisitor.h
clang::MemberExpr::Create
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition: Expr.cpp:1655
TargetInfo.h
clang::MultiVersionKind::Target
@ Target
clang::ConstantExpr::getAPValueResult
APValue getAPValueResult() const
Definition: Expr.cpp:364
clang::CastExpr::getSubExpr
Expr * getSubExpr()
Definition: Expr.h:3524
clang::InitListExpr::reserveInits
void reserveInits(const ASTContext &C, unsigned NumInits)
Reserve space for some number of initializers.
Definition: Expr.cpp:2270
clang::FixedPointLiteral::CreateFromRawInt
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:914
clang::Stmt::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:324
clang::NestedNameSpecifier::isInstantiationDependent
bool isInstantiationDependent() const
Whether this nested name specifier involves a template parameter.
Definition: NestedNameSpecifier.cpp:238
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:673
Attr.h
clang::Expr::getObjectKind
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:437
clang::DeclarationNameInfo::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclarationName.h:867
clang::OMF_init
@ OMF_init
Definition: IdentifierTable.h:668
clang::QualType::getCanonicalType
QualType getCanonicalType() const
Definition: Type.h:6464
clang::FieldDecl
Represents a member of a struct/union/class.
Definition: Decl.h:2835
clang::CastExpr::path_empty
bool path_empty() const
Definition: Expr.h:3542
clang::ASTVector::rbegin
reverse_iterator rbegin()
Definition: ASTVector.h:103
clang::Qualifiers
The collection of all-type qualifiers we support.
Definition: Type.h:145
clang::FieldDecl::getInClassInitializer
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.h:2982
clang::Expr::skipRValueSubobjectAdjustments
const Expr * skipRValueSubobjectAdjustments() const
Definition: Expr.h:969
clang::ast_matchers::type
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchersInternal.cpp:772
clang::TargetInfo
Exposes information about the current target.
Definition: TargetInfo.h:189
clang::Stmt::ConstantExprBits
ConstantExprBitfields ConstantExprBits
Definition: Stmt.h:1022
DeclCXX.h
memcpy
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Definition: __clang_cuda_device_functions.h:1549
clang::TypeInfo::Width
uint64_t Width
Definition: ASTContext.h:182
clang::SourceLocExpr::File
@ File
Definition: Expr.h:4683
clang::BinaryOperator::getOpcodeStr
StringRef getOpcodeStr() const
Definition: Expr.h:3868
clang::InitListExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2349
clang::Stmt::StringLiteralBits
StringLiteralBitfields StringLiteralBits
Definition: Stmt.h:1026
clang::StringLiteral::getStrTokenLoc
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1908
clang::ExprObjectKind
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:125
clang::RecoveryExpr
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:6412
clang::BlockDecl::getBody
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: Decl.h:4232
clang::SourceManager::getExpansionRange
CharSourceRange getExpansionRange(SourceLocation Loc) const
Given a SourceLocation object, return the range of tokens covered by the expansion in the ultimate fi...
Definition: SourceManager.cpp:1041
clang::OMPIteratorExpr::CreateEmpty
static OMPIteratorExpr * CreateEmpty(const ASTContext &Context, unsigned NumIterators)
Definition: Expr.cpp:4985
clang::Expr::IgnoreParenNoopCasts
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parenthese and casts which do not change the value (including ptr->int casts of the sam...
Definition: Expr.cpp:2955
clang::InitListExpr
Describes an C or C++ initializer list.
Definition: Expr.h:4786
clang::DesignatedInitExpr::Designator::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Definition: Expr.h:5212
llvm::Optional< unsigned >
clang::OffsetOfNode::getFieldName
IdentifierInfo * getFieldName() const
For a field or identifier offsetof node, returns the name of the field.
Definition: Expr.cpp:1615
clang::ComparisonCategoryType::First
@ First
clang::CharacterLiteral::UTF8
@ UTF8
Definition: Expr.h:1583
clang::RQ_RValue
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1449
clang::MemberExpr::isImplicitAccess
bool isImplicitAccess() const
Determine whether the base of this explicit is implicit.
Definition: Expr.h:3360
clang::UnaryOperator
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2157
clang::Expr::isPRValue
bool isPRValue() const
Definition: Expr.h:271
SourceManager.h
clang::Expr::NPC_NeverValueDependent
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:776
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:6956
clang::Expr::getObjCProperty
const ObjCPropertyRefExpr * getObjCProperty() const
If this expression is an l-value for an Objective C property, find the underlying property reference ...
Definition: Expr.cpp:3874
clang::QualType::isVolatileQualified
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6495
clang::SourceManager::getPresumedLoc
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
Definition: SourceManager.cpp:1518
clang::APValue::None
@ None
There is no such object (it's outside its lifetime).
Definition: APValue.h:129
clang::CallExpr::getRParenLoc
SourceLocation getRParenLoc() const
Definition: Expr.h:3109
clang::RefQualifierKind
RefQualifierKind
The kind of C++11 ref-qualifier associated with a function type.
Definition: Type.h:1441
clang::Qualifiers::empty
bool empty() const
Definition: Type.h:423
clang::ImplicitCastExpr::CreateEmpty
static ImplicitCastExpr * CreateEmpty(const ASTContext &Context, unsigned PathSize, bool HasFPFeatures)
Definition: Expr.cpp:2028
clang::Expr::isCXX98IntegralConstantExpr
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
Definition: ExprConstant.cpp:15536
clang::FloatingLiteral::getValueAsApproximateDouble
double getValueAsApproximateDouble() const
getValueAsApproximateDouble - This returns the value as an inaccurate double.
Definition: Expr.cpp:1036
clang::Decl::getAttr
T * getAttr() const
Definition: DeclBase.h:543
clang::CC_X86ThisCall
@ CC_X86ThisCall
Definition: Specifiers.h:258
clang::Stmt::SourceLocExprBits
SourceLocExprBitfields SourceLocExprBits
Definition: Stmt.h:1039
skipTemporaryBindingsNoOpCastsAndParens
static const Expr * skipTemporaryBindingsNoOpCastsAndParens(const Expr *E)
Skip over any no-op casts and any temporary-binding expressions.
Definition: Expr.cpp:3036
clang::CallExpr::getCalleeDecl
Decl * getCalleeDecl()
Definition: Expr.h:2959
clang::CXXStaticCastExpr
A C++ static_cast expression (C++ [expr.static.cast]).
Definition: ExprCXX.h:431
clang::PrintingPolicy
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:59
clang::ConstantExpr::getResultAsAPSInt
llvm::APSInt getResultAsAPSInt() const
Definition: Expr.cpp:352
clang::DesignatedInitExpr::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:4368
clang::PseudoObjectExpr::semantics_end
semantics_iterator semantics_end()
Definition: Expr.h:6169
clang::BinaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:3847
clang::Lexer::LexFromRawLexer
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
Definition: Lexer.h:198
clang::StringLiteral::Wide
@ Wide
Definition: Expr.h:1783
clang::FunctionType
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3546
clang::CompoundStmt::body_empty
bool body_empty() const
Definition: Stmt.h:1425
clang::CapturedDecl
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4342
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
clang::SubobjectAdjustment
An adjustment to be made to the temporary created when emitting a reference binding,...
Definition: Expr.h:64
clang::CXXBindTemporaryExpr::getTemporary
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1430
clang::DesignatedInitExpr::getArrayRangeEnd
Expr * getArrayRangeEnd(const Designator &D) const
Definition: Expr.cpp:4383
clang::Expr::IgnoreImpCasts
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:2908
LiteralSupport.h
clang::APValue::IndeterminateValue
static APValue IndeterminateValue()
Definition: APValue.h:358
clang::CastExpr::getTrailingFPFeatures
FPOptionsOverride * getTrailingFPFeatures()
Return a pointer to the trailing FPOptions.
Definition: Expr.cpp:1986
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::OMPIteratorExpr::Create
static OMPIteratorExpr * Create(const ASTContext &Context, QualType T, SourceLocation IteratorKwLoc, SourceLocation L, SourceLocation R, ArrayRef< IteratorDefinition > Data, ArrayRef< OMPIteratorHelperData > Helpers)
Definition: Expr.cpp:4969
clang::ASTContext::getSourceManager
SourceManager & getSourceManager()
Definition: ASTContext.h:694
clang::Stmt::UnaryOperatorBits
UnaryOperatorBitfields UnaryOperatorBits
Definition: Stmt.h:1028
clang::MemberExpr::getMemberNameInfo
DeclarationNameInfo getMemberNameInfo() const
Retrieve the member declaration name info.
Definition: Expr.h:3339
clang::CallExpr::hasUnusedResultAttr
bool hasUnusedResultAttr(const ASTContext &Ctx) const
Returns true if this call expression should warn on unused results.
Definition: Expr.h:3105
clang::InitListExpr::isTransparent
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition: Expr.cpp:2315
clang::Expr::isGLValue
bool isGLValue() const
Definition: Expr.h:273
clang::BinaryOperator::isNullPointerArithmeticExtension
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, Expr *LHS, Expr *RHS)
Definition: Expr.cpp:2138
clang::DeclRefExpr::CreateEmpty
static DeclRefExpr * CreateEmpty(const ASTContext &Context, bool HasQualifier, bool HasFoundDecl, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs)
Construct an empty declaration reference expression.
Definition: Expr.cpp:476
clang::MemberExpr::hasQualifier
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3259
clang::Expr::findBoundMemberType
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:2884
clang::DesignatedInitExpr::FieldDesignator::NameOrField
uintptr_t NameOrField
Refers to the field that is being initialized.
Definition: Expr.h:5070
clang::cast_away_const
StmtIterator cast_away_const(const ConstStmtIterator &RHS)
Definition: StmtIterator.h:155
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:626
clang::Stmt::EmptyShell
A placeholder type used to construct an empty shell of a type, that will be filled in later (e....
Definition: Stmt.h:1102
Paren
@ Paren
Definition: PPMacroExpansion.cpp:633
clang::CC_X86StdCall
@ CC_X86StdCall
Definition: Specifiers.h:256
clang::FixedPointLiteral::Create
static FixedPointLiteral * Create(const ASTContext &C, EmptyShell Empty)
Returns an empty fixed-point literal.
Definition: Expr.cpp:922
clang::DesignatedInitUpdateExpr::DesignatedInitUpdateExpr
DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, Expr *baseExprs, SourceLocation rBraceLoc)
Definition: Expr.cpp:4417
clang::StringLiteral::Ascii
@ Ascii
Definition: Expr.h:1783