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