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