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