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