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     // Escaped "%" character in asm string.
650     if (CurPtr == StrEnd) {
651       // % at end of string is invalid (no escape).
652       DiagOffs = CurPtr-StrStart-1;
653       return diag::err_asm_invalid_escape;
654     }
655     // Handle escaped char and continue looping over the asm string.
656     char EscapedChar = *CurPtr++;
657     switch (EscapedChar) {
658     default:
659       break;
660     case '%': // %% -> %
661     case '{': // %{ -> {
662     case '}': // %} -> }
663       CurStringPiece += EscapedChar;
664       continue;
665     case '=': // %= -> Generate a unique ID.
666       CurStringPiece += "${:uid}";
667       continue;
668     }
669 
670     // Otherwise, we have an operand.  If we have accumulated a string so far,
671     // add it to the Pieces list.
672     if (!CurStringPiece.empty()) {
673       Pieces.push_back(AsmStringPiece(CurStringPiece));
674       CurStringPiece.clear();
675     }
676 
677     // Handle operands that have asmSymbolicName (e.g., %x[foo]) and those that
678     // don't (e.g., %x4). 'x' following the '%' is the constraint modifier.
679 
680     const char *Begin = CurPtr - 1; // Points to the character following '%'.
681     const char *Percent = Begin - 1; // Points to '%'.
682 
683     if (isLetter(EscapedChar)) {
684       if (CurPtr == StrEnd) { // Premature end.
685         DiagOffs = CurPtr-StrStart-1;
686         return diag::err_asm_invalid_escape;
687       }
688       EscapedChar = *CurPtr++;
689     }
690 
691     const TargetInfo &TI = C.getTargetInfo();
692     const SourceManager &SM = C.getSourceManager();
693     const LangOptions &LO = C.getLangOpts();
694 
695     // Handle operands that don't have asmSymbolicName (e.g., %x4).
696     if (isDigit(EscapedChar)) {
697       // %n - Assembler operand n
698       unsigned N = 0;
699 
700       --CurPtr;
701       while (CurPtr != StrEnd && isDigit(*CurPtr))
702         N = N*10 + ((*CurPtr++)-'0');
703 
704       unsigned NumOperands = getNumOutputs() + getNumPlusOperands() +
705                              getNumInputs() + getNumLabels();
706       if (N >= NumOperands) {
707         DiagOffs = CurPtr-StrStart-1;
708         return diag::err_asm_invalid_operand_number;
709       }
710 
711       // Str contains "x4" (Operand without the leading %).
712       std::string Str(Begin, CurPtr - Begin);
713 
714       // (BeginLoc, EndLoc) represents the range of the operand we are currently
715       // processing. Unlike Str, the range includes the leading '%'.
716       SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
717           Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
718           &LastAsmStringOffset);
719       SourceLocation EndLoc = getAsmString()->getLocationOfByte(
720           CurPtr - StrStart, SM, LO, TI, &LastAsmStringToken,
721           &LastAsmStringOffset);
722 
723       Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
724       continue;
725     }
726 
727     // Handle operands that have asmSymbolicName (e.g., %x[foo]).
728     if (EscapedChar == '[') {
729       DiagOffs = CurPtr-StrStart-1;
730 
731       // Find the ']'.
732       const char *NameEnd = (const char*)memchr(CurPtr, ']', StrEnd-CurPtr);
733       if (NameEnd == nullptr)
734         return diag::err_asm_unterminated_symbolic_operand_name;
735       if (NameEnd == CurPtr)
736         return diag::err_asm_empty_symbolic_operand_name;
737 
738       StringRef SymbolicName(CurPtr, NameEnd - CurPtr);
739 
740       int N = getNamedOperand(SymbolicName);
741       if (N == -1) {
742         // Verify that an operand with that name exists.
743         DiagOffs = CurPtr-StrStart;
744         return diag::err_asm_unknown_symbolic_operand_name;
745       }
746 
747       // Str contains "x[foo]" (Operand without the leading %).
748       std::string Str(Begin, NameEnd + 1 - Begin);
749 
750       // (BeginLoc, EndLoc) represents the range of the operand we are currently
751       // processing. Unlike Str, the range includes the leading '%'.
752       SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
753           Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
754           &LastAsmStringOffset);
755       SourceLocation EndLoc = getAsmString()->getLocationOfByte(
756           NameEnd + 1 - StrStart, SM, LO, TI, &LastAsmStringToken,
757           &LastAsmStringOffset);
758 
759       Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
760 
761       CurPtr = NameEnd+1;
762       continue;
763     }
764 
765     DiagOffs = CurPtr-StrStart-1;
766     return diag::err_asm_invalid_escape;
767   }
768 }
769 
770 /// Assemble final IR asm string (GCC-style).
generateAsmString(const ASTContext & C) const771 std::string GCCAsmStmt::generateAsmString(const ASTContext &C) const {
772   // Analyze the asm string to decompose it into its pieces.  We know that Sema
773   // has already done this, so it is guaranteed to be successful.
774   SmallVector<GCCAsmStmt::AsmStringPiece, 4> Pieces;
775   unsigned DiagOffs;
776   AnalyzeAsmString(Pieces, C, DiagOffs);
777 
778   std::string AsmString;
779   for (const auto &Piece : Pieces) {
780     if (Piece.isString())
781       AsmString += Piece.getString();
782     else if (Piece.getModifier() == '\0')
783       AsmString += '$' + llvm::utostr(Piece.getOperandNo());
784     else
785       AsmString += "${" + llvm::utostr(Piece.getOperandNo()) + ':' +
786                    Piece.getModifier() + '}';
787   }
788   return AsmString;
789 }
790 
791 /// Assemble final IR asm string (MS-style).
generateAsmString(const ASTContext & C) const792 std::string MSAsmStmt::generateAsmString(const ASTContext &C) const {
793   // FIXME: This needs to be translated into the IR string representation.
794   return std::string(AsmStr);
795 }
796 
getOutputExpr(unsigned i)797 Expr *MSAsmStmt::getOutputExpr(unsigned i) {
798   return cast<Expr>(Exprs[i]);
799 }
800 
getInputExpr(unsigned i)801 Expr *MSAsmStmt::getInputExpr(unsigned i) {
802   return cast<Expr>(Exprs[i + NumOutputs]);
803 }
804 
setInputExpr(unsigned i,Expr * E)805 void MSAsmStmt::setInputExpr(unsigned i, Expr *E) {
806   Exprs[i + NumOutputs] = E;
807 }
808 
809 //===----------------------------------------------------------------------===//
810 // Constructors
811 //===----------------------------------------------------------------------===//
812 
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)813 GCCAsmStmt::GCCAsmStmt(const ASTContext &C, SourceLocation asmloc,
814                        bool issimple, bool isvolatile, unsigned numoutputs,
815                        unsigned numinputs, IdentifierInfo **names,
816                        StringLiteral **constraints, Expr **exprs,
817                        StringLiteral *asmstr, unsigned numclobbers,
818                        StringLiteral **clobbers, unsigned numlabels,
819                        SourceLocation rparenloc)
820     : AsmStmt(GCCAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
821               numinputs, numclobbers),
822               RParenLoc(rparenloc), AsmStr(asmstr), NumLabels(numlabels) {
823   unsigned NumExprs = NumOutputs + NumInputs + NumLabels;
824 
825   Names = new (C) IdentifierInfo*[NumExprs];
826   std::copy(names, names + NumExprs, Names);
827 
828   Exprs = new (C) Stmt*[NumExprs];
829   std::copy(exprs, exprs + NumExprs, Exprs);
830 
831   unsigned NumConstraints = NumOutputs + NumInputs;
832   Constraints = new (C) StringLiteral*[NumConstraints];
833   std::copy(constraints, constraints + NumConstraints, Constraints);
834 
835   Clobbers = new (C) StringLiteral*[NumClobbers];
836   std::copy(clobbers, clobbers + NumClobbers, Clobbers);
837 }
838 
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)839 MSAsmStmt::MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
840                      SourceLocation lbraceloc, bool issimple, bool isvolatile,
841                      ArrayRef<Token> asmtoks, unsigned numoutputs,
842                      unsigned numinputs,
843                      ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs,
844                      StringRef asmstr, ArrayRef<StringRef> clobbers,
845                      SourceLocation endloc)
846     : AsmStmt(MSAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
847               numinputs, clobbers.size()), LBraceLoc(lbraceloc),
848               EndLoc(endloc), NumAsmToks(asmtoks.size()) {
849   initialize(C, asmstr, asmtoks, constraints, exprs, clobbers);
850 }
851 
copyIntoContext(const ASTContext & C,StringRef str)852 static StringRef copyIntoContext(const ASTContext &C, StringRef str) {
853   return str.copy(C);
854 }
855 
initialize(const ASTContext & C,StringRef asmstr,ArrayRef<Token> asmtoks,ArrayRef<StringRef> constraints,ArrayRef<Expr * > exprs,ArrayRef<StringRef> clobbers)856 void MSAsmStmt::initialize(const ASTContext &C, StringRef asmstr,
857                            ArrayRef<Token> asmtoks,
858                            ArrayRef<StringRef> constraints,
859                            ArrayRef<Expr*> exprs,
860                            ArrayRef<StringRef> clobbers) {
861   assert(NumAsmToks == asmtoks.size());
862   assert(NumClobbers == clobbers.size());
863 
864   assert(exprs.size() == NumOutputs + NumInputs);
865   assert(exprs.size() == constraints.size());
866 
867   AsmStr = copyIntoContext(C, asmstr);
868 
869   Exprs = new (C) Stmt*[exprs.size()];
870   std::copy(exprs.begin(), exprs.end(), Exprs);
871 
872   AsmToks = new (C) Token[asmtoks.size()];
873   std::copy(asmtoks.begin(), asmtoks.end(), AsmToks);
874 
875   Constraints = new (C) StringRef[exprs.size()];
876   std::transform(constraints.begin(), constraints.end(), Constraints,
877                  [&](StringRef Constraint) {
878                    return copyIntoContext(C, Constraint);
879                  });
880 
881   Clobbers = new (C) StringRef[NumClobbers];
882   // FIXME: Avoid the allocation/copy if at all possible.
883   std::transform(clobbers.begin(), clobbers.end(), Clobbers,
884                  [&](StringRef Clobber) {
885                    return copyIntoContext(C, Clobber);
886                  });
887 }
888 
IfStmt(const ASTContext & Ctx,SourceLocation IL,bool IsConstexpr,Stmt * Init,VarDecl * Var,Expr * Cond,SourceLocation LPL,SourceLocation RPL,Stmt * Then,SourceLocation EL,Stmt * Else)889 IfStmt::IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr,
890                Stmt *Init, VarDecl *Var, Expr *Cond, SourceLocation LPL,
891                SourceLocation RPL, Stmt *Then, SourceLocation EL, Stmt *Else)
892     : Stmt(IfStmtClass), LParenLoc(LPL), RParenLoc(RPL) {
893   bool HasElse = Else != nullptr;
894   bool HasVar = Var != nullptr;
895   bool HasInit = Init != nullptr;
896   IfStmtBits.HasElse = HasElse;
897   IfStmtBits.HasVar = HasVar;
898   IfStmtBits.HasInit = HasInit;
899 
900   setConstexpr(IsConstexpr);
901 
902   setCond(Cond);
903   setThen(Then);
904   if (HasElse)
905     setElse(Else);
906   if (HasVar)
907     setConditionVariable(Ctx, Var);
908   if (HasInit)
909     setInit(Init);
910 
911   setIfLoc(IL);
912   if (HasElse)
913     setElseLoc(EL);
914 }
915 
IfStmt(EmptyShell Empty,bool HasElse,bool HasVar,bool HasInit)916 IfStmt::IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit)
917     : Stmt(IfStmtClass, Empty) {
918   IfStmtBits.HasElse = HasElse;
919   IfStmtBits.HasVar = HasVar;
920   IfStmtBits.HasInit = HasInit;
921 }
922 
Create(const ASTContext & Ctx,SourceLocation IL,bool IsConstexpr,Stmt * Init,VarDecl * Var,Expr * Cond,SourceLocation LPL,SourceLocation RPL,Stmt * Then,SourceLocation EL,Stmt * Else)923 IfStmt *IfStmt::Create(const ASTContext &Ctx, SourceLocation IL,
924                        bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond,
925                        SourceLocation LPL, SourceLocation RPL, Stmt *Then,
926                        SourceLocation EL, Stmt *Else) {
927   bool HasElse = Else != nullptr;
928   bool HasVar = Var != nullptr;
929   bool HasInit = Init != nullptr;
930   void *Mem = Ctx.Allocate(
931       totalSizeToAlloc<Stmt *, SourceLocation>(
932           NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse),
933       alignof(IfStmt));
934   return new (Mem)
935       IfStmt(Ctx, IL, IsConstexpr, Init, Var, Cond, LPL, RPL, Then, EL, Else);
936 }
937 
CreateEmpty(const ASTContext & Ctx,bool HasElse,bool HasVar,bool HasInit)938 IfStmt *IfStmt::CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar,
939                             bool HasInit) {
940   void *Mem = Ctx.Allocate(
941       totalSizeToAlloc<Stmt *, SourceLocation>(
942           NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse),
943       alignof(IfStmt));
944   return new (Mem) IfStmt(EmptyShell(), HasElse, HasVar, HasInit);
945 }
946 
getConditionVariable()947 VarDecl *IfStmt::getConditionVariable() {
948   auto *DS = getConditionVariableDeclStmt();
949   if (!DS)
950     return nullptr;
951   return cast<VarDecl>(DS->getSingleDecl());
952 }
953 
setConditionVariable(const ASTContext & Ctx,VarDecl * V)954 void IfStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
955   assert(hasVarStorage() &&
956          "This if statement has no storage for a condition variable!");
957 
958   if (!V) {
959     getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
960     return;
961   }
962 
963   SourceRange VarRange = V->getSourceRange();
964   getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
965       DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
966 }
967 
isObjCAvailabilityCheck() const968 bool IfStmt::isObjCAvailabilityCheck() const {
969   return isa<ObjCAvailabilityCheckExpr>(getCond());
970 }
971 
getNondiscardedCase(const ASTContext & Ctx) const972 Optional<const Stmt*> IfStmt::getNondiscardedCase(const ASTContext &Ctx) const {
973   if (!isConstexpr() || getCond()->isValueDependent())
974     return None;
975   return !getCond()->EvaluateKnownConstInt(Ctx) ? getElse() : getThen();
976 }
977 
ForStmt(const ASTContext & C,Stmt * Init,Expr * Cond,VarDecl * condVar,Expr * Inc,Stmt * Body,SourceLocation FL,SourceLocation LP,SourceLocation RP)978 ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
979                  Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
980                  SourceLocation RP)
981   : Stmt(ForStmtClass), LParenLoc(LP), RParenLoc(RP)
982 {
983   SubExprs[INIT] = Init;
984   setConditionVariable(C, condVar);
985   SubExprs[COND] = Cond;
986   SubExprs[INC] = Inc;
987   SubExprs[BODY] = Body;
988   ForStmtBits.ForLoc = FL;
989 }
990 
getConditionVariable() const991 VarDecl *ForStmt::getConditionVariable() const {
992   if (!SubExprs[CONDVAR])
993     return nullptr;
994 
995   auto *DS = cast<DeclStmt>(SubExprs[CONDVAR]);
996   return cast<VarDecl>(DS->getSingleDecl());
997 }
998 
setConditionVariable(const ASTContext & C,VarDecl * V)999 void ForStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
1000   if (!V) {
1001     SubExprs[CONDVAR] = nullptr;
1002     return;
1003   }
1004 
1005   SourceRange VarRange = V->getSourceRange();
1006   SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
1007                                        VarRange.getEnd());
1008 }
1009 
SwitchStmt(const ASTContext & Ctx,Stmt * Init,VarDecl * Var,Expr * Cond,SourceLocation LParenLoc,SourceLocation RParenLoc)1010 SwitchStmt::SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
1011                        Expr *Cond, SourceLocation LParenLoc,
1012                        SourceLocation RParenLoc)
1013     : Stmt(SwitchStmtClass), FirstCase(nullptr), LParenLoc(LParenLoc),
1014       RParenLoc(RParenLoc) {
1015   bool HasInit = Init != nullptr;
1016   bool HasVar = Var != nullptr;
1017   SwitchStmtBits.HasInit = HasInit;
1018   SwitchStmtBits.HasVar = HasVar;
1019   SwitchStmtBits.AllEnumCasesCovered = false;
1020 
1021   setCond(Cond);
1022   setBody(nullptr);
1023   if (HasInit)
1024     setInit(Init);
1025   if (HasVar)
1026     setConditionVariable(Ctx, Var);
1027 
1028   setSwitchLoc(SourceLocation{});
1029 }
1030 
SwitchStmt(EmptyShell Empty,bool HasInit,bool HasVar)1031 SwitchStmt::SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar)
1032     : Stmt(SwitchStmtClass, Empty) {
1033   SwitchStmtBits.HasInit = HasInit;
1034   SwitchStmtBits.HasVar = HasVar;
1035   SwitchStmtBits.AllEnumCasesCovered = false;
1036 }
1037 
Create(const ASTContext & Ctx,Stmt * Init,VarDecl * Var,Expr * Cond,SourceLocation LParenLoc,SourceLocation RParenLoc)1038 SwitchStmt *SwitchStmt::Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
1039                                Expr *Cond, SourceLocation LParenLoc,
1040                                SourceLocation RParenLoc) {
1041   bool HasInit = Init != nullptr;
1042   bool HasVar = Var != nullptr;
1043   void *Mem = Ctx.Allocate(
1044       totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar),
1045       alignof(SwitchStmt));
1046   return new (Mem) SwitchStmt(Ctx, Init, Var, Cond, LParenLoc, RParenLoc);
1047 }
1048 
CreateEmpty(const ASTContext & Ctx,bool HasInit,bool HasVar)1049 SwitchStmt *SwitchStmt::CreateEmpty(const ASTContext &Ctx, bool HasInit,
1050                                     bool HasVar) {
1051   void *Mem = Ctx.Allocate(
1052       totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar),
1053       alignof(SwitchStmt));
1054   return new (Mem) SwitchStmt(EmptyShell(), HasInit, HasVar);
1055 }
1056 
getConditionVariable()1057 VarDecl *SwitchStmt::getConditionVariable() {
1058   auto *DS = getConditionVariableDeclStmt();
1059   if (!DS)
1060     return nullptr;
1061   return cast<VarDecl>(DS->getSingleDecl());
1062 }
1063 
setConditionVariable(const ASTContext & Ctx,VarDecl * V)1064 void SwitchStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
1065   assert(hasVarStorage() &&
1066          "This switch statement has no storage for a condition variable!");
1067 
1068   if (!V) {
1069     getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
1070     return;
1071   }
1072 
1073   SourceRange VarRange = V->getSourceRange();
1074   getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
1075       DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
1076 }
1077 
WhileStmt(const ASTContext & Ctx,VarDecl * Var,Expr * Cond,Stmt * Body,SourceLocation WL,SourceLocation LParenLoc,SourceLocation RParenLoc)1078 WhileStmt::WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
1079                      Stmt *Body, SourceLocation WL, SourceLocation LParenLoc,
1080                      SourceLocation RParenLoc)
1081     : Stmt(WhileStmtClass) {
1082   bool HasVar = Var != nullptr;
1083   WhileStmtBits.HasVar = HasVar;
1084 
1085   setCond(Cond);
1086   setBody(Body);
1087   if (HasVar)
1088     setConditionVariable(Ctx, Var);
1089 
1090   setWhileLoc(WL);
1091   setLParenLoc(LParenLoc);
1092   setRParenLoc(RParenLoc);
1093 }
1094 
WhileStmt(EmptyShell Empty,bool HasVar)1095 WhileStmt::WhileStmt(EmptyShell Empty, bool HasVar)
1096     : Stmt(WhileStmtClass, Empty) {
1097   WhileStmtBits.HasVar = HasVar;
1098 }
1099 
Create(const ASTContext & Ctx,VarDecl * Var,Expr * Cond,Stmt * Body,SourceLocation WL,SourceLocation LParenLoc,SourceLocation RParenLoc)1100 WhileStmt *WhileStmt::Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
1101                              Stmt *Body, SourceLocation WL,
1102                              SourceLocation LParenLoc,
1103                              SourceLocation RParenLoc) {
1104   bool HasVar = Var != nullptr;
1105   void *Mem =
1106       Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar),
1107                    alignof(WhileStmt));
1108   return new (Mem) WhileStmt(Ctx, Var, Cond, Body, WL, LParenLoc, RParenLoc);
1109 }
1110 
CreateEmpty(const ASTContext & Ctx,bool HasVar)1111 WhileStmt *WhileStmt::CreateEmpty(const ASTContext &Ctx, bool HasVar) {
1112   void *Mem =
1113       Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar),
1114                    alignof(WhileStmt));
1115   return new (Mem) WhileStmt(EmptyShell(), HasVar);
1116 }
1117 
getConditionVariable()1118 VarDecl *WhileStmt::getConditionVariable() {
1119   auto *DS = getConditionVariableDeclStmt();
1120   if (!DS)
1121     return nullptr;
1122   return cast<VarDecl>(DS->getSingleDecl());
1123 }
1124 
setConditionVariable(const ASTContext & Ctx,VarDecl * V)1125 void WhileStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
1126   assert(hasVarStorage() &&
1127          "This while statement has no storage for a condition variable!");
1128 
1129   if (!V) {
1130     getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
1131     return;
1132   }
1133 
1134   SourceRange VarRange = V->getSourceRange();
1135   getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
1136       DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
1137 }
1138 
1139 // IndirectGotoStmt
getConstantTarget()1140 LabelDecl *IndirectGotoStmt::getConstantTarget() {
1141   if (auto *E = dyn_cast<AddrLabelExpr>(getTarget()->IgnoreParenImpCasts()))
1142     return E->getLabel();
1143   return nullptr;
1144 }
1145 
1146 // ReturnStmt
ReturnStmt(SourceLocation RL,Expr * E,const VarDecl * NRVOCandidate)1147 ReturnStmt::ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
1148     : Stmt(ReturnStmtClass), RetExpr(E) {
1149   bool HasNRVOCandidate = NRVOCandidate != nullptr;
1150   ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
1151   if (HasNRVOCandidate)
1152     setNRVOCandidate(NRVOCandidate);
1153   setReturnLoc(RL);
1154 }
1155 
ReturnStmt(EmptyShell Empty,bool HasNRVOCandidate)1156 ReturnStmt::ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate)
1157     : Stmt(ReturnStmtClass, Empty) {
1158   ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
1159 }
1160 
Create(const ASTContext & Ctx,SourceLocation RL,Expr * E,const VarDecl * NRVOCandidate)1161 ReturnStmt *ReturnStmt::Create(const ASTContext &Ctx, SourceLocation RL,
1162                                Expr *E, const VarDecl *NRVOCandidate) {
1163   bool HasNRVOCandidate = NRVOCandidate != nullptr;
1164   void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate),
1165                            alignof(ReturnStmt));
1166   return new (Mem) ReturnStmt(RL, E, NRVOCandidate);
1167 }
1168 
CreateEmpty(const ASTContext & Ctx,bool HasNRVOCandidate)1169 ReturnStmt *ReturnStmt::CreateEmpty(const ASTContext &Ctx,
1170                                     bool HasNRVOCandidate) {
1171   void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate),
1172                            alignof(ReturnStmt));
1173   return new (Mem) ReturnStmt(EmptyShell(), HasNRVOCandidate);
1174 }
1175 
1176 // CaseStmt
Create(const ASTContext & Ctx,Expr * lhs,Expr * rhs,SourceLocation caseLoc,SourceLocation ellipsisLoc,SourceLocation colonLoc)1177 CaseStmt *CaseStmt::Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
1178                            SourceLocation caseLoc, SourceLocation ellipsisLoc,
1179                            SourceLocation colonLoc) {
1180   bool CaseStmtIsGNURange = rhs != nullptr;
1181   void *Mem = Ctx.Allocate(
1182       totalSizeToAlloc<Stmt *, SourceLocation>(
1183           NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange),
1184       alignof(CaseStmt));
1185   return new (Mem) CaseStmt(lhs, rhs, caseLoc, ellipsisLoc, colonLoc);
1186 }
1187 
CreateEmpty(const ASTContext & Ctx,bool CaseStmtIsGNURange)1188 CaseStmt *CaseStmt::CreateEmpty(const ASTContext &Ctx,
1189                                 bool CaseStmtIsGNURange) {
1190   void *Mem = Ctx.Allocate(
1191       totalSizeToAlloc<Stmt *, SourceLocation>(
1192           NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange),
1193       alignof(CaseStmt));
1194   return new (Mem) CaseStmt(EmptyShell(), CaseStmtIsGNURange);
1195 }
1196 
SEHTryStmt(bool IsCXXTry,SourceLocation TryLoc,Stmt * TryBlock,Stmt * Handler)1197 SEHTryStmt::SEHTryStmt(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock,
1198                        Stmt *Handler)
1199     : Stmt(SEHTryStmtClass), IsCXXTry(IsCXXTry), TryLoc(TryLoc) {
1200   Children[TRY]     = TryBlock;
1201   Children[HANDLER] = Handler;
1202 }
1203 
Create(const ASTContext & C,bool IsCXXTry,SourceLocation TryLoc,Stmt * TryBlock,Stmt * Handler)1204 SEHTryStmt* SEHTryStmt::Create(const ASTContext &C, bool IsCXXTry,
1205                                SourceLocation TryLoc, Stmt *TryBlock,
1206                                Stmt *Handler) {
1207   return new(C) SEHTryStmt(IsCXXTry,TryLoc,TryBlock,Handler);
1208 }
1209 
getExceptHandler() const1210 SEHExceptStmt* SEHTryStmt::getExceptHandler() const {
1211   return dyn_cast<SEHExceptStmt>(getHandler());
1212 }
1213 
getFinallyHandler() const1214 SEHFinallyStmt* SEHTryStmt::getFinallyHandler() const {
1215   return dyn_cast<SEHFinallyStmt>(getHandler());
1216 }
1217 
SEHExceptStmt(SourceLocation Loc,Expr * FilterExpr,Stmt * Block)1218 SEHExceptStmt::SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
1219     : Stmt(SEHExceptStmtClass), Loc(Loc) {
1220   Children[FILTER_EXPR] = FilterExpr;
1221   Children[BLOCK]       = Block;
1222 }
1223 
Create(const ASTContext & C,SourceLocation Loc,Expr * FilterExpr,Stmt * Block)1224 SEHExceptStmt* SEHExceptStmt::Create(const ASTContext &C, SourceLocation Loc,
1225                                      Expr *FilterExpr, Stmt *Block) {
1226   return new(C) SEHExceptStmt(Loc,FilterExpr,Block);
1227 }
1228 
SEHFinallyStmt(SourceLocation Loc,Stmt * Block)1229 SEHFinallyStmt::SEHFinallyStmt(SourceLocation Loc, Stmt *Block)
1230     : Stmt(SEHFinallyStmtClass), Loc(Loc), Block(Block) {}
1231 
Create(const ASTContext & C,SourceLocation Loc,Stmt * Block)1232 SEHFinallyStmt* SEHFinallyStmt::Create(const ASTContext &C, SourceLocation Loc,
1233                                        Stmt *Block) {
1234   return new(C)SEHFinallyStmt(Loc,Block);
1235 }
1236 
Capture(SourceLocation Loc,VariableCaptureKind Kind,VarDecl * Var)1237 CapturedStmt::Capture::Capture(SourceLocation Loc, VariableCaptureKind Kind,
1238                                VarDecl *Var)
1239     : VarAndKind(Var, Kind), Loc(Loc) {
1240   switch (Kind) {
1241   case VCK_This:
1242     assert(!Var && "'this' capture cannot have a variable!");
1243     break;
1244   case VCK_ByRef:
1245     assert(Var && "capturing by reference must have a variable!");
1246     break;
1247   case VCK_ByCopy:
1248     assert(Var && "capturing by copy must have a variable!");
1249     assert(
1250         (Var->getType()->isScalarType() || (Var->getType()->isReferenceType() &&
1251                                             Var->getType()
1252                                                 ->castAs<ReferenceType>()
1253                                                 ->getPointeeType()
1254                                                 ->isScalarType())) &&
1255         "captures by copy are expected to have a scalar type!");
1256     break;
1257   case VCK_VLAType:
1258     assert(!Var &&
1259            "Variable-length array type capture cannot have a variable!");
1260     break;
1261   }
1262 }
1263 
1264 CapturedStmt::VariableCaptureKind
getCaptureKind() const1265 CapturedStmt::Capture::getCaptureKind() const {
1266   return VarAndKind.getInt();
1267 }
1268 
getCapturedVar() const1269 VarDecl *CapturedStmt::Capture::getCapturedVar() const {
1270   assert((capturesVariable() || capturesVariableByCopy()) &&
1271          "No variable available for 'this' or VAT capture");
1272   return VarAndKind.getPointer();
1273 }
1274 
getStoredCaptures() const1275 CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const {
1276   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1277 
1278   // Offset of the first Capture object.
1279   unsigned FirstCaptureOffset = llvm::alignTo(Size, alignof(Capture));
1280 
1281   return reinterpret_cast<Capture *>(
1282       reinterpret_cast<char *>(const_cast<CapturedStmt *>(this))
1283       + FirstCaptureOffset);
1284 }
1285 
CapturedStmt(Stmt * S,CapturedRegionKind Kind,ArrayRef<Capture> Captures,ArrayRef<Expr * > CaptureInits,CapturedDecl * CD,RecordDecl * RD)1286 CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind,
1287                            ArrayRef<Capture> Captures,
1288                            ArrayRef<Expr *> CaptureInits,
1289                            CapturedDecl *CD,
1290                            RecordDecl *RD)
1291   : Stmt(CapturedStmtClass), NumCaptures(Captures.size()),
1292     CapDeclAndKind(CD, Kind), TheRecordDecl(RD) {
1293   assert( S && "null captured statement");
1294   assert(CD && "null captured declaration for captured statement");
1295   assert(RD && "null record declaration for captured statement");
1296 
1297   // Copy initialization expressions.
1298   Stmt **Stored = getStoredStmts();
1299   for (unsigned I = 0, N = NumCaptures; I != N; ++I)
1300     *Stored++ = CaptureInits[I];
1301 
1302   // Copy the statement being captured.
1303   *Stored = S;
1304 
1305   // Copy all Capture objects.
1306   Capture *Buffer = getStoredCaptures();
1307   std::copy(Captures.begin(), Captures.end(), Buffer);
1308 }
1309 
CapturedStmt(EmptyShell Empty,unsigned NumCaptures)1310 CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures)
1311   : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures),
1312     CapDeclAndKind(nullptr, CR_Default) {
1313   getStoredStmts()[NumCaptures] = nullptr;
1314 }
1315 
Create(const ASTContext & Context,Stmt * S,CapturedRegionKind Kind,ArrayRef<Capture> Captures,ArrayRef<Expr * > CaptureInits,CapturedDecl * CD,RecordDecl * RD)1316 CapturedStmt *CapturedStmt::Create(const ASTContext &Context, Stmt *S,
1317                                    CapturedRegionKind Kind,
1318                                    ArrayRef<Capture> Captures,
1319                                    ArrayRef<Expr *> CaptureInits,
1320                                    CapturedDecl *CD,
1321                                    RecordDecl *RD) {
1322   // The layout is
1323   //
1324   // -----------------------------------------------------------
1325   // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture |
1326   // ----------------^-------------------^----------------------
1327   //                 getStoredStmts()    getStoredCaptures()
1328   //
1329   // where S is the statement being captured.
1330   //
1331   assert(CaptureInits.size() == Captures.size() && "wrong number of arguments");
1332 
1333   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1);
1334   if (!Captures.empty()) {
1335     // Realign for the following Capture array.
1336     Size = llvm::alignTo(Size, alignof(Capture));
1337     Size += sizeof(Capture) * Captures.size();
1338   }
1339 
1340   void *Mem = Context.Allocate(Size);
1341   return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD);
1342 }
1343 
CreateDeserialized(const ASTContext & Context,unsigned NumCaptures)1344 CapturedStmt *CapturedStmt::CreateDeserialized(const ASTContext &Context,
1345                                                unsigned NumCaptures) {
1346   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1347   if (NumCaptures > 0) {
1348     // Realign for the following Capture array.
1349     Size = llvm::alignTo(Size, alignof(Capture));
1350     Size += sizeof(Capture) * NumCaptures;
1351   }
1352 
1353   void *Mem = Context.Allocate(Size);
1354   return new (Mem) CapturedStmt(EmptyShell(), NumCaptures);
1355 }
1356 
children()1357 Stmt::child_range CapturedStmt::children() {
1358   // Children are captured field initializers.
1359   return child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
1360 }
1361 
children() const1362 Stmt::const_child_range CapturedStmt::children() const {
1363   return const_child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
1364 }
1365 
getCapturedDecl()1366 CapturedDecl *CapturedStmt::getCapturedDecl() {
1367   return CapDeclAndKind.getPointer();
1368 }
1369 
getCapturedDecl() const1370 const CapturedDecl *CapturedStmt::getCapturedDecl() const {
1371   return CapDeclAndKind.getPointer();
1372 }
1373 
1374 /// Set the outlined function declaration.
setCapturedDecl(CapturedDecl * D)1375 void CapturedStmt::setCapturedDecl(CapturedDecl *D) {
1376   assert(D && "null CapturedDecl");
1377   CapDeclAndKind.setPointer(D);
1378 }
1379 
1380 /// Retrieve the captured region kind.
getCapturedRegionKind() const1381 CapturedRegionKind CapturedStmt::getCapturedRegionKind() const {
1382   return CapDeclAndKind.getInt();
1383 }
1384 
1385 /// Set the captured region kind.
setCapturedRegionKind(CapturedRegionKind Kind)1386 void CapturedStmt::setCapturedRegionKind(CapturedRegionKind Kind) {
1387   CapDeclAndKind.setInt(Kind);
1388 }
1389 
capturesVariable(const VarDecl * Var) const1390 bool CapturedStmt::capturesVariable(const VarDecl *Var) const {
1391   for (const auto &I : captures()) {
1392     if (!I.capturesVariable() && !I.capturesVariableByCopy())
1393       continue;
1394     if (I.getCapturedVar()->getCanonicalDecl() == Var->getCanonicalDecl())
1395       return true;
1396   }
1397 
1398   return false;
1399 }
1400