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