clang  10.0.0svn
Stmt.cpp
Go to the documentation of this file.
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"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclGroup.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/ExprOpenMP.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/AST/StmtOpenMP.h"
25 #include "clang/AST/Type.h"
26 #include "clang/Basic/CharInfo.h"
27 #include "clang/Basic/LLVM.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Token.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <algorithm>
40 #include <cassert>
41 #include <cstring>
42 #include <string>
43 #include <utility>
44 #include <type_traits>
45 
46 using namespace clang;
47 
48 static struct StmtClassNameTable {
49  const char *Name;
50  unsigned Counter;
51  unsigned Size;
52 } StmtClassInfo[Stmt::lastStmtConstant+1];
53 
55  static bool Initialized = false;
56  if (Initialized)
57  return StmtClassInfo[E];
58 
59  // Initialize the table on the first use.
60  Initialized = true;
61 #define ABSTRACT_STMT(STMT)
62 #define STMT(CLASS, PARENT) \
63  StmtClassInfo[(unsigned)Stmt::CLASS##Class].Name = #CLASS; \
64  StmtClassInfo[(unsigned)Stmt::CLASS##Class].Size = sizeof(CLASS);
65 #include "clang/AST/StmtNodes.inc"
66 
67  return StmtClassInfo[E];
68 }
69 
70 void *Stmt::operator new(size_t bytes, const ASTContext& C,
71  unsigned alignment) {
72  return ::operator new(bytes, C, alignment);
73 }
74 
75 const char *Stmt::getStmtClassName() const {
76  return getStmtInfoTableEntry((StmtClass) StmtBits.sClass).Name;
77 }
78 
79 // Check that no statement / expression class is polymorphic. LLVM style RTTI
80 // should be used instead. If absolutely needed an exception can still be added
81 // here by defining the appropriate macro (but please don't do this).
82 #define STMT(CLASS, PARENT) \
83  static_assert(!std::is_polymorphic<CLASS>::value, \
84  #CLASS " should not be polymorphic!");
85 #include "clang/AST/StmtNodes.inc"
86 
87 // Check that no statement / expression class has a non-trival destructor.
88 // Statements and expressions are allocated with the BumpPtrAllocator from
89 // ASTContext and therefore their destructor is not executed.
90 #define STMT(CLASS, PARENT) \
91  static_assert(std::is_trivially_destructible<CLASS>::value, \
92  #CLASS " should be trivially destructible!");
93 // FIXME: InitListExpr is not trivially destructible due to its ASTVector.
94 #define INITLISTEXPR(CLASS, PARENT)
95 #include "clang/AST/StmtNodes.inc"
96 
98  // Ensure the table is primed.
99  getStmtInfoTableEntry(Stmt::NullStmtClass);
100 
101  unsigned sum = 0;
102  llvm::errs() << "\n*** Stmt/Expr Stats:\n";
103  for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
104  if (StmtClassInfo[i].Name == nullptr) continue;
105  sum += StmtClassInfo[i].Counter;
106  }
107  llvm::errs() << " " << sum << " stmts/exprs total.\n";
108  sum = 0;
109  for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
110  if (StmtClassInfo[i].Name == nullptr) continue;
111  if (StmtClassInfo[i].Counter == 0) continue;
112  llvm::errs() << " " << StmtClassInfo[i].Counter << " "
113  << StmtClassInfo[i].Name << ", " << StmtClassInfo[i].Size
114  << " each (" << StmtClassInfo[i].Counter*StmtClassInfo[i].Size
115  << " bytes)\n";
117  }
118 
119  llvm::errs() << "Total bytes = " << sum << "\n";
120 }
121 
124 }
125 
126 bool Stmt::StatisticsEnabled = false;
128  StatisticsEnabled = true;
129 }
130 
131 /// Skip no-op (attributed, compound) container stmts and skip captured
132 /// stmt at the top, if \a IgnoreCaptured is true.
133 Stmt *Stmt::IgnoreContainers(bool IgnoreCaptured) {
134  Stmt *S = this;
135  if (IgnoreCaptured)
136  if (auto CapS = dyn_cast_or_null<CapturedStmt>(S))
137  S = CapS->getCapturedStmt();
138  while (true) {
139  if (auto AS = dyn_cast_or_null<AttributedStmt>(S))
140  S = AS->getSubStmt();
141  else if (auto CS = dyn_cast_or_null<CompoundStmt>(S)) {
142  if (CS->size() != 1)
143  break;
144  S = CS->body_back();
145  } else
146  break;
147  }
148  return S;
149 }
150 
151 /// Strip off all label-like statements.
152 ///
153 /// This will strip off label statements, case statements, attributed
154 /// statements and default statements recursively.
156  const Stmt *S = this;
157  while (true) {
158  if (const auto *LS = dyn_cast<LabelStmt>(S))
159  S = LS->getSubStmt();
160  else if (const auto *SC = dyn_cast<SwitchCase>(S))
161  S = SC->getSubStmt();
162  else if (const auto *AS = dyn_cast<AttributedStmt>(S))
163  S = AS->getSubStmt();
164  else
165  return S;
166  }
167 }
168 
169 namespace {
170 
171  struct good {};
172  struct bad {};
173 
174  // These silly little functions have to be static inline to suppress
175  // unused warnings, and they have to be defined to suppress other
176  // warnings.
177  static good is_good(good) { return good(); }
178 
179  typedef Stmt::child_range children_t();
180  template <class T> good implements_children(children_t T::*) {
181  return good();
182  }
183  LLVM_ATTRIBUTE_UNUSED
184  static bad implements_children(children_t Stmt::*) {
185  return bad();
186  }
187 
188  typedef SourceLocation getBeginLoc_t() const;
189  template <class T> good implements_getBeginLoc(getBeginLoc_t T::*) {
190  return good();
191  }
192  LLVM_ATTRIBUTE_UNUSED
193  static bad implements_getBeginLoc(getBeginLoc_t Stmt::*) { return bad(); }
194 
195  typedef SourceLocation getLocEnd_t() const;
196  template <class T> good implements_getEndLoc(getLocEnd_t T::*) {
197  return good();
198  }
199  LLVM_ATTRIBUTE_UNUSED
200  static bad implements_getEndLoc(getLocEnd_t Stmt::*) { return bad(); }
201 
202 #define ASSERT_IMPLEMENTS_children(type) \
203  (void) is_good(implements_children(&type::children))
204 #define ASSERT_IMPLEMENTS_getBeginLoc(type) \
205  (void)is_good(implements_getBeginLoc(&type::getBeginLoc))
206 #define ASSERT_IMPLEMENTS_getEndLoc(type) \
207  (void)is_good(implements_getEndLoc(&type::getEndLoc))
208 
209 } // namespace
210 
211 /// Check whether the various Stmt classes implement their member
212 /// functions.
213 LLVM_ATTRIBUTE_UNUSED
214 static inline void check_implementations() {
215 #define ABSTRACT_STMT(type)
216 #define STMT(type, base) \
217  ASSERT_IMPLEMENTS_children(type); \
218  ASSERT_IMPLEMENTS_getBeginLoc(type); \
219  ASSERT_IMPLEMENTS_getEndLoc(type);
220 #include "clang/AST/StmtNodes.inc"
221 }
222 
224  switch (getStmtClass()) {
225  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
226 #define ABSTRACT_STMT(type)
227 #define STMT(type, base) \
228  case Stmt::type##Class: \
229  return static_cast<type*>(this)->children();
230 #include "clang/AST/StmtNodes.inc"
231  }
232  llvm_unreachable("unknown statement kind!");
233 }
234 
235 // Amusing macro metaprogramming hack: check whether a class provides
236 // a more specific implementation of getSourceRange.
237 //
238 // See also Expr.cpp:getExprLoc().
239 namespace {
240 
241  /// This implementation is used when a class provides a custom
242  /// implementation of getSourceRange.
243  template <class S, class T>
244  SourceRange getSourceRangeImpl(const Stmt *stmt,
245  SourceRange (T::*v)() const) {
246  return static_cast<const S*>(stmt)->getSourceRange();
247  }
248 
249  /// This implementation is used when a class doesn't provide a custom
250  /// implementation of getSourceRange. Overload resolution should pick it over
251  /// the implementation above because it's more specialized according to
252  /// function template partial ordering.
253  template <class S>
254  SourceRange getSourceRangeImpl(const Stmt *stmt,
255  SourceRange (Stmt::*v)() const) {
256  return SourceRange(static_cast<const S *>(stmt)->getBeginLoc(),
257  static_cast<const S *>(stmt)->getEndLoc());
258  }
259 
260 } // namespace
261 
263  switch (getStmtClass()) {
264  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
265 #define ABSTRACT_STMT(type)
266 #define STMT(type, base) \
267  case Stmt::type##Class: \
268  return getSourceRangeImpl<type>(this, &type::getSourceRange);
269 #include "clang/AST/StmtNodes.inc"
270  }
271  llvm_unreachable("unknown statement kind!");
272 }
273 
275  // llvm::errs() << "getBeginLoc() for " << getStmtClassName() << "\n";
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 
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 
320  void *Mem =
321  C.Allocate(totalSizeToAlloc<Stmt *>(Stmts.size()), alignof(CompoundStmt));
322  return new (Mem) CompoundStmt(Stmts, LB, RB);
323 }
324 
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 
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 
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 
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 
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 
451  return cast<Expr>(Exprs[i + NumOutputs]);
452 }
453 
454 void GCCAsmStmt::setInputExpr(unsigned i, Expr *E) {
455  Exprs[i + NumOutputs] = E;
456 }
457 
459  return cast<AddrLabelExpr>(Exprs[i + 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 + 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.
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.
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 AsmStr;
735 }
736 
738  return cast<Expr>(Exprs[i]);
739 }
740 
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 
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 
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 
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 
887  auto *DS = getConditionVariableDeclStmt();
888  if (!DS)
889  return nullptr;
890  return cast<VarDecl>(DS->getSingleDecl());
891 }
892 
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 
908  return isa<ObjCAvailabilityCheckExpr>(getCond());
909 }
910 
911 ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
912  Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
913  SourceLocation RP)
914  : Stmt(ForStmtClass), LParenLoc(LP), RParenLoc(RP)
915 {
916  SubExprs[INIT] = Init;
917  setConditionVariable(C, condVar);
918  SubExprs[COND] = Cond;
919  SubExprs[INC] = Inc;
920  SubExprs[BODY] = Body;
921  ForStmtBits.ForLoc = FL;
922 }
923 
925  if (!SubExprs[CONDVAR])
926  return nullptr;
927 
928  auto *DS = cast<DeclStmt>(SubExprs[CONDVAR]);
929  return cast<VarDecl>(DS->getSingleDecl());
930 }
931 
933  if (!V) {
934  SubExprs[CONDVAR] = nullptr;
935  return;
936  }
937 
938  SourceRange VarRange = V->getSourceRange();
939  SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
940  VarRange.getEnd());
941 }
942 
943 SwitchStmt::SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
944  Expr *Cond)
945  : Stmt(SwitchStmtClass), FirstCase(nullptr) {
946  bool HasInit = Init != nullptr;
947  bool HasVar = Var != nullptr;
948  SwitchStmtBits.HasInit = HasInit;
949  SwitchStmtBits.HasVar = HasVar;
950  SwitchStmtBits.AllEnumCasesCovered = false;
951 
952  setCond(Cond);
953  setBody(nullptr);
954  if (HasInit)
955  setInit(Init);
956  if (HasVar)
957  setConditionVariable(Ctx, Var);
958 
959  setSwitchLoc(SourceLocation{});
960 }
961 
962 SwitchStmt::SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar)
963  : Stmt(SwitchStmtClass, Empty) {
964  SwitchStmtBits.HasInit = HasInit;
965  SwitchStmtBits.HasVar = HasVar;
966  SwitchStmtBits.AllEnumCasesCovered = false;
967 }
968 
970  Expr *Cond) {
971  bool HasInit = Init != nullptr;
972  bool HasVar = Var != nullptr;
973  void *Mem = Ctx.Allocate(
974  totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar),
975  alignof(SwitchStmt));
976  return new (Mem) SwitchStmt(Ctx, Init, Var, Cond);
977 }
978 
980  bool HasVar) {
981  void *Mem = Ctx.Allocate(
982  totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar),
983  alignof(SwitchStmt));
984  return new (Mem) SwitchStmt(EmptyShell(), HasInit, HasVar);
985 }
986 
988  auto *DS = getConditionVariableDeclStmt();
989  if (!DS)
990  return nullptr;
991  return cast<VarDecl>(DS->getSingleDecl());
992 }
993 
995  assert(hasVarStorage() &&
996  "This switch statement has no storage for a condition variable!");
997 
998  if (!V) {
999  getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
1000  return;
1001  }
1002 
1003  SourceRange VarRange = V->getSourceRange();
1004  getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
1005  DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
1006 }
1007 
1008 WhileStmt::WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
1009  Stmt *Body, SourceLocation WL)
1010  : Stmt(WhileStmtClass) {
1011  bool HasVar = Var != nullptr;
1012  WhileStmtBits.HasVar = HasVar;
1013 
1014  setCond(Cond);
1015  setBody(Body);
1016  if (HasVar)
1017  setConditionVariable(Ctx, Var);
1018 
1019  setWhileLoc(WL);
1020 }
1021 
1022 WhileStmt::WhileStmt(EmptyShell Empty, bool HasVar)
1023  : Stmt(WhileStmtClass, Empty) {
1024  WhileStmtBits.HasVar = HasVar;
1025 }
1026 
1028  Stmt *Body, SourceLocation WL) {
1029  bool HasVar = Var != nullptr;
1030  void *Mem =
1031  Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar),
1032  alignof(WhileStmt));
1033  return new (Mem) WhileStmt(Ctx, Var, Cond, Body, WL);
1034 }
1035 
1036 WhileStmt *WhileStmt::CreateEmpty(const ASTContext &Ctx, bool HasVar) {
1037  void *Mem =
1038  Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar),
1039  alignof(WhileStmt));
1040  return new (Mem) WhileStmt(EmptyShell(), HasVar);
1041 }
1042 
1044  auto *DS = getConditionVariableDeclStmt();
1045  if (!DS)
1046  return nullptr;
1047  return cast<VarDecl>(DS->getSingleDecl());
1048 }
1049 
1051  assert(hasVarStorage() &&
1052  "This while statement has no storage for a condition variable!");
1053 
1054  if (!V) {
1055  getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
1056  return;
1057  }
1058 
1059  SourceRange VarRange = V->getSourceRange();
1060  getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
1061  DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
1062 }
1063 
1064 // IndirectGotoStmt
1066  if (auto *E = dyn_cast<AddrLabelExpr>(getTarget()->IgnoreParenImpCasts()))
1067  return E->getLabel();
1068  return nullptr;
1069 }
1070 
1071 // ReturnStmt
1072 ReturnStmt::ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
1073  : Stmt(ReturnStmtClass), RetExpr(E) {
1074  bool HasNRVOCandidate = NRVOCandidate != nullptr;
1075  ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
1076  if (HasNRVOCandidate)
1077  setNRVOCandidate(NRVOCandidate);
1078  setReturnLoc(RL);
1079 }
1080 
1081 ReturnStmt::ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate)
1082  : Stmt(ReturnStmtClass, Empty) {
1083  ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
1084 }
1085 
1087  Expr *E, const VarDecl *NRVOCandidate) {
1088  bool HasNRVOCandidate = NRVOCandidate != nullptr;
1089  void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate),
1090  alignof(ReturnStmt));
1091  return new (Mem) ReturnStmt(RL, E, NRVOCandidate);
1092 }
1093 
1095  bool HasNRVOCandidate) {
1096  void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate),
1097  alignof(ReturnStmt));
1098  return new (Mem) ReturnStmt(EmptyShell(), HasNRVOCandidate);
1099 }
1100 
1101 // CaseStmt
1103  SourceLocation caseLoc, SourceLocation ellipsisLoc,
1104  SourceLocation colonLoc) {
1105  bool CaseStmtIsGNURange = rhs != nullptr;
1106  void *Mem = Ctx.Allocate(
1107  totalSizeToAlloc<Stmt *, SourceLocation>(
1108  NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange),
1109  alignof(CaseStmt));
1110  return new (Mem) CaseStmt(lhs, rhs, caseLoc, ellipsisLoc, colonLoc);
1111 }
1112 
1114  bool CaseStmtIsGNURange) {
1115  void *Mem = Ctx.Allocate(
1116  totalSizeToAlloc<Stmt *, SourceLocation>(
1117  NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange),
1118  alignof(CaseStmt));
1119  return new (Mem) CaseStmt(EmptyShell(), CaseStmtIsGNURange);
1120 }
1121 
1122 SEHTryStmt::SEHTryStmt(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock,
1123  Stmt *Handler)
1124  : Stmt(SEHTryStmtClass), IsCXXTry(IsCXXTry), TryLoc(TryLoc) {
1125  Children[TRY] = TryBlock;
1126  Children[HANDLER] = Handler;
1127 }
1128 
1129 SEHTryStmt* SEHTryStmt::Create(const ASTContext &C, bool IsCXXTry,
1130  SourceLocation TryLoc, Stmt *TryBlock,
1131  Stmt *Handler) {
1132  return new(C) SEHTryStmt(IsCXXTry,TryLoc,TryBlock,Handler);
1133 }
1134 
1136  return dyn_cast<SEHExceptStmt>(getHandler());
1137 }
1138 
1140  return dyn_cast<SEHFinallyStmt>(getHandler());
1141 }
1142 
1143 SEHExceptStmt::SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
1144  : Stmt(SEHExceptStmtClass), Loc(Loc) {
1145  Children[FILTER_EXPR] = FilterExpr;
1146  Children[BLOCK] = Block;
1147 }
1148 
1150  Expr *FilterExpr, Stmt *Block) {
1151  return new(C) SEHExceptStmt(Loc,FilterExpr,Block);
1152 }
1153 
1154 SEHFinallyStmt::SEHFinallyStmt(SourceLocation Loc, Stmt *Block)
1155  : Stmt(SEHFinallyStmtClass), Loc(Loc), Block(Block) {}
1156 
1158  Stmt *Block) {
1159  return new(C)SEHFinallyStmt(Loc,Block);
1160 }
1161 
1163  VarDecl *Var)
1164  : VarAndKind(Var, Kind), Loc(Loc) {
1165  switch (Kind) {
1166  case VCK_This:
1167  assert(!Var && "'this' capture cannot have a variable!");
1168  break;
1169  case VCK_ByRef:
1170  assert(Var && "capturing by reference must have a variable!");
1171  break;
1172  case VCK_ByCopy:
1173  assert(Var && "capturing by copy must have a variable!");
1174  assert(
1175  (Var->getType()->isScalarType() || (Var->getType()->isReferenceType() &&
1176  Var->getType()
1177  ->castAs<ReferenceType>()
1178  ->getPointeeType()
1179  ->isScalarType())) &&
1180  "captures by copy are expected to have a scalar type!");
1181  break;
1182  case VCK_VLAType:
1183  assert(!Var &&
1184  "Variable-length array type capture cannot have a variable!");
1185  break;
1186  }
1187 }
1188 
1191  return VarAndKind.getInt();
1192 }
1193 
1195  assert((capturesVariable() || capturesVariableByCopy()) &&
1196  "No variable available for 'this' or VAT capture");
1197  return VarAndKind.getPointer();
1198 }
1199 
1200 CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const {
1201  unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1202 
1203  // Offset of the first Capture object.
1204  unsigned FirstCaptureOffset = llvm::alignTo(Size, alignof(Capture));
1205 
1206  return reinterpret_cast<Capture *>(
1207  reinterpret_cast<char *>(const_cast<CapturedStmt *>(this))
1208  + FirstCaptureOffset);
1209 }
1210 
1211 CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind,
1212  ArrayRef<Capture> Captures,
1213  ArrayRef<Expr *> CaptureInits,
1214  CapturedDecl *CD,
1215  RecordDecl *RD)
1216  : Stmt(CapturedStmtClass), NumCaptures(Captures.size()),
1217  CapDeclAndKind(CD, Kind), TheRecordDecl(RD) {
1218  assert( S && "null captured statement");
1219  assert(CD && "null captured declaration for captured statement");
1220  assert(RD && "null record declaration for captured statement");
1221 
1222  // Copy initialization expressions.
1223  Stmt **Stored = getStoredStmts();
1224  for (unsigned I = 0, N = NumCaptures; I != N; ++I)
1225  *Stored++ = CaptureInits[I];
1226 
1227  // Copy the statement being captured.
1228  *Stored = S;
1229 
1230  // Copy all Capture objects.
1231  Capture *Buffer = getStoredCaptures();
1232  std::copy(Captures.begin(), Captures.end(), Buffer);
1233 }
1234 
1235 CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures)
1236  : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures),
1237  CapDeclAndKind(nullptr, CR_Default) {
1238  getStoredStmts()[NumCaptures] = nullptr;
1239 }
1240 
1243  ArrayRef<Capture> Captures,
1244  ArrayRef<Expr *> CaptureInits,
1245  CapturedDecl *CD,
1246  RecordDecl *RD) {
1247  // The layout is
1248  //
1249  // -----------------------------------------------------------
1250  // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture |
1251  // ----------------^-------------------^----------------------
1252  // getStoredStmts() getStoredCaptures()
1253  //
1254  // where S is the statement being captured.
1255  //
1256  assert(CaptureInits.size() == Captures.size() && "wrong number of arguments");
1257 
1258  unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1);
1259  if (!Captures.empty()) {
1260  // Realign for the following Capture array.
1261  Size = llvm::alignTo(Size, alignof(Capture));
1262  Size += sizeof(Capture) * Captures.size();
1263  }
1264 
1265  void *Mem = Context.Allocate(Size);
1266  return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD);
1267 }
1268 
1270  unsigned NumCaptures) {
1271  unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1272  if (NumCaptures > 0) {
1273  // Realign for the following Capture array.
1274  Size = llvm::alignTo(Size, alignof(Capture));
1275  Size += sizeof(Capture) * NumCaptures;
1276  }
1277 
1278  void *Mem = Context.Allocate(Size);
1279  return new (Mem) CapturedStmt(EmptyShell(), NumCaptures);
1280 }
1281 
1283  // Children are captured field initializers.
1284  return child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
1285 }
1286 
1288  return const_child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
1289 }
1290 
1292  return CapDeclAndKind.getPointer();
1293 }
1294 
1296  return CapDeclAndKind.getPointer();
1297 }
1298 
1299 /// Set the outlined function declaration.
1301  assert(D && "null CapturedDecl");
1302  CapDeclAndKind.setPointer(D);
1303 }
1304 
1305 /// Retrieve the captured region kind.
1307  return CapDeclAndKind.getInt();
1308 }
1309 
1310 /// Set the captured region kind.
1312  CapDeclAndKind.setInt(Kind);
1313 }
1314 
1315 bool CapturedStmt::capturesVariable(const VarDecl *Var) const {
1316  for (const auto &I : captures()) {
1317  if (!I.capturesVariable() && !I.capturesVariableByCopy())
1318  continue;
1319  if (I.getCapturedVar()->getCanonicalDecl() == Var->getCanonicalDecl())
1320  return true;
1321  }
1322 
1323  return false;
1324 }
static AttributedStmt * CreateEmpty(const ASTContext &C, unsigned NumAttrs)
Definition: Stmt.cpp:364
void setConditionVariable(const ASTContext &C, VarDecl *V)
Definition: Stmt.cpp:932
Defines the clang::ASTContext interface.
Capture(SourceLocation Loc, VariableCaptureKind Kind, VarDecl *Var=nullptr)
Create a new capture.
Definition: Stmt.cpp:1162
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
const DeclStmt * getConditionVariableDeclStmt() const
If this ForStmt has a condition variable, return the faux DeclStmt associated with the creation of th...
Definition: Stmt.h:2422
Stmt - This represents one statement.
Definition: Stmt.h:66
IfStmt - This represents an if/then/else.
Definition: Stmt.h:1822
const char * Name
Definition: Stmt.cpp:49
VarDecl * getCapturedVar() const
Retrieve the declaration of the variable being captured.
Definition: Stmt.cpp:1194
C Language Family Type Representation.
Represents an attribute applied to a statement.
Definition: Stmt.h:1764
llvm::iterator_range< child_iterator > child_range
Definition: Stmt.h:1168
unsigned NumOutputs
Definition: Stmt.h:2717
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:706
static AttributedStmt * Create(const ASTContext &C, SourceLocation Loc, ArrayRef< const Attr *> Attrs, Stmt *SubStmt)
Definition: Stmt.cpp:355
static void addStmtClass(const StmtClass s)
Definition: Stmt.cpp:122
bool capturesVariable(const VarDecl *Var) const
True if this variable has been captured.
Definition: Stmt.cpp:1315
void setInputExpr(unsigned i, Expr *E)
Definition: Stmt.cpp:745
void setInputExpr(unsigned i, Expr *E)
Definition: Stmt.cpp:454
Represents a variable declaration or definition.
Definition: Decl.h:827
unsigned AnalyzeAsmString(SmallVectorImpl< AsmStringPiece > &Pieces, const ASTContext &C, unsigned &DiagOffs) const
AnalyzeAsmString - Analyze the asm string of the current asm, decomposing it into pieces...
Definition: Stmt.cpp:534
const char * getName() const
Definition: Stmt.cpp:351
const Expr * getExprStmt() const
Definition: Stmt.cpp:334
Defines the Objective-C statement AST node classes.
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:119
int getNamedOperand(StringRef SymbolicName) const
getNamedOperand - Given a symbolic operand reference like %[foo], translate this into a numeric value...
Definition: Stmt.cpp:510
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
Defines the clang::Expr interface and subclasses for C++ expressions.
static struct StmtClassNameTable StmtClassInfo[Stmt::lastStmtConstant+1]
const char * getStmtClassName() const
Definition: Stmt.cpp:75
Represents a struct/union/class.
Definition: Decl.h:3662
One of these records is kept for each identifier that is lexed.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:160
LLVM_READONLY bool isLetter(unsigned char c)
Return true if this character is an ASCII letter: [a-zA-Z].
Definition: CharInfo.h:111
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:274
bool isReferenceType() const
Definition: Type.h:6403
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
void setCapturedDecl(CapturedDecl *D)
Set the outlined function declaration.
Definition: Stmt.cpp:1300
bool hasNoAsmVariants() const
Return true if {|} are normal characters in the asm string.
Definition: TargetInfo.h:1208
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:49
WhileStmtBitfields WhileStmtBits
Definition: Stmt.h:958
static CapturedStmt * Create(const ASTContext &Context, Stmt *S, CapturedRegionKind Kind, ArrayRef< Capture > Captures, ArrayRef< Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD)
Definition: Stmt.cpp:1241
static IfStmt * Create(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond, Stmt *Then, SourceLocation EL=SourceLocation(), Stmt *Else=nullptr)
Create an IfStmt.
Definition: Stmt.cpp:863
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
const Expr * getOutputExpr(unsigned i) const
Definition: Stmt.cpp:388
static CaseStmt * Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs, SourceLocation caseLoc, SourceLocation ellipsisLoc, SourceLocation colonLoc)
Build a case statement.
Definition: Stmt.cpp:1102
child_range children()
Definition: Stmt.cpp:223
Expr * getOutputExpr(unsigned i)
Definition: Stmt.cpp:439
SwitchStmtBitfields SwitchStmtBits
Definition: Stmt.h:957
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt *> Stmts, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:318
CaseStmt - Represent a case statement.
Definition: Stmt.h:1488
std::string generateAsmString(const ASTContext &C) const
Assemble final IR asm string.
Definition: Stmt.cpp:732
ReturnStmtBitfields ReturnStmtBits
Definition: Stmt.h:964
void setCond(Expr *E)
Definition: Stmt.h:2436
unsigned getNumPlusOperands() const
getNumPlusOperands - Return the number of output operands that have a "+" constraint.
Definition: Stmt.cpp:422
bool isScalarType() const
Definition: Type.h:6739
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4140
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition: Stmt.cpp:924
StmtClass
Definition: Stmt.h:68
MSAsmStmt(const ASTContext &C, SourceLocation asmloc, SourceLocation lbraceloc, bool issimple, bool isvolatile, ArrayRef< Token > asmtoks, unsigned numoutputs, unsigned numinputs, ArrayRef< StringRef > constraints, ArrayRef< Expr *> exprs, StringRef asmstr, ArrayRef< StringRef > clobbers, SourceLocation endloc)
Definition: Stmt.cpp:779
static SEHTryStmt * Create(const ASTContext &C, bool isCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler)
Definition: Stmt.cpp:1129
StringRef getClobber(unsigned i) const
Definition: Stmt.cpp:435
unsigned NumClobbers
Definition: Stmt.h:2719
llvm::iterator_range< const_child_iterator > const_child_range
Definition: Stmt.h:1169
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1320
Describes the capture of either a variable, or &#39;this&#39;, or variable-length array type.
Definition: Stmt.h:3373
std::string generateAsmString(const ASTContext &C) const
Assemble final IR asm string.
Definition: Stmt.cpp:372
void setConditionVariable(const ASTContext &Ctx, VarDecl *V)
Set the condition variable for this if statement.
Definition: Stmt.cpp:893
Exposes information about the current target.
Definition: TargetInfo.h:163
This represents one expression.
Definition: Expr.h:108
Stmt * IgnoreContainers(bool IgnoreCaptured=false)
Skip no-op (attributed, compound) container stmts and skip captured stmt at the top, if IgnoreCaptured is true.
Definition: Stmt.cpp:133
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6923
static ReturnStmt * CreateEmpty(const ASTContext &Ctx, bool HasNRVOCandidate)
Create an empty return statement, optionally with storage for an NRVO candidate.
Definition: Stmt.cpp:1094
AsmStringPiece - this is part of a decomposed asm string specification (for use with the AnalyzeAsmSt...
Definition: Stmt.h:2897
#define V(N, I)
Definition: ASTContext.h:2921
VariableCaptureKind getCaptureKind() const
Determine the kind of capture.
Definition: Stmt.cpp:1190
LabelDecl * getConstantTarget()
getConstantTarget - Returns the fixed target of this indirect goto, if one exists.
Definition: Stmt.cpp:1065
void setBody(Stmt *S)
Definition: Stmt.h:2438
SourceLocation Begin
child_range children()
Definition: Stmt.cpp:1282
Stmt()=delete
CompoundStmtBitfields CompoundStmtBits
Definition: Stmt.h:953
static StringRef copyIntoContext(const ASTContext &C, StringRef str)
Definition: Stmt.cpp:792
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:2620
StringRef getInputConstraint(unsigned i) const
getInputConstraint - Return the specified input constraint.
Definition: Stmt.cpp:468
SourceLocation getEnd() const
Expr * getInputExpr(unsigned i)
Definition: Stmt.cpp:741
Expr * getOutputExpr(unsigned i)
Definition: Stmt.cpp:737
StringRef getClobber(unsigned i) const
Definition: Stmt.cpp:412
static WhileStmt * Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, Stmt *Body, SourceLocation WL)
Create a while statement.
Definition: Stmt.cpp:1027
The result type of a method or function.
void setConditionVariable(const ASTContext &Ctx, VarDecl *V)
Set the condition variable of this while statement.
Definition: Stmt.cpp:1050
do v
Definition: arm_acle.h:64
const SourceManager & SM
Definition: Format.cpp:1667
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2073
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:287
static SEHFinallyStmt * Create(const ASTContext &C, SourceLocation FinallyLoc, Stmt *Block)
Definition: Stmt.cpp:1157
AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
Definition: Stmt.h:2703
void setConditionVariable(const ASTContext &Ctx, VarDecl *VD)
Set the condition variable in this switch statement.
Definition: Stmt.cpp:994
static SwitchStmt * Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond)
Create a switch statement.
Definition: Stmt.cpp:969
Kind
StringRef getInputConstraint(unsigned i) const
getInputConstraint - Return the specified input constraint.
Definition: Stmt.cpp:396
This captures a statement into a function.
Definition: Stmt.h:3360
StringRef getOutputConstraint(unsigned i) const
getOutputConstraint - Return the constraint string for the specified output operand.
Definition: Stmt.cpp:380
Encodes a location in the source.
StringRef getLabelName(unsigned i) const
Definition: Stmt.cpp:462
IfStmtBitfields IfStmtBits
Definition: Stmt.h:956
static void PrintStats()
Definition: Stmt.cpp:97
std::string generateAsmString(const ASTContext &C) const
Assemble final IR asm string.
Definition: Stmt.cpp:711
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:1213
Represents the declaration of a label.
Definition: Decl.h:476
bool capturesVariable() const
Determine whether this capture handles a variable (by reference).
Definition: Stmt.h:3401
ForStmtBitfields ForStmtBits
Definition: Stmt.h:960
GCCAsmStmt(const ASTContext &C, SourceLocation asmloc, bool issimple, bool isvolatile, unsigned numoutputs, unsigned numinputs, IdentifierInfo **names, StringLiteral **constraints, Expr **exprs, StringLiteral *asmstr, unsigned numclobbers, StringLiteral **clobbers, unsigned numlabels, SourceLocation rparenloc)
Definition: Stmt.cpp:753
int64_t getID(const ASTContext &Context) const
Definition: Stmt.cpp:299
StringRef getOutputConstraint(unsigned i) const
getOutputConstraint - Return the constraint string for the specified output operand.
Definition: Stmt.cpp:446
static WhileStmt * CreateEmpty(const ASTContext &Ctx, bool HasVar)
Create an empty while statement optionally with storage for a condition variable. ...
Definition: Stmt.cpp:1036
Expr * getInputExpr(unsigned i)
Definition: Stmt.cpp:450
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2005
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:987
A placeholder type used to construct an empty shell of a type, that will be filled in later (e...
Definition: Stmt.h:1044
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:685
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:3882
Dataflow Directional Tag Classes.
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1043
static CapturedStmt * CreateDeserialized(const ASTContext &Context, unsigned NumCaptures)
Definition: Stmt.cpp:1269
const Stmt * stripLabelLikeStatements() const
Strip off all label-like statements.
Definition: Stmt.cpp:155
static ReturnStmt * Create(const ASTContext &Ctx, SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
Create a return statement.
Definition: Stmt.cpp:1086
unsigned Counter
Definition: Stmt.cpp:50
SEHExceptStmt * getExceptHandler() const
Returns 0 if not defined.
Definition: Stmt.cpp:1135
static LLVM_ATTRIBUTE_UNUSED void check_implementations()
Check whether the various Stmt classes implement their member functions.
Definition: Stmt.cpp:214
char getModifier() const
getModifier - Get the modifier for this operand, if present.
Definition: Stmt.cpp:430
bool isObjCAvailabilityCheck() const
Definition: Stmt.cpp:907
llvm::BumpPtrAllocator & getAllocator() const
Definition: ASTContext.h:681
static CompoundStmt * CreateEmpty(const ASTContext &C, unsigned NumStmts)
Definition: Stmt.cpp:325
bool capturesVariableByCopy() const
Determine whether this capture handles a variable by copy.
Definition: Stmt.h:3404
SwitchStmt - This represents a &#39;switch&#39; stmt.
Definition: Stmt.h:2027
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition: CharInfo.h:93
This file defines OpenMP AST classes for executable directives and clauses.
AddrLabelExpr * getLabelExpr(unsigned i) const
Definition: Stmt.cpp:458
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2721
const Expr * getInputExpr(unsigned i) const
Definition: Stmt.cpp:404
ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar, Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP, SourceLocation RP)
Definition: Stmt.cpp:911
SourceManager & getSourceManager()
Definition: ASTContext.h:678
SEHFinallyStmt * getFinallyHandler() const
Definition: Stmt.cpp:1139
Stmt ** Exprs
Definition: Stmt.h:2721
CapturedDecl * getCapturedDecl()
Retrieve the outlined function declaration.
Definition: Stmt.cpp:1291
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:886
void Deallocate(void *Ptr) const
Definition: ASTContext.h:691
Defines the clang::SourceLocation class and associated facilities.
unsigned Size
Definition: Stmt.cpp:51
WhileStmt - This represents a &#39;while&#39; stmt.
Definition: Stmt.h:2210
static IfStmt * CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar, bool HasInit)
Create an empty IfStmt optionally with storage for an else statement, condition variable and init exp...
Definition: Stmt.cpp:877
VariableCaptureKind
The different capture forms: by &#39;this&#39;, by reference, capture for variable-length array type etc...
Definition: Stmt.h:3364
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:262
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1686
Defines the clang::TargetInfo interface.
capture_range captures()
Definition: Stmt.h:3495
static CaseStmt * CreateEmpty(const ASTContext &Ctx, bool CaseStmtIsGNURange)
Build an empty case statement.
Definition: Stmt.cpp:1113
CapturedRegionKind
The different kinds of captured statement.
Definition: CapturedStmt.h:16
QualType getType() const
Definition: Decl.h:655
static SwitchStmt * CreateEmpty(const ASTContext &Ctx, bool HasInit, bool HasVar)
Create an empty switch statement optionally with storage for an init expression and a condition varia...
Definition: Stmt.cpp:979
static StmtClassNameTable & getStmtInfoTableEntry(Stmt::StmtClass E)
Definition: Stmt.cpp:54
A trivial tuple used to represent a source range.
void setInit(Stmt *S)
Definition: Stmt.h:2435
unsigned NumInputs
Definition: Stmt.h:2718
SourceLocation getBegin() const
const LangOptions & getLangOpts() const
Definition: ASTContext.h:723
static SEHExceptStmt * Create(const ASTContext &C, SourceLocation ExceptLoc, Expr *FilterExpr, Stmt *Block)
Definition: Stmt.cpp:1149
This class handles loading and caching of source files into memory.
void setCapturedRegionKind(CapturedRegionKind Kind)
Set the captured region kind.
Definition: Stmt.cpp:1311
CapturedRegionKind getCapturedRegionKind() const
Retrieve the captured region kind.
Definition: Stmt.cpp:1306
static void EnableStatistics()
Definition: Stmt.cpp:127
#define BLOCK(DERIVED, BASE)
Definition: Template.h:469