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