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