1 //===- Stmt.cpp - Statement 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 Stmt class and statement subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/Stmt.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTDiagnostic.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclGroup.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprConcepts.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExprOpenMP.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/StmtOpenMP.h"
27 #include "clang/AST/Type.h"
28 #include "clang/Basic/CharInfo.h"
29 #include "clang/Basic/LLVM.h"
30 #include "clang/Basic/SourceLocation.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/Token.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <algorithm>
42 #include <cassert>
43 #include <cstring>
44 #include <string>
45 #include <type_traits>
46 #include <utility>
47 
48 using namespace clang;
49 
50 static struct StmtClassNameTable {
51   const char *Name;
52   unsigned Counter;
53   unsigned Size;
54 } StmtClassInfo[Stmt::lastStmtConstant+1];
55 
getStmtInfoTableEntry(Stmt::StmtClass E)56 static StmtClassNameTable &getStmtInfoTableEntry(Stmt::StmtClass E) {
57   static bool Initialized = false;
58   if (Initialized)
59     return StmtClassInfo[E];
60 
61   // Initialize the table on the first use.
62   Initialized = true;
63 #define ABSTRACT_STMT(STMT)
64 #define STMT(CLASS, PARENT) \
65   StmtClassInfo[(unsigned)Stmt::CLASS##Class].Name = #CLASS;    \
66   StmtClassInfo[(unsigned)Stmt::CLASS##Class].Size = sizeof(CLASS);
67 #include "clang/AST/StmtNodes.inc"
68 
69   return StmtClassInfo[E];
70 }
71 
operator new(size_t bytes,const ASTContext & C,unsigned alignment)72 void *Stmt::operator new(size_t bytes, const ASTContext& C,
73                          unsigned alignment) {
74   return ::operator new(bytes, C, alignment);
75 }
76 
getStmtClassName() const77 const char *Stmt::getStmtClassName() const {
78   return getStmtInfoTableEntry((StmtClass) StmtBits.sClass).Name;
79 }
80 
81 // Check that no statement / expression class is polymorphic. LLVM style RTTI
82 // should be used instead. If absolutely needed an exception can still be added
83 // here by defining the appropriate macro (but please don't do this).
84 #define STMT(CLASS, PARENT) \
85   static_assert(!std::is_polymorphic<CLASS>::value, \
86                 #CLASS " should not be polymorphic!");
87 #include "clang/AST/StmtNodes.inc"
88 
89 // Check that no statement / expression class has a non-trival destructor.
90 // Statements and expressions are allocated with the BumpPtrAllocator from
91 // ASTContext and therefore their destructor is not executed.
92 #define STMT(CLASS, PARENT)                                                    \
93   static_assert(std::is_trivially_destructible<CLASS>::value,                  \
94                 #CLASS " should be trivially destructible!");
95 // FIXME: InitListExpr is not trivially destructible due to its ASTVector.
96 #define INITLISTEXPR(CLASS, PARENT)
97 #include "clang/AST/StmtNodes.inc"
98 
PrintStats()99 void Stmt::PrintStats() {
100   // Ensure the table is primed.
101   getStmtInfoTableEntry(Stmt::NullStmtClass);
102 
103   unsigned sum = 0;
104   llvm::errs() << "\n*** Stmt/Expr Stats:\n";
105   for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
106     if (StmtClassInfo[i].Name == nullptr) continue;
107     sum += StmtClassInfo[i].Counter;
108   }
109   llvm::errs() << "  " << sum << " stmts/exprs total.\n";
110   sum = 0;
111   for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
112     if (StmtClassInfo[i].Name == nullptr) continue;
113     if (StmtClassInfo[i].Counter == 0) continue;
114     llvm::errs() << "    " << StmtClassInfo[i].Counter << " "
115                  << StmtClassInfo[i].Name << ", " << StmtClassInfo[i].Size
116                  << " each (" << StmtClassInfo[i].Counter*StmtClassInfo[i].Size
117                  << " bytes)\n";
118     sum += StmtClassInfo[i].Counter*StmtClassInfo[i].Size;
119   }
120 
121   llvm::errs() << "Total bytes = " << sum << "\n";
122 }
123 
addStmtClass(StmtClass s)124 void Stmt::addStmtClass(StmtClass s) {
125   ++getStmtInfoTableEntry(s).Counter;
126 }
127 
128 bool Stmt::StatisticsEnabled = false;
EnableStatistics()129 void Stmt::EnableStatistics() {
130   StatisticsEnabled = true;
131 }
132 
133 static std::pair<Stmt::Likelihood, const Attr *>
getLikelihood(ArrayRef<const Attr * > Attrs)134 getLikelihood(ArrayRef<const Attr *> Attrs) {
135   for (const auto *A : Attrs) {
136     if (isa<LikelyAttr>(A))
137       return std::make_pair(Stmt::LH_Likely, A);
138 
139     if (isa<UnlikelyAttr>(A))
140       return std::make_pair(Stmt::LH_Unlikely, A);
141   }
142 
143   return std::make_pair(Stmt::LH_None, nullptr);
144 }
145 
getLikelihood(const Stmt * S)146 static std::pair<Stmt::Likelihood, const Attr *> getLikelihood(const Stmt *S) {
147   if (const auto *AS = dyn_cast_or_null<AttributedStmt>(S))
148     return getLikelihood(AS->getAttrs());
149 
150   return std::make_pair(Stmt::LH_None, nullptr);
151 }
152 
getLikelihood(ArrayRef<const Attr * > Attrs)153 Stmt::Likelihood Stmt::getLikelihood(ArrayRef<const Attr *> Attrs) {
154   return ::getLikelihood(Attrs).first;
155 }
156 
getLikelihood(const Stmt * S)157 Stmt::Likelihood Stmt::getLikelihood(const Stmt *S) {
158   return ::getLikelihood(S).first;
159 }
160 
getLikelihoodAttr(const Stmt * S)161 const Attr *Stmt::getLikelihoodAttr(const Stmt *S) {
162   return ::getLikelihood(S).second;
163 }
164 
getLikelihood(const Stmt * Then,const Stmt * Else)165 Stmt::Likelihood Stmt::getLikelihood(const Stmt *Then, const Stmt *Else) {
166   Likelihood LHT = ::getLikelihood(Then).first;
167   Likelihood LHE = ::getLikelihood(Else).first;
168   if (LHE == LH_None)
169     return LHT;
170 
171   // If the same attribute is used on both branches there's a conflict.
172   if (LHT == LHE)
173     return LH_None;
174 
175   if (LHT != LH_None)
176     return LHT;
177 
178   // Invert the value of Else to get the value for Then.
179   return LHE == LH_Likely ? LH_Unlikely : LH_Likely;
180 }
181 
182 std::tuple<bool, const Attr *, const Attr *>
determineLikelihoodConflict(const Stmt * Then,const Stmt * Else)183 Stmt::determineLikelihoodConflict(const Stmt *Then, const Stmt *Else) {
184   std::pair<Likelihood, const Attr *> LHT = ::getLikelihood(Then);
185   std::pair<Likelihood, const Attr *> LHE = ::getLikelihood(Else);
186   // If the same attribute is used on both branches there's a conflict.
187   if (LHT.first != LH_None && LHT.first == LHE.first)
188     return std::make_tuple(true, LHT.second, LHE.second);
189 
190   return std::make_tuple(false, nullptr, nullptr);
191 }
192 
193 /// Skip no-op (attributed, compound) container stmts and skip captured
194 /// stmt at the top, if \a IgnoreCaptured is true.
IgnoreContainers(bool IgnoreCaptured)195 Stmt *Stmt::IgnoreContainers(bool IgnoreCaptured) {
196   Stmt *S = this;
197   if (IgnoreCaptured)
198     if (auto CapS = dyn_cast_or_null<CapturedStmt>(S))
199       S = CapS->getCapturedStmt();
200   while (true) {
201     if (auto AS = dyn_cast_or_null<AttributedStmt>(S))
202       S = AS->getSubStmt();
203     else if (auto CS = dyn_cast_or_null<CompoundStmt>(S)) {
204       if (CS->size() != 1)
205         break;
206       S = CS->body_back();
207     } else
208       break;
209   }
210   return S;
211 }
212 
213 /// Strip off all label-like statements.
214 ///
215 /// This will strip off label statements, case statements, attributed
216 /// statements and default statements recursively.
stripLabelLikeStatements() const217 const Stmt *Stmt::stripLabelLikeStatements() const {
218   const Stmt *S = this;
219   while (true) {
220     if (const auto *LS = dyn_cast<LabelStmt>(S))
221       S = LS->getSubStmt();
222     else if (const auto *SC = dyn_cast<SwitchCase>(S))
223       S = SC->getSubStmt();
224     else if (const auto *AS = dyn_cast<AttributedStmt>(S))
225       S = AS->getSubStmt();
226     else
227       return S;
228   }
229 }
230 
231 namespace {
232 
233   struct good {};
234   struct bad {};
235 
236   // These silly little functions have to be static inline to suppress
237   // unused warnings, and they have to be defined to suppress other
238   // warnings.
is_good(good)239   static good is_good(good) { return good(); }
240 
241   typedef Stmt::child_range children_t();
implements_children(children_t T::*)242   template <class T> good implements_children(children_t T::*) {
243     return good();
244   }
245   LLVM_ATTRIBUTE_UNUSED
implements_children(children_t Stmt::*)246   static bad implements_children(children_t Stmt::*) {
247     return bad();
248   }
249 
250   typedef SourceLocation getBeginLoc_t() const;
implements_getBeginLoc(getBeginLoc_t T::*)251   template <class T> good implements_getBeginLoc(getBeginLoc_t T::*) {
252     return good();
253   }
254   LLVM_ATTRIBUTE_UNUSED
implements_getBeginLoc(getBeginLoc_t Stmt::*)255   static bad implements_getBeginLoc(getBeginLoc_t Stmt::*) { return bad(); }
256 
257   typedef SourceLocation getLocEnd_t() const;
implements_getEndLoc(getLocEnd_t T::*)258   template <class T> good implements_getEndLoc(getLocEnd_t T::*) {
259     return good();
260   }
261   LLVM_ATTRIBUTE_UNUSED
implements_getEndLoc(getLocEnd_t Stmt::*)262   static bad implements_getEndLoc(getLocEnd_t Stmt::*) { return bad(); }
263 
264 #define ASSERT_IMPLEMENTS_children(type) \
265   (void) is_good(implements_children(&type::children))
266 #define ASSERT_IMPLEMENTS_getBeginLoc(type)                                    \
267   (void)is_good(implements_getBeginLoc(&type::getBeginLoc))
268 #define ASSERT_IMPLEMENTS_getEndLoc(type)                                      \
269   (void)is_good(implements_getEndLoc(&type::getEndLoc))
270 
271 } // namespace
272 
273 /// Check whether the various Stmt classes implement their member
274 /// functions.
275 LLVM_ATTRIBUTE_UNUSED
check_implementations()276 static inline void check_implementations() {
277 #define ABSTRACT_STMT(type)
278 #define STMT(type, base)                                                       \
279   ASSERT_IMPLEMENTS_children(type);                                            \
280   ASSERT_IMPLEMENTS_getBeginLoc(type);                                         \
281   ASSERT_IMPLEMENTS_getEndLoc(type);
282 #include "clang/AST/StmtNodes.inc"
283 }
284 
children()285 Stmt::child_range Stmt::children() {
286   switch (getStmtClass()) {
287   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
288 #define ABSTRACT_STMT(type)
289 #define STMT(type, base) \
290   case Stmt::type##Class: \
291     return static_cast<type*>(this)->children();
292 #include "clang/AST/StmtNodes.inc"
293   }
294   llvm_unreachable("unknown statement kind!");
295 }
296 
297 // Amusing macro metaprogramming hack: check whether a class provides
298 // a more specific implementation of getSourceRange.
299 //
300 // See also Expr.cpp:getExprLoc().
301 namespace {
302 
303   /// This implementation is used when a class provides a custom
304   /// implementation of getSourceRange.
305   template <class S, class T>
getSourceRangeImpl(const Stmt * stmt,SourceRange (T::* v)()const)306   SourceRange getSourceRangeImpl(const Stmt *stmt,
307                                  SourceRange (T::*v)() const) {
308     return static_cast<const S*>(stmt)->getSourceRange();
309   }
310 
311   /// This implementation is used when a class doesn't provide a custom
312   /// implementation of getSourceRange.  Overload resolution should pick it over
313   /// the implementation above because it's more specialized according to
314   /// function template partial ordering.
315   template <class S>
getSourceRangeImpl(const Stmt * stmt,SourceRange (Stmt::* v)()const)316   SourceRange getSourceRangeImpl(const Stmt *stmt,
317                                  SourceRange (Stmt::*v)() const) {
318     return SourceRange(static_cast<const S *>(stmt)->getBeginLoc(),
319                        static_cast<const S *>(stmt)->getEndLoc());
320   }
321 
322 } // namespace
323 
getSourceRange() const324 SourceRange Stmt::getSourceRange() const {
325   switch (getStmtClass()) {
326   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
327 #define ABSTRACT_STMT(type)
328 #define STMT(type, base) \
329   case Stmt::type##Class: \
330     return getSourceRangeImpl<type>(this, &type::getSourceRange);
331 #include "clang/AST/StmtNodes.inc"
332   }
333   llvm_unreachable("unknown statement kind!");
334 }
335 
getBeginLoc() const336 SourceLocation Stmt::getBeginLoc() const {
337   switch (getStmtClass()) {
338   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
339 #define ABSTRACT_STMT(type)
340 #define STMT(type, base)                                                       \
341   case Stmt::type##Class:                                                      \
342     return static_cast<const type *>(this)->getBeginLoc();
343 #include "clang/AST/StmtNodes.inc"
344   }
345   llvm_unreachable("unknown statement kind");
346 }
347 
getEndLoc() const348 SourceLocation Stmt::getEndLoc() const {
349   switch (getStmtClass()) {
350   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
351 #define ABSTRACT_STMT(type)
352 #define STMT(type, base)                                                       \
353   case Stmt::type##Class:                                                      \
354     return static_cast<const type *>(this)->getEndLoc();
355 #include "clang/AST/StmtNodes.inc"
356   }
357   llvm_unreachable("unknown statement kind");
358 }
359 
getID(const ASTContext & Context) const360 int64_t Stmt::getID(const ASTContext &Context) const {
361   return Context.getAllocator().identifyKnownAlignedObject<Stmt>(this);
362 }
363 
CompoundStmt(ArrayRef<Stmt * > Stmts,SourceLocation LB,SourceLocation RB)364 CompoundStmt::CompoundStmt(ArrayRef<Stmt *> Stmts, SourceLocation LB,
365                            SourceLocation RB)
366     : Stmt(CompoundStmtClass), RBraceLoc(RB) {
367   CompoundStmtBits.NumStmts = Stmts.size();
368   setStmts(Stmts);
369   CompoundStmtBits.LBraceLoc = LB;
370 }
371 
setStmts(ArrayRef<Stmt * > Stmts)372 void CompoundStmt::setStmts(ArrayRef<Stmt *> Stmts) {
373   assert(CompoundStmtBits.NumStmts == Stmts.size() &&
374          "NumStmts doesn't fit in bits of CompoundStmtBits.NumStmts!");
375 
376   std::copy(Stmts.begin(), Stmts.end(), body_begin());
377 }
378 
Create(const ASTContext & C,ArrayRef<Stmt * > Stmts,SourceLocation LB,SourceLocation RB)379 CompoundStmt *CompoundStmt::Create(const ASTContext &C, ArrayRef<Stmt *> Stmts,
380                                    SourceLocation LB, SourceLocation RB) {
381   void *Mem =
382       C.Allocate(totalSizeToAlloc<Stmt *>(Stmts.size()), alignof(CompoundStmt));
383   return new (Mem) CompoundStmt(Stmts, LB, RB);
384 }
385 
CreateEmpty(const ASTContext & C,unsigned NumStmts)386 CompoundStmt *CompoundStmt::CreateEmpty(const ASTContext &C,
387                                         unsigned NumStmts) {
388   void *Mem =
389       C.Allocate(totalSizeToAlloc<Stmt *>(NumStmts), alignof(CompoundStmt));
390   CompoundStmt *New = new (Mem) CompoundStmt(EmptyShell());
391   New->CompoundStmtBits.NumStmts = NumStmts;
392   return New;
393 }
394 
getExprStmt() const395 const Expr *ValueStmt::getExprStmt() const {
396   const Stmt *S = this;
397   do {
398     if (const auto *E = dyn_cast<Expr>(S))
399       return E;
400 
401     if (const auto *LS = dyn_cast<LabelStmt>(S))
402       S = LS->getSubStmt();
403     else if (const auto *AS = dyn_cast<AttributedStmt>(S))
404       S = AS->getSubStmt();
405     else
406       llvm_unreachable("unknown kind of ValueStmt");
407   } while (isa<ValueStmt>(S));
408 
409   return nullptr;
410 }
411 
getName() const412 const char *LabelStmt::getName() const {
413   return getDecl()->getIdentifier()->getNameStart();
414 }
415 
Create(const ASTContext & C,SourceLocation Loc,ArrayRef<const Attr * > Attrs,Stmt * SubStmt)416 AttributedStmt *AttributedStmt::Create(const ASTContext &C, SourceLocation Loc,
417                                        ArrayRef<const Attr*> Attrs,
418                                        Stmt *SubStmt) {
419   assert(!Attrs.empty() && "Attrs should not be empty");
420   void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(Attrs.size()),
421                          alignof(AttributedStmt));
422   return new (Mem) AttributedStmt(Loc, Attrs, SubStmt);
423 }
424 
CreateEmpty(const ASTContext & C,unsigned NumAttrs)425 AttributedStmt *AttributedStmt::CreateEmpty(const ASTContext &C,
426                                             unsigned NumAttrs) {
427   assert(NumAttrs > 0 && "NumAttrs should be greater than zero");
428   void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(NumAttrs),
429                          alignof(AttributedStmt));
430   return new (Mem) AttributedStmt(EmptyShell(), NumAttrs);
431 }
432 
generateAsmString(const ASTContext & C) const433 std::string AsmStmt::generateAsmString(const ASTContext &C) const {
434   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
435     return gccAsmStmt->generateAsmString(C);
436   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
437     return msAsmStmt->generateAsmString(C);
438   llvm_unreachable("unknown asm statement kind!");
439 }
440 
getOutputConstraint(unsigned i) const441 StringRef AsmStmt::getOutputConstraint(unsigned i) const {
442   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
443     return gccAsmStmt->getOutputConstraint(i);
444   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
445     return msAsmStmt->getOutputConstraint(i);
446   llvm_unreachable("unknown asm statement kind!");
447 }
448 
getOutputExpr(unsigned i) const449 const Expr *AsmStmt::getOutputExpr(unsigned i) const {
450   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
451     return gccAsmStmt->getOutputExpr(i);
452   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
453     return msAsmStmt->getOutputExpr(i);
454   llvm_unreachable("unknown asm statement kind!");
455 }
456 
getInputConstraint(unsigned i) const457 StringRef AsmStmt::getInputConstraint(unsigned i) const {
458   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
459     return gccAsmStmt->getInputConstraint(i);
460   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
461     return msAsmStmt->getInputConstraint(i);
462   llvm_unreachable("unknown asm statement kind!");
463 }
464 
getInputExpr(unsigned i) const465 const Expr *AsmStmt::getInputExpr(unsigned i) const {
466   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
467     return gccAsmStmt->getInputExpr(i);
468   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
469     return msAsmStmt->getInputExpr(i);
470   llvm_unreachable("unknown asm statement kind!");
471 }
472 
getClobber(unsigned i) const473 StringRef AsmStmt::getClobber(unsigned i) const {
474   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
475     return gccAsmStmt->getClobber(i);
476   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
477     return msAsmStmt->getClobber(i);
478   llvm_unreachable("unknown asm statement kind!");
479 }
480 
481 /// getNumPlusOperands - Return the number of output operands that have a "+"
482 /// constraint.
getNumPlusOperands() const483 unsigned AsmStmt::getNumPlusOperands() const {
484   unsigned Res = 0;
485   for (unsigned i = 0, e = getNumOutputs(); i != e; ++i)
486     if (isOutputPlusConstraint(i))
487       ++Res;
488   return Res;
489 }
490 
getModifier() const491 char GCCAsmStmt::AsmStringPiece::getModifier() const {
492   assert(isOperand() && "Only Operands can have modifiers.");
493   return isLetter(Str[0]) ? Str[0] : '\0';
494 }
495 
getClobber(unsigned i) const496 StringRef GCCAsmStmt::getClobber(unsigned i) const {
497   return getClobberStringLiteral(i)->getString();
498 }
499 
getOutputExpr(unsigned i)500 Expr *GCCAsmStmt::getOutputExpr(unsigned i) {
501   return cast<Expr>(Exprs[i]);
502 }
503 
504 /// getOutputConstraint - Return the constraint string for the specified
505 /// output operand.  All output constraints are known to be non-empty (either
506 /// '=' or '+').
getOutputConstraint(unsigned i) const507 StringRef GCCAsmStmt::getOutputConstraint(unsigned i) const {
508   return getOutputConstraintLiteral(i)->getString();
509 }
510 
getInputExpr(unsigned i)511 Expr *GCCAsmStmt::getInputExpr(unsigned i) {
512   return cast<Expr>(Exprs[i + NumOutputs]);
513 }
514 
setInputExpr(unsigned i,Expr * E)515 void GCCAsmStmt::setInputExpr(unsigned i, Expr *E) {
516   Exprs[i + NumOutputs] = E;
517 }
518 
getLabelExpr(unsigned i) const519 AddrLabelExpr *GCCAsmStmt::getLabelExpr(unsigned i) const {
520   return cast<AddrLabelExpr>(Exprs[i + NumOutputs + NumInputs]);
521 }
522 
getLabelName(unsigned i) const523 StringRef GCCAsmStmt::getLabelName(unsigned i) const {
524   return getLabelExpr(i)->getLabel()->getName();
525 }
526 
527 /// getInputConstraint - Return the specified input constraint.  Unlike output
528 /// constraints, these can be empty.
getInputConstraint(unsigned i) const529 StringRef GCCAsmStmt::getInputConstraint(unsigned i) const {
530   return getInputConstraintLiteral(i)->getString();
531 }
532 
setOutputsAndInputsAndClobbers(const ASTContext & C,IdentifierInfo ** Names,StringLiteral ** Constraints,Stmt ** Exprs,unsigned NumOutputs,unsigned NumInputs,unsigned NumLabels,StringLiteral ** Clobbers,unsigned NumClobbers)533 void GCCAsmStmt::setOutputsAndInputsAndClobbers(const ASTContext &C,
534                                                 IdentifierInfo **Names,
535                                                 StringLiteral **Constraints,
536                                                 Stmt **Exprs,
537                                                 unsigned NumOutputs,
538                                                 unsigned NumInputs,
539                                                 unsigned NumLabels,
540                                                 StringLiteral **Clobbers,
541                                                 unsigned NumClobbers) {
542   this->NumOutputs = NumOutputs;
543   this->NumInputs = NumInputs;
544   this->NumClobbers = NumClobbers;
545   this->NumLabels = NumLabels;
546 
547   unsigned NumExprs = NumOutputs + NumInputs + NumLabels;
548 
549   C.Deallocate(this->Names);
550   this->Names = new (C) IdentifierInfo*[NumExprs];
551   std::copy(Names, Names + NumExprs, this->Names);
552 
553   C.Deallocate(this->Exprs);
554   this->Exprs = new (C) Stmt*[NumExprs];
555   std::copy(Exprs, Exprs + NumExprs, this->Exprs);
556 
557   unsigned NumConstraints = NumOutputs + NumInputs;
558   C.Deallocate(this->Constraints);
559   this->Constraints = new (C) StringLiteral*[NumConstraints];
560   std::copy(Constraints, Constraints + NumConstraints, this->Constraints);
561 
562   C.Deallocate(this->Clobbers);
563   this->Clobbers = new (C) StringLiteral*[NumClobbers];
564   std::copy(Clobbers, Clobbers + NumClobbers, this->Clobbers);
565 }
566 
567 /// getNamedOperand - Given a symbolic operand reference like %[foo],
568 /// translate this into a numeric value needed to reference the same operand.
569 /// This returns -1 if the operand name is invalid.
getNamedOperand(StringRef SymbolicName) const570 int GCCAsmStmt::getNamedOperand(StringRef SymbolicName) const {
571   unsigned NumPlusOperands = 0;
572 
573   // Check if this is an output operand.
574   for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) {
575     if (getOutputName(i) == SymbolicName)
576       return i;
577   }
578 
579   for (unsigned i = 0, e = getNumInputs(); i != e; ++i)
580     if (getInputName(i) == SymbolicName)
581       return getNumOutputs() + NumPlusOperands + i;
582 
583   for (unsigned i = 0, e = getNumLabels(); i != e; ++i)
584     if (getLabelName(i) == SymbolicName)
585       return i + getNumOutputs() + getNumInputs();
586 
587   // Not found.
588   return -1;
589 }
590 
591 /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
592 /// it into pieces.  If the asm string is erroneous, emit errors and return
593 /// true, otherwise return false.
AnalyzeAsmString(SmallVectorImpl<AsmStringPiece> & Pieces,const ASTContext & C,unsigned & DiagOffs) const594 unsigned GCCAsmStmt::AnalyzeAsmString(SmallVectorImpl<AsmStringPiece>&Pieces,
595                                 const ASTContext &C, unsigned &DiagOffs) const {
596   StringRef Str = getAsmString()->getString();
597   const char *StrStart = Str.begin();
598   const char *StrEnd = Str.end();
599   const char *CurPtr = StrStart;
600 
601   // "Simple" inline asms have no constraints or operands, just convert the asm
602   // string to escape $'s.
603   if (isSimple()) {
604     std::string Result;
605     for (; CurPtr != StrEnd; ++CurPtr) {
606       switch (*CurPtr) {
607       case '$':
608         Result += "$$";
609         break;
610       default:
611         Result += *CurPtr;
612         break;
613       }
614     }
615     Pieces.push_back(AsmStringPiece(Result));
616     return 0;
617   }
618 
619   // CurStringPiece - The current string that we are building up as we scan the
620   // asm string.
621   std::string CurStringPiece;
622 
623   bool HasVariants = !C.getTargetInfo().hasNoAsmVariants();
624 
625   unsigned LastAsmStringToken = 0;
626   unsigned LastAsmStringOffset = 0;
627 
628   while (true) {
629     // Done with the string?
630     if (CurPtr == StrEnd) {
631       if (!CurStringPiece.empty())
632         Pieces.push_back(AsmStringPiece(CurStringPiece));
633       return 0;
634     }
635 
636     char CurChar = *CurPtr++;
637     switch (CurChar) {
638     case '$': CurStringPiece += "$$"; continue;
639     case '{': CurStringPiece += (HasVariants ? "$(" : "{"); continue;
640     case '|': CurStringPiece += (HasVariants ? "$|" : "|"); continue;
641     case '}': CurStringPiece += (HasVariants ? "$)" : "}"); continue;
642     case '%':
643       break;
644     default:
645       CurStringPiece += CurChar;
646       continue;
647     }
648 
649     const TargetInfo &TI = C.getTargetInfo();
650 
651     // Escaped "%" character in asm string.
652     if (CurPtr == StrEnd) {
653       // % at end of string is invalid (no escape).
654       DiagOffs = CurPtr-StrStart-1;
655       return diag::err_asm_invalid_escape;
656     }
657     // Handle escaped char and continue looping over the asm string.
658     char EscapedChar = *CurPtr++;
659     switch (EscapedChar) {
660     default:
661       // Handle target-specific escaped characters.
662       if (auto MaybeReplaceStr = TI.handleAsmEscapedChar(EscapedChar)) {
663         CurStringPiece += *MaybeReplaceStr;
664         continue;
665       }
666       break;
667     case '%': // %% -> %
668     case '{': // %{ -> {
669     case '}': // %} -> }
670       CurStringPiece += EscapedChar;
671       continue;
672     case '=': // %= -> Generate a unique ID.
673       CurStringPiece += "${:uid}";
674       continue;
675     }
676 
677     // Otherwise, we have an operand.  If we have accumulated a string so far,
678     // add it to the Pieces list.
679     if (!CurStringPiece.empty()) {
680       Pieces.push_back(AsmStringPiece(CurStringPiece));
681       CurStringPiece.clear();
682     }
683 
684     // Handle operands that have asmSymbolicName (e.g., %x[foo]) and those that
685     // don't (e.g., %x4). 'x' following the '%' is the constraint modifier.
686 
687     const char *Begin = CurPtr - 1; // Points to the character following '%'.
688     const char *Percent = Begin - 1; // Points to '%'.
689 
690     if (isLetter(EscapedChar)) {
691       if (CurPtr == StrEnd) { // Premature end.
692         DiagOffs = CurPtr-StrStart-1;
693         return diag::err_asm_invalid_escape;
694       }
695       EscapedChar = *CurPtr++;
696     }
697 
698     const SourceManager &SM = C.getSourceManager();
699     const LangOptions &LO = C.getLangOpts();
700 
701     // Handle operands that don't have asmSymbolicName (e.g., %x4).
702     if (isDigit(EscapedChar)) {
703       // %n - Assembler operand n
704       unsigned N = 0;
705 
706       --CurPtr;
707       while (CurPtr != StrEnd && isDigit(*CurPtr))
708         N = N*10 + ((*CurPtr++)-'0');
709 
710       unsigned NumOperands = getNumOutputs() + getNumPlusOperands() +
711                              getNumInputs() + getNumLabels();
712       if (N >= NumOperands) {
713         DiagOffs = CurPtr-StrStart-1;
714         return diag::err_asm_invalid_operand_number;
715       }
716 
717       // Str contains "x4" (Operand without the leading %).
718       std::string Str(Begin, CurPtr - Begin);
719 
720       // (BeginLoc, EndLoc) represents the range of the operand we are currently
721       // processing. Unlike Str, the range includes the leading '%'.
722       SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
723           Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
724           &LastAsmStringOffset);
725       SourceLocation EndLoc = getAsmString()->getLocationOfByte(
726           CurPtr - StrStart, SM, LO, TI, &LastAsmStringToken,
727           &LastAsmStringOffset);
728 
729       Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
730       continue;
731     }
732 
733     // Handle operands that have asmSymbolicName (e.g., %x[foo]).
734     if (EscapedChar == '[') {
735       DiagOffs = CurPtr-StrStart-1;
736 
737       // Find the ']'.
738       const char *NameEnd = (const char*)memchr(CurPtr, ']', StrEnd-CurPtr);
739       if (NameEnd == nullptr)
740         return diag::err_asm_unterminated_symbolic_operand_name;
741       if (NameEnd == CurPtr)
742         return diag::err_asm_empty_symbolic_operand_name;
743 
744       StringRef SymbolicName(CurPtr, NameEnd - CurPtr);
745 
746       int N = getNamedOperand(SymbolicName);
747       if (N == -1) {
748         // Verify that an operand with that name exists.
749         DiagOffs = CurPtr-StrStart;
750         return diag::err_asm_unknown_symbolic_operand_name;
751       }
752 
753       // Str contains "x[foo]" (Operand without the leading %).
754       std::string Str(Begin, NameEnd + 1 - Begin);
755 
756       // (BeginLoc, EndLoc) represents the range of the operand we are currently
757       // processing. Unlike Str, the range includes the leading '%'.
758       SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
759           Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
760           &LastAsmStringOffset);
761       SourceLocation EndLoc = getAsmString()->getLocationOfByte(
762           NameEnd + 1 - StrStart, SM, LO, TI, &LastAsmStringToken,
763           &LastAsmStringOffset);
764 
765       Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
766 
767       CurPtr = NameEnd+1;
768       continue;
769     }
770 
771     DiagOffs = CurPtr-StrStart-1;
772     return diag::err_asm_invalid_escape;
773   }
774 }
775 
776 /// Assemble final IR asm string (GCC-style).
generateAsmString(const ASTContext & C) const777 std::string GCCAsmStmt::generateAsmString(const ASTContext &C) const {
778   // Analyze the asm string to decompose it into its pieces.  We know that Sema
779   // has already done this, so it is guaranteed to be successful.
780   SmallVector<GCCAsmStmt::AsmStringPiece, 4> Pieces;
781   unsigned DiagOffs;
782   AnalyzeAsmString(Pieces, C, DiagOffs);
783 
784   std::string AsmString;
785   for (const auto &Piece : Pieces) {
786     if (Piece.isString())
787       AsmString += Piece.getString();
788     else if (Piece.getModifier() == '\0')
789       AsmString += '$' + llvm::utostr(Piece.getOperandNo());
790     else
791       AsmString += "${" + llvm::utostr(Piece.getOperandNo()) + ':' +
792                    Piece.getModifier() + '}';
793   }
794   return AsmString;
795 }
796 
797 /// Assemble final IR asm string (MS-style).
generateAsmString(const ASTContext & C) const798 std::string MSAsmStmt::generateAsmString(const ASTContext &C) const {
799   // FIXME: This needs to be translated into the IR string representation.
800   SmallVector<StringRef, 8> Pieces;
801   AsmStr.split(Pieces, "\n\t");
802   std::string MSAsmString;
803   for (size_t I = 0, E = Pieces.size(); I < E; ++I) {
804     StringRef Instruction = Pieces[I];
805     // For vex/vex2/vex3/evex masm style prefix, convert it to att style
806     // since we don't support masm style prefix in backend.
807     if (Instruction.startswith("vex "))
808       MSAsmString += '{' + Instruction.substr(0, 3).str() + '}' +
809                      Instruction.substr(3).str();
810     else if (Instruction.startswith("vex2 ") ||
811              Instruction.startswith("vex3 ") || Instruction.startswith("evex "))
812       MSAsmString += '{' + Instruction.substr(0, 4).str() + '}' +
813                      Instruction.substr(4).str();
814     else
815       MSAsmString += Instruction.str();
816     // If this is not the last instruction, adding back the '\n\t'.
817     if (I < E - 1)
818       MSAsmString += "\n\t";
819   }
820   return MSAsmString;
821 }
822 
getOutputExpr(unsigned i)823 Expr *MSAsmStmt::getOutputExpr(unsigned i) {
824   return cast<Expr>(Exprs[i]);
825 }
826 
getInputExpr(unsigned i)827 Expr *MSAsmStmt::getInputExpr(unsigned i) {
828   return cast<Expr>(Exprs[i + NumOutputs]);
829 }
830 
setInputExpr(unsigned i,Expr * E)831 void MSAsmStmt::setInputExpr(unsigned i, Expr *E) {
832   Exprs[i + NumOutputs] = E;
833 }
834 
835 //===----------------------------------------------------------------------===//
836 // Constructors
837 //===----------------------------------------------------------------------===//
838 
GCCAsmStmt(const ASTContext & C,SourceLocation asmloc,bool issimple,bool isvolatile,unsigned numoutputs,unsigned numinputs,IdentifierInfo ** names,StringLiteral ** constraints,Expr ** exprs,StringLiteral * asmstr,unsigned numclobbers,StringLiteral ** clobbers,unsigned numlabels,SourceLocation rparenloc)839 GCCAsmStmt::GCCAsmStmt(const ASTContext &C, SourceLocation asmloc,
840                        bool issimple, bool isvolatile, unsigned numoutputs,
841                        unsigned numinputs, IdentifierInfo **names,
842                        StringLiteral **constraints, Expr **exprs,
843                        StringLiteral *asmstr, unsigned numclobbers,
844                        StringLiteral **clobbers, unsigned numlabels,
845                        SourceLocation rparenloc)
846     : AsmStmt(GCCAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
847               numinputs, numclobbers),
848               RParenLoc(rparenloc), AsmStr(asmstr), NumLabels(numlabels) {
849   unsigned NumExprs = NumOutputs + NumInputs + NumLabels;
850 
851   Names = new (C) IdentifierInfo*[NumExprs];
852   std::copy(names, names + NumExprs, Names);
853 
854   Exprs = new (C) Stmt*[NumExprs];
855   std::copy(exprs, exprs + NumExprs, Exprs);
856 
857   unsigned NumConstraints = NumOutputs + NumInputs;
858   Constraints = new (C) StringLiteral*[NumConstraints];
859   std::copy(constraints, constraints + NumConstraints, Constraints);
860 
861   Clobbers = new (C) StringLiteral*[NumClobbers];
862   std::copy(clobbers, clobbers + NumClobbers, Clobbers);
863 }
864 
MSAsmStmt(const ASTContext & C,SourceLocation asmloc,SourceLocation lbraceloc,bool issimple,bool isvolatile,ArrayRef<Token> asmtoks,unsigned numoutputs,unsigned numinputs,ArrayRef<StringRef> constraints,ArrayRef<Expr * > exprs,StringRef asmstr,ArrayRef<StringRef> clobbers,SourceLocation endloc)865 MSAsmStmt::MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
866                      SourceLocation lbraceloc, bool issimple, bool isvolatile,
867                      ArrayRef<Token> asmtoks, unsigned numoutputs,
868                      unsigned numinputs,
869                      ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs,
870                      StringRef asmstr, ArrayRef<StringRef> clobbers,
871                      SourceLocation endloc)
872     : AsmStmt(MSAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
873               numinputs, clobbers.size()), LBraceLoc(lbraceloc),
874               EndLoc(endloc), NumAsmToks(asmtoks.size()) {
875   initialize(C, asmstr, asmtoks, constraints, exprs, clobbers);
876 }
877 
copyIntoContext(const ASTContext & C,StringRef str)878 static StringRef copyIntoContext(const ASTContext &C, StringRef str) {
879   return str.copy(C);
880 }
881 
initialize(const ASTContext & C,StringRef asmstr,ArrayRef<Token> asmtoks,ArrayRef<StringRef> constraints,ArrayRef<Expr * > exprs,ArrayRef<StringRef> clobbers)882 void MSAsmStmt::initialize(const ASTContext &C, StringRef asmstr,
883                            ArrayRef<Token> asmtoks,
884                            ArrayRef<StringRef> constraints,
885                            ArrayRef<Expr*> exprs,
886                            ArrayRef<StringRef> clobbers) {
887   assert(NumAsmToks == asmtoks.size());
888   assert(NumClobbers == clobbers.size());
889 
890   assert(exprs.size() == NumOutputs + NumInputs);
891   assert(exprs.size() == constraints.size());
892 
893   AsmStr = copyIntoContext(C, asmstr);
894 
895   Exprs = new (C) Stmt*[exprs.size()];
896   std::copy(exprs.begin(), exprs.end(), Exprs);
897 
898   AsmToks = new (C) Token[asmtoks.size()];
899   std::copy(asmtoks.begin(), asmtoks.end(), AsmToks);
900 
901   Constraints = new (C) StringRef[exprs.size()];
902   std::transform(constraints.begin(), constraints.end(), Constraints,
903                  [&](StringRef Constraint) {
904                    return copyIntoContext(C, Constraint);
905                  });
906 
907   Clobbers = new (C) StringRef[NumClobbers];
908   // FIXME: Avoid the allocation/copy if at all possible.
909   std::transform(clobbers.begin(), clobbers.end(), Clobbers,
910                  [&](StringRef Clobber) {
911                    return copyIntoContext(C, Clobber);
912                  });
913 }
914 
IfStmt(const ASTContext & Ctx,SourceLocation IL,bool IsConstexpr,Stmt * Init,VarDecl * Var,Expr * Cond,SourceLocation LPL,SourceLocation RPL,Stmt * Then,SourceLocation EL,Stmt * Else)915 IfStmt::IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr,
916                Stmt *Init, VarDecl *Var, Expr *Cond, SourceLocation LPL,
917                SourceLocation RPL, Stmt *Then, SourceLocation EL, Stmt *Else)
918     : Stmt(IfStmtClass), LParenLoc(LPL), RParenLoc(RPL) {
919   bool HasElse = Else != nullptr;
920   bool HasVar = Var != nullptr;
921   bool HasInit = Init != nullptr;
922   IfStmtBits.HasElse = HasElse;
923   IfStmtBits.HasVar = HasVar;
924   IfStmtBits.HasInit = HasInit;
925 
926   setConstexpr(IsConstexpr);
927 
928   setCond(Cond);
929   setThen(Then);
930   if (HasElse)
931     setElse(Else);
932   if (HasVar)
933     setConditionVariable(Ctx, Var);
934   if (HasInit)
935     setInit(Init);
936 
937   setIfLoc(IL);
938   if (HasElse)
939     setElseLoc(EL);
940 }
941 
IfStmt(EmptyShell Empty,bool HasElse,bool HasVar,bool HasInit)942 IfStmt::IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit)
943     : Stmt(IfStmtClass, Empty) {
944   IfStmtBits.HasElse = HasElse;
945   IfStmtBits.HasVar = HasVar;
946   IfStmtBits.HasInit = HasInit;
947 }
948 
Create(const ASTContext & Ctx,SourceLocation IL,bool IsConstexpr,Stmt * Init,VarDecl * Var,Expr * Cond,SourceLocation LPL,SourceLocation RPL,Stmt * Then,SourceLocation EL,Stmt * Else)949 IfStmt *IfStmt::Create(const ASTContext &Ctx, SourceLocation IL,
950                        bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond,
951                        SourceLocation LPL, SourceLocation RPL, Stmt *Then,
952                        SourceLocation EL, Stmt *Else) {
953   bool HasElse = Else != nullptr;
954   bool HasVar = Var != nullptr;
955   bool HasInit = Init != nullptr;
956   void *Mem = Ctx.Allocate(
957       totalSizeToAlloc<Stmt *, SourceLocation>(
958           NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse),
959       alignof(IfStmt));
960   return new (Mem)
961       IfStmt(Ctx, IL, IsConstexpr, Init, Var, Cond, LPL, RPL, Then, EL, Else);
962 }
963 
CreateEmpty(const ASTContext & Ctx,bool HasElse,bool HasVar,bool HasInit)964 IfStmt *IfStmt::CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar,
965                             bool HasInit) {
966   void *Mem = Ctx.Allocate(
967       totalSizeToAlloc<Stmt *, SourceLocation>(
968           NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse),
969       alignof(IfStmt));
970   return new (Mem) IfStmt(EmptyShell(), HasElse, HasVar, HasInit);
971 }
972 
getConditionVariable()973 VarDecl *IfStmt::getConditionVariable() {
974   auto *DS = getConditionVariableDeclStmt();
975   if (!DS)
976     return nullptr;
977   return cast<VarDecl>(DS->getSingleDecl());
978 }
979 
setConditionVariable(const ASTContext & Ctx,VarDecl * V)980 void IfStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
981   assert(hasVarStorage() &&
982          "This if statement has no storage for a condition variable!");
983 
984   if (!V) {
985     getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
986     return;
987   }
988 
989   SourceRange VarRange = V->getSourceRange();
990   getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
991       DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
992 }
993 
isObjCAvailabilityCheck() const994 bool IfStmt::isObjCAvailabilityCheck() const {
995   return isa<ObjCAvailabilityCheckExpr>(getCond());
996 }
997 
getNondiscardedCase(const ASTContext & Ctx)998 Optional<Stmt *> IfStmt::getNondiscardedCase(const ASTContext &Ctx) {
999   if (!isConstexpr() || getCond()->isValueDependent())
1000     return None;
1001   return !getCond()->EvaluateKnownConstInt(Ctx) ? getElse() : getThen();
1002 }
1003 
1004 Optional<const Stmt *>
getNondiscardedCase(const ASTContext & Ctx) const1005 IfStmt::getNondiscardedCase(const ASTContext &Ctx) const {
1006   if (Optional<Stmt *> Result =
1007           const_cast<IfStmt *>(this)->getNondiscardedCase(Ctx))
1008     return *Result;
1009   return None;
1010 }
1011 
ForStmt(const ASTContext & C,Stmt * Init,Expr * Cond,VarDecl * condVar,Expr * Inc,Stmt * Body,SourceLocation FL,SourceLocation LP,SourceLocation RP)1012 ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
1013                  Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
1014                  SourceLocation RP)
1015   : Stmt(ForStmtClass), LParenLoc(LP), RParenLoc(RP)
1016 {
1017   SubExprs[INIT] = Init;
1018   setConditionVariable(C, condVar);
1019   SubExprs[COND] = Cond;
1020   SubExprs[INC] = Inc;
1021   SubExprs[BODY] = Body;
1022   ForStmtBits.ForLoc = FL;
1023 }
1024 
getConditionVariable() const1025 VarDecl *ForStmt::getConditionVariable() const {
1026   if (!SubExprs[CONDVAR])
1027     return nullptr;
1028 
1029   auto *DS = cast<DeclStmt>(SubExprs[CONDVAR]);
1030   return cast<VarDecl>(DS->getSingleDecl());
1031 }
1032 
setConditionVariable(const ASTContext & C,VarDecl * V)1033 void ForStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
1034   if (!V) {
1035     SubExprs[CONDVAR] = nullptr;
1036     return;
1037   }
1038 
1039   SourceRange VarRange = V->getSourceRange();
1040   SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
1041                                        VarRange.getEnd());
1042 }
1043 
SwitchStmt(const ASTContext & Ctx,Stmt * Init,VarDecl * Var,Expr * Cond,SourceLocation LParenLoc,SourceLocation RParenLoc)1044 SwitchStmt::SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
1045                        Expr *Cond, SourceLocation LParenLoc,
1046                        SourceLocation RParenLoc)
1047     : Stmt(SwitchStmtClass), FirstCase(nullptr), LParenLoc(LParenLoc),
1048       RParenLoc(RParenLoc) {
1049   bool HasInit = Init != nullptr;
1050   bool HasVar = Var != nullptr;
1051   SwitchStmtBits.HasInit = HasInit;
1052   SwitchStmtBits.HasVar = HasVar;
1053   SwitchStmtBits.AllEnumCasesCovered = false;
1054 
1055   setCond(Cond);
1056   setBody(nullptr);
1057   if (HasInit)
1058     setInit(Init);
1059   if (HasVar)
1060     setConditionVariable(Ctx, Var);
1061 
1062   setSwitchLoc(SourceLocation{});
1063 }
1064 
SwitchStmt(EmptyShell Empty,bool HasInit,bool HasVar)1065 SwitchStmt::SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar)
1066     : Stmt(SwitchStmtClass, Empty) {
1067   SwitchStmtBits.HasInit = HasInit;
1068   SwitchStmtBits.HasVar = HasVar;
1069   SwitchStmtBits.AllEnumCasesCovered = false;
1070 }
1071 
Create(const ASTContext & Ctx,Stmt * Init,VarDecl * Var,Expr * Cond,SourceLocation LParenLoc,SourceLocation RParenLoc)1072 SwitchStmt *SwitchStmt::Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
1073                                Expr *Cond, SourceLocation LParenLoc,
1074                                SourceLocation RParenLoc) {
1075   bool HasInit = Init != nullptr;
1076   bool HasVar = Var != nullptr;
1077   void *Mem = Ctx.Allocate(
1078       totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar),
1079       alignof(SwitchStmt));
1080   return new (Mem) SwitchStmt(Ctx, Init, Var, Cond, LParenLoc, RParenLoc);
1081 }
1082 
CreateEmpty(const ASTContext & Ctx,bool HasInit,bool HasVar)1083 SwitchStmt *SwitchStmt::CreateEmpty(const ASTContext &Ctx, bool HasInit,
1084                                     bool HasVar) {
1085   void *Mem = Ctx.Allocate(
1086       totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar),
1087       alignof(SwitchStmt));
1088   return new (Mem) SwitchStmt(EmptyShell(), HasInit, HasVar);
1089 }
1090 
getConditionVariable()1091 VarDecl *SwitchStmt::getConditionVariable() {
1092   auto *DS = getConditionVariableDeclStmt();
1093   if (!DS)
1094     return nullptr;
1095   return cast<VarDecl>(DS->getSingleDecl());
1096 }
1097 
setConditionVariable(const ASTContext & Ctx,VarDecl * V)1098 void SwitchStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
1099   assert(hasVarStorage() &&
1100          "This switch statement has no storage for a condition variable!");
1101 
1102   if (!V) {
1103     getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
1104     return;
1105   }
1106 
1107   SourceRange VarRange = V->getSourceRange();
1108   getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
1109       DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
1110 }
1111 
WhileStmt(const ASTContext & Ctx,VarDecl * Var,Expr * Cond,Stmt * Body,SourceLocation WL,SourceLocation LParenLoc,SourceLocation RParenLoc)1112 WhileStmt::WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
1113                      Stmt *Body, SourceLocation WL, SourceLocation LParenLoc,
1114                      SourceLocation RParenLoc)
1115     : Stmt(WhileStmtClass) {
1116   bool HasVar = Var != nullptr;
1117   WhileStmtBits.HasVar = HasVar;
1118 
1119   setCond(Cond);
1120   setBody(Body);
1121   if (HasVar)
1122     setConditionVariable(Ctx, Var);
1123 
1124   setWhileLoc(WL);
1125   setLParenLoc(LParenLoc);
1126   setRParenLoc(RParenLoc);
1127 }
1128 
WhileStmt(EmptyShell Empty,bool HasVar)1129 WhileStmt::WhileStmt(EmptyShell Empty, bool HasVar)
1130     : Stmt(WhileStmtClass, Empty) {
1131   WhileStmtBits.HasVar = HasVar;
1132 }
1133 
Create(const ASTContext & Ctx,VarDecl * Var,Expr * Cond,Stmt * Body,SourceLocation WL,SourceLocation LParenLoc,SourceLocation RParenLoc)1134 WhileStmt *WhileStmt::Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
1135                              Stmt *Body, SourceLocation WL,
1136                              SourceLocation LParenLoc,
1137                              SourceLocation RParenLoc) {
1138   bool HasVar = Var != nullptr;
1139   void *Mem =
1140       Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar),
1141                    alignof(WhileStmt));
1142   return new (Mem) WhileStmt(Ctx, Var, Cond, Body, WL, LParenLoc, RParenLoc);
1143 }
1144 
CreateEmpty(const ASTContext & Ctx,bool HasVar)1145 WhileStmt *WhileStmt::CreateEmpty(const ASTContext &Ctx, bool HasVar) {
1146   void *Mem =
1147       Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar),
1148                    alignof(WhileStmt));
1149   return new (Mem) WhileStmt(EmptyShell(), HasVar);
1150 }
1151 
getConditionVariable()1152 VarDecl *WhileStmt::getConditionVariable() {
1153   auto *DS = getConditionVariableDeclStmt();
1154   if (!DS)
1155     return nullptr;
1156   return cast<VarDecl>(DS->getSingleDecl());
1157 }
1158 
setConditionVariable(const ASTContext & Ctx,VarDecl * V)1159 void WhileStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
1160   assert(hasVarStorage() &&
1161          "This while statement has no storage for a condition variable!");
1162 
1163   if (!V) {
1164     getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
1165     return;
1166   }
1167 
1168   SourceRange VarRange = V->getSourceRange();
1169   getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
1170       DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
1171 }
1172 
1173 // IndirectGotoStmt
getConstantTarget()1174 LabelDecl *IndirectGotoStmt::getConstantTarget() {
1175   if (auto *E = dyn_cast<AddrLabelExpr>(getTarget()->IgnoreParenImpCasts()))
1176     return E->getLabel();
1177   return nullptr;
1178 }
1179 
1180 // ReturnStmt
ReturnStmt(SourceLocation RL,Expr * E,const VarDecl * NRVOCandidate)1181 ReturnStmt::ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
1182     : Stmt(ReturnStmtClass), RetExpr(E) {
1183   bool HasNRVOCandidate = NRVOCandidate != nullptr;
1184   ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
1185   if (HasNRVOCandidate)
1186     setNRVOCandidate(NRVOCandidate);
1187   setReturnLoc(RL);
1188 }
1189 
ReturnStmt(EmptyShell Empty,bool HasNRVOCandidate)1190 ReturnStmt::ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate)
1191     : Stmt(ReturnStmtClass, Empty) {
1192   ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
1193 }
1194 
Create(const ASTContext & Ctx,SourceLocation RL,Expr * E,const VarDecl * NRVOCandidate)1195 ReturnStmt *ReturnStmt::Create(const ASTContext &Ctx, SourceLocation RL,
1196                                Expr *E, const VarDecl *NRVOCandidate) {
1197   bool HasNRVOCandidate = NRVOCandidate != nullptr;
1198   void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate),
1199                            alignof(ReturnStmt));
1200   return new (Mem) ReturnStmt(RL, E, NRVOCandidate);
1201 }
1202 
CreateEmpty(const ASTContext & Ctx,bool HasNRVOCandidate)1203 ReturnStmt *ReturnStmt::CreateEmpty(const ASTContext &Ctx,
1204                                     bool HasNRVOCandidate) {
1205   void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate),
1206                            alignof(ReturnStmt));
1207   return new (Mem) ReturnStmt(EmptyShell(), HasNRVOCandidate);
1208 }
1209 
1210 // CaseStmt
Create(const ASTContext & Ctx,Expr * lhs,Expr * rhs,SourceLocation caseLoc,SourceLocation ellipsisLoc,SourceLocation colonLoc)1211 CaseStmt *CaseStmt::Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
1212                            SourceLocation caseLoc, SourceLocation ellipsisLoc,
1213                            SourceLocation colonLoc) {
1214   bool CaseStmtIsGNURange = rhs != nullptr;
1215   void *Mem = Ctx.Allocate(
1216       totalSizeToAlloc<Stmt *, SourceLocation>(
1217           NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange),
1218       alignof(CaseStmt));
1219   return new (Mem) CaseStmt(lhs, rhs, caseLoc, ellipsisLoc, colonLoc);
1220 }
1221 
CreateEmpty(const ASTContext & Ctx,bool CaseStmtIsGNURange)1222 CaseStmt *CaseStmt::CreateEmpty(const ASTContext &Ctx,
1223                                 bool CaseStmtIsGNURange) {
1224   void *Mem = Ctx.Allocate(
1225       totalSizeToAlloc<Stmt *, SourceLocation>(
1226           NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange),
1227       alignof(CaseStmt));
1228   return new (Mem) CaseStmt(EmptyShell(), CaseStmtIsGNURange);
1229 }
1230 
SEHTryStmt(bool IsCXXTry,SourceLocation TryLoc,Stmt * TryBlock,Stmt * Handler)1231 SEHTryStmt::SEHTryStmt(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock,
1232                        Stmt *Handler)
1233     : Stmt(SEHTryStmtClass), IsCXXTry(IsCXXTry), TryLoc(TryLoc) {
1234   Children[TRY]     = TryBlock;
1235   Children[HANDLER] = Handler;
1236 }
1237 
Create(const ASTContext & C,bool IsCXXTry,SourceLocation TryLoc,Stmt * TryBlock,Stmt * Handler)1238 SEHTryStmt* SEHTryStmt::Create(const ASTContext &C, bool IsCXXTry,
1239                                SourceLocation TryLoc, Stmt *TryBlock,
1240                                Stmt *Handler) {
1241   return new(C) SEHTryStmt(IsCXXTry,TryLoc,TryBlock,Handler);
1242 }
1243 
getExceptHandler() const1244 SEHExceptStmt* SEHTryStmt::getExceptHandler() const {
1245   return dyn_cast<SEHExceptStmt>(getHandler());
1246 }
1247 
getFinallyHandler() const1248 SEHFinallyStmt* SEHTryStmt::getFinallyHandler() const {
1249   return dyn_cast<SEHFinallyStmt>(getHandler());
1250 }
1251 
SEHExceptStmt(SourceLocation Loc,Expr * FilterExpr,Stmt * Block)1252 SEHExceptStmt::SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
1253     : Stmt(SEHExceptStmtClass), Loc(Loc) {
1254   Children[FILTER_EXPR] = FilterExpr;
1255   Children[BLOCK]       = Block;
1256 }
1257 
Create(const ASTContext & C,SourceLocation Loc,Expr * FilterExpr,Stmt * Block)1258 SEHExceptStmt* SEHExceptStmt::Create(const ASTContext &C, SourceLocation Loc,
1259                                      Expr *FilterExpr, Stmt *Block) {
1260   return new(C) SEHExceptStmt(Loc,FilterExpr,Block);
1261 }
1262 
SEHFinallyStmt(SourceLocation Loc,Stmt * Block)1263 SEHFinallyStmt::SEHFinallyStmt(SourceLocation Loc, Stmt *Block)
1264     : Stmt(SEHFinallyStmtClass), Loc(Loc), Block(Block) {}
1265 
Create(const ASTContext & C,SourceLocation Loc,Stmt * Block)1266 SEHFinallyStmt* SEHFinallyStmt::Create(const ASTContext &C, SourceLocation Loc,
1267                                        Stmt *Block) {
1268   return new(C)SEHFinallyStmt(Loc,Block);
1269 }
1270 
Capture(SourceLocation Loc,VariableCaptureKind Kind,VarDecl * Var)1271 CapturedStmt::Capture::Capture(SourceLocation Loc, VariableCaptureKind Kind,
1272                                VarDecl *Var)
1273     : VarAndKind(Var, Kind), Loc(Loc) {
1274   switch (Kind) {
1275   case VCK_This:
1276     assert(!Var && "'this' capture cannot have a variable!");
1277     break;
1278   case VCK_ByRef:
1279     assert(Var && "capturing by reference must have a variable!");
1280     break;
1281   case VCK_ByCopy:
1282     assert(Var && "capturing by copy must have a variable!");
1283     break;
1284   case VCK_VLAType:
1285     assert(!Var &&
1286            "Variable-length array type capture cannot have a variable!");
1287     break;
1288   }
1289 }
1290 
1291 CapturedStmt::VariableCaptureKind
getCaptureKind() const1292 CapturedStmt::Capture::getCaptureKind() const {
1293   return VarAndKind.getInt();
1294 }
1295 
getCapturedVar() const1296 VarDecl *CapturedStmt::Capture::getCapturedVar() const {
1297   assert((capturesVariable() || capturesVariableByCopy()) &&
1298          "No variable available for 'this' or VAT capture");
1299   return VarAndKind.getPointer();
1300 }
1301 
getStoredCaptures() const1302 CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const {
1303   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1304 
1305   // Offset of the first Capture object.
1306   unsigned FirstCaptureOffset = llvm::alignTo(Size, alignof(Capture));
1307 
1308   return reinterpret_cast<Capture *>(
1309       reinterpret_cast<char *>(const_cast<CapturedStmt *>(this))
1310       + FirstCaptureOffset);
1311 }
1312 
CapturedStmt(Stmt * S,CapturedRegionKind Kind,ArrayRef<Capture> Captures,ArrayRef<Expr * > CaptureInits,CapturedDecl * CD,RecordDecl * RD)1313 CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind,
1314                            ArrayRef<Capture> Captures,
1315                            ArrayRef<Expr *> CaptureInits,
1316                            CapturedDecl *CD,
1317                            RecordDecl *RD)
1318   : Stmt(CapturedStmtClass), NumCaptures(Captures.size()),
1319     CapDeclAndKind(CD, Kind), TheRecordDecl(RD) {
1320   assert( S && "null captured statement");
1321   assert(CD && "null captured declaration for captured statement");
1322   assert(RD && "null record declaration for captured statement");
1323 
1324   // Copy initialization expressions.
1325   Stmt **Stored = getStoredStmts();
1326   for (unsigned I = 0, N = NumCaptures; I != N; ++I)
1327     *Stored++ = CaptureInits[I];
1328 
1329   // Copy the statement being captured.
1330   *Stored = S;
1331 
1332   // Copy all Capture objects.
1333   Capture *Buffer = getStoredCaptures();
1334   std::copy(Captures.begin(), Captures.end(), Buffer);
1335 }
1336 
CapturedStmt(EmptyShell Empty,unsigned NumCaptures)1337 CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures)
1338   : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures),
1339     CapDeclAndKind(nullptr, CR_Default) {
1340   getStoredStmts()[NumCaptures] = nullptr;
1341 }
1342 
Create(const ASTContext & Context,Stmt * S,CapturedRegionKind Kind,ArrayRef<Capture> Captures,ArrayRef<Expr * > CaptureInits,CapturedDecl * CD,RecordDecl * RD)1343 CapturedStmt *CapturedStmt::Create(const ASTContext &Context, Stmt *S,
1344                                    CapturedRegionKind Kind,
1345                                    ArrayRef<Capture> Captures,
1346                                    ArrayRef<Expr *> CaptureInits,
1347                                    CapturedDecl *CD,
1348                                    RecordDecl *RD) {
1349   // The layout is
1350   //
1351   // -----------------------------------------------------------
1352   // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture |
1353   // ----------------^-------------------^----------------------
1354   //                 getStoredStmts()    getStoredCaptures()
1355   //
1356   // where S is the statement being captured.
1357   //
1358   assert(CaptureInits.size() == Captures.size() && "wrong number of arguments");
1359 
1360   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1);
1361   if (!Captures.empty()) {
1362     // Realign for the following Capture array.
1363     Size = llvm::alignTo(Size, alignof(Capture));
1364     Size += sizeof(Capture) * Captures.size();
1365   }
1366 
1367   void *Mem = Context.Allocate(Size);
1368   return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD);
1369 }
1370 
CreateDeserialized(const ASTContext & Context,unsigned NumCaptures)1371 CapturedStmt *CapturedStmt::CreateDeserialized(const ASTContext &Context,
1372                                                unsigned NumCaptures) {
1373   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1374   if (NumCaptures > 0) {
1375     // Realign for the following Capture array.
1376     Size = llvm::alignTo(Size, alignof(Capture));
1377     Size += sizeof(Capture) * NumCaptures;
1378   }
1379 
1380   void *Mem = Context.Allocate(Size);
1381   return new (Mem) CapturedStmt(EmptyShell(), NumCaptures);
1382 }
1383 
children()1384 Stmt::child_range CapturedStmt::children() {
1385   // Children are captured field initializers.
1386   return child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
1387 }
1388 
children() const1389 Stmt::const_child_range CapturedStmt::children() const {
1390   return const_child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
1391 }
1392 
getCapturedDecl()1393 CapturedDecl *CapturedStmt::getCapturedDecl() {
1394   return CapDeclAndKind.getPointer();
1395 }
1396 
getCapturedDecl() const1397 const CapturedDecl *CapturedStmt::getCapturedDecl() const {
1398   return CapDeclAndKind.getPointer();
1399 }
1400 
1401 /// Set the outlined function declaration.
setCapturedDecl(CapturedDecl * D)1402 void CapturedStmt::setCapturedDecl(CapturedDecl *D) {
1403   assert(D && "null CapturedDecl");
1404   CapDeclAndKind.setPointer(D);
1405 }
1406 
1407 /// Retrieve the captured region kind.
getCapturedRegionKind() const1408 CapturedRegionKind CapturedStmt::getCapturedRegionKind() const {
1409   return CapDeclAndKind.getInt();
1410 }
1411 
1412 /// Set the captured region kind.
setCapturedRegionKind(CapturedRegionKind Kind)1413 void CapturedStmt::setCapturedRegionKind(CapturedRegionKind Kind) {
1414   CapDeclAndKind.setInt(Kind);
1415 }
1416 
capturesVariable(const VarDecl * Var) const1417 bool CapturedStmt::capturesVariable(const VarDecl *Var) const {
1418   for (const auto &I : captures()) {
1419     if (!I.capturesVariable() && !I.capturesVariableByCopy())
1420       continue;
1421     if (I.getCapturedVar()->getCanonicalDecl() == Var->getCanonicalDecl())
1422       return true;
1423   }
1424 
1425   return false;
1426 }
1427