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), RBraceLoc(RB) { 367 CompoundStmtBits.NumStmts = Stmts.size(); 368 setStmts(Stmts); 369 CompoundStmtBits.LBraceLoc = LB; 370 } 371 372 void CompoundStmt::setStmts(ArrayRef<Stmt *> Stmts) { 373 assert(CompoundStmtBits.NumStmts == Stmts.size() && 374 "NumStmts doesn't fit in bits of CompoundStmtBits.NumStmts!"); 375 376 std::copy(Stmts.begin(), Stmts.end(), body_begin()); 377 } 378 379 CompoundStmt *CompoundStmt::Create(const ASTContext &C, ArrayRef<Stmt *> Stmts, 380 SourceLocation LB, SourceLocation RB) { 381 void *Mem = 382 C.Allocate(totalSizeToAlloc<Stmt *>(Stmts.size()), alignof(CompoundStmt)); 383 return new (Mem) CompoundStmt(Stmts, LB, RB); 384 } 385 386 CompoundStmt *CompoundStmt::CreateEmpty(const ASTContext &C, 387 unsigned NumStmts) { 388 void *Mem = 389 C.Allocate(totalSizeToAlloc<Stmt *>(NumStmts), alignof(CompoundStmt)); 390 CompoundStmt *New = new (Mem) CompoundStmt(EmptyShell()); 391 New->CompoundStmtBits.NumStmts = NumStmts; 392 return New; 393 } 394 395 const Expr *ValueStmt::getExprStmt() const { 396 const Stmt *S = this; 397 do { 398 if (const auto *E = dyn_cast<Expr>(S)) 399 return E; 400 401 if (const auto *LS = dyn_cast<LabelStmt>(S)) 402 S = LS->getSubStmt(); 403 else if (const auto *AS = dyn_cast<AttributedStmt>(S)) 404 S = AS->getSubStmt(); 405 else 406 llvm_unreachable("unknown kind of ValueStmt"); 407 } while (isa<ValueStmt>(S)); 408 409 return nullptr; 410 } 411 412 const char *LabelStmt::getName() const { 413 return getDecl()->getIdentifier()->getNameStart(); 414 } 415 416 AttributedStmt *AttributedStmt::Create(const ASTContext &C, SourceLocation Loc, 417 ArrayRef<const Attr*> Attrs, 418 Stmt *SubStmt) { 419 assert(!Attrs.empty() && "Attrs should not be empty"); 420 void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(Attrs.size()), 421 alignof(AttributedStmt)); 422 return new (Mem) AttributedStmt(Loc, Attrs, SubStmt); 423 } 424 425 AttributedStmt *AttributedStmt::CreateEmpty(const ASTContext &C, 426 unsigned NumAttrs) { 427 assert(NumAttrs > 0 && "NumAttrs should be greater than zero"); 428 void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(NumAttrs), 429 alignof(AttributedStmt)); 430 return new (Mem) AttributedStmt(EmptyShell(), NumAttrs); 431 } 432 433 std::string AsmStmt::generateAsmString(const ASTContext &C) const { 434 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 435 return gccAsmStmt->generateAsmString(C); 436 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 437 return msAsmStmt->generateAsmString(C); 438 llvm_unreachable("unknown asm statement kind!"); 439 } 440 441 StringRef AsmStmt::getOutputConstraint(unsigned i) const { 442 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 443 return gccAsmStmt->getOutputConstraint(i); 444 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 445 return msAsmStmt->getOutputConstraint(i); 446 llvm_unreachable("unknown asm statement kind!"); 447 } 448 449 const Expr *AsmStmt::getOutputExpr(unsigned i) const { 450 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 451 return gccAsmStmt->getOutputExpr(i); 452 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 453 return msAsmStmt->getOutputExpr(i); 454 llvm_unreachable("unknown asm statement kind!"); 455 } 456 457 StringRef AsmStmt::getInputConstraint(unsigned i) const { 458 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 459 return gccAsmStmt->getInputConstraint(i); 460 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 461 return msAsmStmt->getInputConstraint(i); 462 llvm_unreachable("unknown asm statement kind!"); 463 } 464 465 const Expr *AsmStmt::getInputExpr(unsigned i) const { 466 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 467 return gccAsmStmt->getInputExpr(i); 468 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 469 return msAsmStmt->getInputExpr(i); 470 llvm_unreachable("unknown asm statement kind!"); 471 } 472 473 StringRef AsmStmt::getClobber(unsigned i) const { 474 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 475 return gccAsmStmt->getClobber(i); 476 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 477 return msAsmStmt->getClobber(i); 478 llvm_unreachable("unknown asm statement kind!"); 479 } 480 481 /// getNumPlusOperands - Return the number of output operands that have a "+" 482 /// constraint. 483 unsigned AsmStmt::getNumPlusOperands() const { 484 unsigned Res = 0; 485 for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) 486 if (isOutputPlusConstraint(i)) 487 ++Res; 488 return Res; 489 } 490 491 char GCCAsmStmt::AsmStringPiece::getModifier() const { 492 assert(isOperand() && "Only Operands can have modifiers."); 493 return isLetter(Str[0]) ? Str[0] : '\0'; 494 } 495 496 StringRef GCCAsmStmt::getClobber(unsigned i) const { 497 return getClobberStringLiteral(i)->getString(); 498 } 499 500 Expr *GCCAsmStmt::getOutputExpr(unsigned i) { 501 return cast<Expr>(Exprs[i]); 502 } 503 504 /// getOutputConstraint - Return the constraint string for the specified 505 /// output operand. All output constraints are known to be non-empty (either 506 /// '=' or '+'). 507 StringRef GCCAsmStmt::getOutputConstraint(unsigned i) const { 508 return getOutputConstraintLiteral(i)->getString(); 509 } 510 511 Expr *GCCAsmStmt::getInputExpr(unsigned i) { 512 return cast<Expr>(Exprs[i + NumOutputs]); 513 } 514 515 void GCCAsmStmt::setInputExpr(unsigned i, Expr *E) { 516 Exprs[i + NumOutputs] = E; 517 } 518 519 AddrLabelExpr *GCCAsmStmt::getLabelExpr(unsigned i) const { 520 return cast<AddrLabelExpr>(Exprs[i + NumOutputs + NumInputs]); 521 } 522 523 StringRef GCCAsmStmt::getLabelName(unsigned i) const { 524 return getLabelExpr(i)->getLabel()->getName(); 525 } 526 527 /// getInputConstraint - Return the specified input constraint. Unlike output 528 /// constraints, these can be empty. 529 StringRef GCCAsmStmt::getInputConstraint(unsigned i) const { 530 return getInputConstraintLiteral(i)->getString(); 531 } 532 533 void GCCAsmStmt::setOutputsAndInputsAndClobbers(const ASTContext &C, 534 IdentifierInfo **Names, 535 StringLiteral **Constraints, 536 Stmt **Exprs, 537 unsigned NumOutputs, 538 unsigned NumInputs, 539 unsigned NumLabels, 540 StringLiteral **Clobbers, 541 unsigned NumClobbers) { 542 this->NumOutputs = NumOutputs; 543 this->NumInputs = NumInputs; 544 this->NumClobbers = NumClobbers; 545 this->NumLabels = NumLabels; 546 547 unsigned NumExprs = NumOutputs + NumInputs + NumLabels; 548 549 C.Deallocate(this->Names); 550 this->Names = new (C) IdentifierInfo*[NumExprs]; 551 std::copy(Names, Names + NumExprs, this->Names); 552 553 C.Deallocate(this->Exprs); 554 this->Exprs = new (C) Stmt*[NumExprs]; 555 std::copy(Exprs, Exprs + NumExprs, this->Exprs); 556 557 unsigned NumConstraints = NumOutputs + NumInputs; 558 C.Deallocate(this->Constraints); 559 this->Constraints = new (C) StringLiteral*[NumConstraints]; 560 std::copy(Constraints, Constraints + NumConstraints, this->Constraints); 561 562 C.Deallocate(this->Clobbers); 563 this->Clobbers = new (C) StringLiteral*[NumClobbers]; 564 std::copy(Clobbers, Clobbers + NumClobbers, this->Clobbers); 565 } 566 567 /// getNamedOperand - Given a symbolic operand reference like %[foo], 568 /// translate this into a numeric value needed to reference the same operand. 569 /// This returns -1 if the operand name is invalid. 570 int GCCAsmStmt::getNamedOperand(StringRef SymbolicName) const { 571 unsigned NumPlusOperands = 0; 572 573 // Check if this is an output operand. 574 for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) { 575 if (getOutputName(i) == SymbolicName) 576 return i; 577 } 578 579 for (unsigned i = 0, e = getNumInputs(); i != e; ++i) 580 if (getInputName(i) == SymbolicName) 581 return getNumOutputs() + NumPlusOperands + i; 582 583 for (unsigned i = 0, e = getNumLabels(); i != e; ++i) 584 if (getLabelName(i) == SymbolicName) 585 return i + getNumOutputs() + getNumInputs(); 586 587 // Not found. 588 return -1; 589 } 590 591 /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing 592 /// it into pieces. If the asm string is erroneous, emit errors and return 593 /// true, otherwise return false. 594 unsigned GCCAsmStmt::AnalyzeAsmString(SmallVectorImpl<AsmStringPiece>&Pieces, 595 const ASTContext &C, unsigned &DiagOffs) const { 596 StringRef Str = getAsmString()->getString(); 597 const char *StrStart = Str.begin(); 598 const char *StrEnd = Str.end(); 599 const char *CurPtr = StrStart; 600 601 // "Simple" inline asms have no constraints or operands, just convert the asm 602 // string to escape $'s. 603 if (isSimple()) { 604 std::string Result; 605 for (; CurPtr != StrEnd; ++CurPtr) { 606 switch (*CurPtr) { 607 case '$': 608 Result += "$$"; 609 break; 610 default: 611 Result += *CurPtr; 612 break; 613 } 614 } 615 Pieces.push_back(AsmStringPiece(Result)); 616 return 0; 617 } 618 619 // CurStringPiece - The current string that we are building up as we scan the 620 // asm string. 621 std::string CurStringPiece; 622 623 bool HasVariants = !C.getTargetInfo().hasNoAsmVariants(); 624 625 unsigned LastAsmStringToken = 0; 626 unsigned LastAsmStringOffset = 0; 627 628 while (true) { 629 // Done with the string? 630 if (CurPtr == StrEnd) { 631 if (!CurStringPiece.empty()) 632 Pieces.push_back(AsmStringPiece(CurStringPiece)); 633 return 0; 634 } 635 636 char CurChar = *CurPtr++; 637 switch (CurChar) { 638 case '$': CurStringPiece += "$$"; continue; 639 case '{': CurStringPiece += (HasVariants ? "$(" : "{"); continue; 640 case '|': CurStringPiece += (HasVariants ? "$|" : "|"); continue; 641 case '}': CurStringPiece += (HasVariants ? "$)" : "}"); continue; 642 case '%': 643 break; 644 default: 645 CurStringPiece += CurChar; 646 continue; 647 } 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 break; 660 case '%': // %% -> % 661 case '{': // %{ -> { 662 case '}': // %} -> } 663 CurStringPiece += EscapedChar; 664 continue; 665 case '=': // %= -> Generate a unique ID. 666 CurStringPiece += "${:uid}"; 667 continue; 668 } 669 670 // Otherwise, we have an operand. If we have accumulated a string so far, 671 // add it to the Pieces list. 672 if (!CurStringPiece.empty()) { 673 Pieces.push_back(AsmStringPiece(CurStringPiece)); 674 CurStringPiece.clear(); 675 } 676 677 // Handle operands that have asmSymbolicName (e.g., %x[foo]) and those that 678 // don't (e.g., %x4). 'x' following the '%' is the constraint modifier. 679 680 const char *Begin = CurPtr - 1; // Points to the character following '%'. 681 const char *Percent = Begin - 1; // Points to '%'. 682 683 if (isLetter(EscapedChar)) { 684 if (CurPtr == StrEnd) { // Premature end. 685 DiagOffs = CurPtr-StrStart-1; 686 return diag::err_asm_invalid_escape; 687 } 688 EscapedChar = *CurPtr++; 689 } 690 691 const TargetInfo &TI = C.getTargetInfo(); 692 const SourceManager &SM = C.getSourceManager(); 693 const LangOptions &LO = C.getLangOpts(); 694 695 // Handle operands that don't have asmSymbolicName (e.g., %x4). 696 if (isDigit(EscapedChar)) { 697 // %n - Assembler operand n 698 unsigned N = 0; 699 700 --CurPtr; 701 while (CurPtr != StrEnd && isDigit(*CurPtr)) 702 N = N*10 + ((*CurPtr++)-'0'); 703 704 unsigned NumOperands = getNumOutputs() + getNumPlusOperands() + 705 getNumInputs() + getNumLabels(); 706 if (N >= NumOperands) { 707 DiagOffs = CurPtr-StrStart-1; 708 return diag::err_asm_invalid_operand_number; 709 } 710 711 // Str contains "x4" (Operand without the leading %). 712 std::string Str(Begin, CurPtr - Begin); 713 714 // (BeginLoc, EndLoc) represents the range of the operand we are currently 715 // processing. Unlike Str, the range includes the leading '%'. 716 SourceLocation BeginLoc = getAsmString()->getLocationOfByte( 717 Percent - StrStart, SM, LO, TI, &LastAsmStringToken, 718 &LastAsmStringOffset); 719 SourceLocation EndLoc = getAsmString()->getLocationOfByte( 720 CurPtr - StrStart, SM, LO, TI, &LastAsmStringToken, 721 &LastAsmStringOffset); 722 723 Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc); 724 continue; 725 } 726 727 // Handle operands that have asmSymbolicName (e.g., %x[foo]). 728 if (EscapedChar == '[') { 729 DiagOffs = CurPtr-StrStart-1; 730 731 // Find the ']'. 732 const char *NameEnd = (const char*)memchr(CurPtr, ']', StrEnd-CurPtr); 733 if (NameEnd == nullptr) 734 return diag::err_asm_unterminated_symbolic_operand_name; 735 if (NameEnd == CurPtr) 736 return diag::err_asm_empty_symbolic_operand_name; 737 738 StringRef SymbolicName(CurPtr, NameEnd - CurPtr); 739 740 int N = getNamedOperand(SymbolicName); 741 if (N == -1) { 742 // Verify that an operand with that name exists. 743 DiagOffs = CurPtr-StrStart; 744 return diag::err_asm_unknown_symbolic_operand_name; 745 } 746 747 // Str contains "x[foo]" (Operand without the leading %). 748 std::string Str(Begin, NameEnd + 1 - Begin); 749 750 // (BeginLoc, EndLoc) represents the range of the operand we are currently 751 // processing. Unlike Str, the range includes the leading '%'. 752 SourceLocation BeginLoc = getAsmString()->getLocationOfByte( 753 Percent - StrStart, SM, LO, TI, &LastAsmStringToken, 754 &LastAsmStringOffset); 755 SourceLocation EndLoc = getAsmString()->getLocationOfByte( 756 NameEnd + 1 - StrStart, SM, LO, TI, &LastAsmStringToken, 757 &LastAsmStringOffset); 758 759 Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc); 760 761 CurPtr = NameEnd+1; 762 continue; 763 } 764 765 DiagOffs = CurPtr-StrStart-1; 766 return diag::err_asm_invalid_escape; 767 } 768 } 769 770 /// Assemble final IR asm string (GCC-style). 771 std::string GCCAsmStmt::generateAsmString(const ASTContext &C) const { 772 // Analyze the asm string to decompose it into its pieces. We know that Sema 773 // has already done this, so it is guaranteed to be successful. 774 SmallVector<GCCAsmStmt::AsmStringPiece, 4> Pieces; 775 unsigned DiagOffs; 776 AnalyzeAsmString(Pieces, C, DiagOffs); 777 778 std::string AsmString; 779 for (const auto &Piece : Pieces) { 780 if (Piece.isString()) 781 AsmString += Piece.getString(); 782 else if (Piece.getModifier() == '\0') 783 AsmString += '$' + llvm::utostr(Piece.getOperandNo()); 784 else 785 AsmString += "${" + llvm::utostr(Piece.getOperandNo()) + ':' + 786 Piece.getModifier() + '}'; 787 } 788 return AsmString; 789 } 790 791 /// Assemble final IR asm string (MS-style). 792 std::string MSAsmStmt::generateAsmString(const ASTContext &C) const { 793 // FIXME: This needs to be translated into the IR string representation. 794 SmallVector<StringRef, 8> Pieces; 795 AsmStr.split(Pieces, "\n\t"); 796 std::string MSAsmString; 797 for (size_t I = 0, E = Pieces.size(); I < E; ++I) { 798 StringRef Instruction = Pieces[I]; 799 // For vex/vex2/vex3/evex masm style prefix, convert it to att style 800 // since we don't support masm style prefix in backend. 801 if (Instruction.startswith("vex ")) 802 MSAsmString += '{' + Instruction.substr(0, 3).str() + '}' + 803 Instruction.substr(3).str(); 804 else if (Instruction.startswith("vex2 ") || 805 Instruction.startswith("vex3 ") || Instruction.startswith("evex ")) 806 MSAsmString += '{' + Instruction.substr(0, 4).str() + '}' + 807 Instruction.substr(4).str(); 808 else 809 MSAsmString += Instruction.str(); 810 // If this is not the last instruction, adding back the '\n\t'. 811 if (I < E - 1) 812 MSAsmString += "\n\t"; 813 } 814 return MSAsmString; 815 } 816 817 Expr *MSAsmStmt::getOutputExpr(unsigned i) { 818 return cast<Expr>(Exprs[i]); 819 } 820 821 Expr *MSAsmStmt::getInputExpr(unsigned i) { 822 return cast<Expr>(Exprs[i + NumOutputs]); 823 } 824 825 void MSAsmStmt::setInputExpr(unsigned i, Expr *E) { 826 Exprs[i + NumOutputs] = E; 827 } 828 829 //===----------------------------------------------------------------------===// 830 // Constructors 831 //===----------------------------------------------------------------------===// 832 833 GCCAsmStmt::GCCAsmStmt(const ASTContext &C, SourceLocation asmloc, 834 bool issimple, bool isvolatile, unsigned numoutputs, 835 unsigned numinputs, IdentifierInfo **names, 836 StringLiteral **constraints, Expr **exprs, 837 StringLiteral *asmstr, unsigned numclobbers, 838 StringLiteral **clobbers, unsigned numlabels, 839 SourceLocation rparenloc) 840 : AsmStmt(GCCAsmStmtClass, asmloc, issimple, isvolatile, numoutputs, 841 numinputs, numclobbers), 842 RParenLoc(rparenloc), AsmStr(asmstr), NumLabels(numlabels) { 843 unsigned NumExprs = NumOutputs + NumInputs + NumLabels; 844 845 Names = new (C) IdentifierInfo*[NumExprs]; 846 std::copy(names, names + NumExprs, Names); 847 848 Exprs = new (C) Stmt*[NumExprs]; 849 std::copy(exprs, exprs + NumExprs, Exprs); 850 851 unsigned NumConstraints = NumOutputs + NumInputs; 852 Constraints = new (C) StringLiteral*[NumConstraints]; 853 std::copy(constraints, constraints + NumConstraints, Constraints); 854 855 Clobbers = new (C) StringLiteral*[NumClobbers]; 856 std::copy(clobbers, clobbers + NumClobbers, Clobbers); 857 } 858 859 MSAsmStmt::MSAsmStmt(const ASTContext &C, SourceLocation asmloc, 860 SourceLocation lbraceloc, bool issimple, bool isvolatile, 861 ArrayRef<Token> asmtoks, unsigned numoutputs, 862 unsigned numinputs, 863 ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs, 864 StringRef asmstr, ArrayRef<StringRef> clobbers, 865 SourceLocation endloc) 866 : AsmStmt(MSAsmStmtClass, asmloc, issimple, isvolatile, numoutputs, 867 numinputs, clobbers.size()), LBraceLoc(lbraceloc), 868 EndLoc(endloc), NumAsmToks(asmtoks.size()) { 869 initialize(C, asmstr, asmtoks, constraints, exprs, clobbers); 870 } 871 872 static StringRef copyIntoContext(const ASTContext &C, StringRef str) { 873 return str.copy(C); 874 } 875 876 void MSAsmStmt::initialize(const ASTContext &C, StringRef asmstr, 877 ArrayRef<Token> asmtoks, 878 ArrayRef<StringRef> constraints, 879 ArrayRef<Expr*> exprs, 880 ArrayRef<StringRef> clobbers) { 881 assert(NumAsmToks == asmtoks.size()); 882 assert(NumClobbers == clobbers.size()); 883 884 assert(exprs.size() == NumOutputs + NumInputs); 885 assert(exprs.size() == constraints.size()); 886 887 AsmStr = copyIntoContext(C, asmstr); 888 889 Exprs = new (C) Stmt*[exprs.size()]; 890 std::copy(exprs.begin(), exprs.end(), Exprs); 891 892 AsmToks = new (C) Token[asmtoks.size()]; 893 std::copy(asmtoks.begin(), asmtoks.end(), AsmToks); 894 895 Constraints = new (C) StringRef[exprs.size()]; 896 std::transform(constraints.begin(), constraints.end(), Constraints, 897 [&](StringRef Constraint) { 898 return copyIntoContext(C, Constraint); 899 }); 900 901 Clobbers = new (C) StringRef[NumClobbers]; 902 // FIXME: Avoid the allocation/copy if at all possible. 903 std::transform(clobbers.begin(), clobbers.end(), Clobbers, 904 [&](StringRef Clobber) { 905 return copyIntoContext(C, Clobber); 906 }); 907 } 908 909 IfStmt::IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, 910 Stmt *Init, VarDecl *Var, Expr *Cond, SourceLocation LPL, 911 SourceLocation RPL, Stmt *Then, SourceLocation EL, Stmt *Else) 912 : Stmt(IfStmtClass), LParenLoc(LPL), RParenLoc(RPL) { 913 bool HasElse = Else != nullptr; 914 bool HasVar = Var != nullptr; 915 bool HasInit = Init != nullptr; 916 IfStmtBits.HasElse = HasElse; 917 IfStmtBits.HasVar = HasVar; 918 IfStmtBits.HasInit = HasInit; 919 920 setConstexpr(IsConstexpr); 921 922 setCond(Cond); 923 setThen(Then); 924 if (HasElse) 925 setElse(Else); 926 if (HasVar) 927 setConditionVariable(Ctx, Var); 928 if (HasInit) 929 setInit(Init); 930 931 setIfLoc(IL); 932 if (HasElse) 933 setElseLoc(EL); 934 } 935 936 IfStmt::IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit) 937 : Stmt(IfStmtClass, Empty) { 938 IfStmtBits.HasElse = HasElse; 939 IfStmtBits.HasVar = HasVar; 940 IfStmtBits.HasInit = HasInit; 941 } 942 943 IfStmt *IfStmt::Create(const ASTContext &Ctx, SourceLocation IL, 944 bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond, 945 SourceLocation LPL, SourceLocation RPL, Stmt *Then, 946 SourceLocation EL, Stmt *Else) { 947 bool HasElse = Else != nullptr; 948 bool HasVar = Var != nullptr; 949 bool HasInit = Init != nullptr; 950 void *Mem = Ctx.Allocate( 951 totalSizeToAlloc<Stmt *, SourceLocation>( 952 NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse), 953 alignof(IfStmt)); 954 return new (Mem) 955 IfStmt(Ctx, IL, IsConstexpr, Init, Var, Cond, LPL, RPL, Then, EL, Else); 956 } 957 958 IfStmt *IfStmt::CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar, 959 bool HasInit) { 960 void *Mem = Ctx.Allocate( 961 totalSizeToAlloc<Stmt *, SourceLocation>( 962 NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse), 963 alignof(IfStmt)); 964 return new (Mem) IfStmt(EmptyShell(), HasElse, HasVar, HasInit); 965 } 966 967 VarDecl *IfStmt::getConditionVariable() { 968 auto *DS = getConditionVariableDeclStmt(); 969 if (!DS) 970 return nullptr; 971 return cast<VarDecl>(DS->getSingleDecl()); 972 } 973 974 void IfStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) { 975 assert(hasVarStorage() && 976 "This if statement has no storage for a condition variable!"); 977 978 if (!V) { 979 getTrailingObjects<Stmt *>()[varOffset()] = nullptr; 980 return; 981 } 982 983 SourceRange VarRange = V->getSourceRange(); 984 getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx) 985 DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd()); 986 } 987 988 bool IfStmt::isObjCAvailabilityCheck() const { 989 return isa<ObjCAvailabilityCheckExpr>(getCond()); 990 } 991 992 Optional<const Stmt*> IfStmt::getNondiscardedCase(const ASTContext &Ctx) const { 993 if (!isConstexpr() || getCond()->isValueDependent()) 994 return None; 995 return !getCond()->EvaluateKnownConstInt(Ctx) ? getElse() : getThen(); 996 } 997 998 ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar, 999 Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP, 1000 SourceLocation RP) 1001 : Stmt(ForStmtClass), LParenLoc(LP), RParenLoc(RP) 1002 { 1003 SubExprs[INIT] = Init; 1004 setConditionVariable(C, condVar); 1005 SubExprs[COND] = Cond; 1006 SubExprs[INC] = Inc; 1007 SubExprs[BODY] = Body; 1008 ForStmtBits.ForLoc = FL; 1009 } 1010 1011 VarDecl *ForStmt::getConditionVariable() const { 1012 if (!SubExprs[CONDVAR]) 1013 return nullptr; 1014 1015 auto *DS = cast<DeclStmt>(SubExprs[CONDVAR]); 1016 return cast<VarDecl>(DS->getSingleDecl()); 1017 } 1018 1019 void ForStmt::setConditionVariable(const ASTContext &C, VarDecl *V) { 1020 if (!V) { 1021 SubExprs[CONDVAR] = nullptr; 1022 return; 1023 } 1024 1025 SourceRange VarRange = V->getSourceRange(); 1026 SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(), 1027 VarRange.getEnd()); 1028 } 1029 1030 SwitchStmt::SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, 1031 Expr *Cond, SourceLocation LParenLoc, 1032 SourceLocation RParenLoc) 1033 : Stmt(SwitchStmtClass), FirstCase(nullptr), LParenLoc(LParenLoc), 1034 RParenLoc(RParenLoc) { 1035 bool HasInit = Init != nullptr; 1036 bool HasVar = Var != nullptr; 1037 SwitchStmtBits.HasInit = HasInit; 1038 SwitchStmtBits.HasVar = HasVar; 1039 SwitchStmtBits.AllEnumCasesCovered = false; 1040 1041 setCond(Cond); 1042 setBody(nullptr); 1043 if (HasInit) 1044 setInit(Init); 1045 if (HasVar) 1046 setConditionVariable(Ctx, Var); 1047 1048 setSwitchLoc(SourceLocation{}); 1049 } 1050 1051 SwitchStmt::SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar) 1052 : Stmt(SwitchStmtClass, Empty) { 1053 SwitchStmtBits.HasInit = HasInit; 1054 SwitchStmtBits.HasVar = HasVar; 1055 SwitchStmtBits.AllEnumCasesCovered = false; 1056 } 1057 1058 SwitchStmt *SwitchStmt::Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, 1059 Expr *Cond, SourceLocation LParenLoc, 1060 SourceLocation RParenLoc) { 1061 bool HasInit = Init != nullptr; 1062 bool HasVar = Var != nullptr; 1063 void *Mem = Ctx.Allocate( 1064 totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar), 1065 alignof(SwitchStmt)); 1066 return new (Mem) SwitchStmt(Ctx, Init, Var, Cond, LParenLoc, RParenLoc); 1067 } 1068 1069 SwitchStmt *SwitchStmt::CreateEmpty(const ASTContext &Ctx, bool HasInit, 1070 bool HasVar) { 1071 void *Mem = Ctx.Allocate( 1072 totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar), 1073 alignof(SwitchStmt)); 1074 return new (Mem) SwitchStmt(EmptyShell(), HasInit, HasVar); 1075 } 1076 1077 VarDecl *SwitchStmt::getConditionVariable() { 1078 auto *DS = getConditionVariableDeclStmt(); 1079 if (!DS) 1080 return nullptr; 1081 return cast<VarDecl>(DS->getSingleDecl()); 1082 } 1083 1084 void SwitchStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) { 1085 assert(hasVarStorage() && 1086 "This switch statement has no storage for a condition variable!"); 1087 1088 if (!V) { 1089 getTrailingObjects<Stmt *>()[varOffset()] = nullptr; 1090 return; 1091 } 1092 1093 SourceRange VarRange = V->getSourceRange(); 1094 getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx) 1095 DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd()); 1096 } 1097 1098 WhileStmt::WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, 1099 Stmt *Body, SourceLocation WL, SourceLocation LParenLoc, 1100 SourceLocation RParenLoc) 1101 : Stmt(WhileStmtClass) { 1102 bool HasVar = Var != nullptr; 1103 WhileStmtBits.HasVar = HasVar; 1104 1105 setCond(Cond); 1106 setBody(Body); 1107 if (HasVar) 1108 setConditionVariable(Ctx, Var); 1109 1110 setWhileLoc(WL); 1111 setLParenLoc(LParenLoc); 1112 setRParenLoc(RParenLoc); 1113 } 1114 1115 WhileStmt::WhileStmt(EmptyShell Empty, bool HasVar) 1116 : Stmt(WhileStmtClass, Empty) { 1117 WhileStmtBits.HasVar = HasVar; 1118 } 1119 1120 WhileStmt *WhileStmt::Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, 1121 Stmt *Body, SourceLocation WL, 1122 SourceLocation LParenLoc, 1123 SourceLocation RParenLoc) { 1124 bool HasVar = Var != nullptr; 1125 void *Mem = 1126 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar), 1127 alignof(WhileStmt)); 1128 return new (Mem) WhileStmt(Ctx, Var, Cond, Body, WL, LParenLoc, RParenLoc); 1129 } 1130 1131 WhileStmt *WhileStmt::CreateEmpty(const ASTContext &Ctx, bool HasVar) { 1132 void *Mem = 1133 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar), 1134 alignof(WhileStmt)); 1135 return new (Mem) WhileStmt(EmptyShell(), HasVar); 1136 } 1137 1138 VarDecl *WhileStmt::getConditionVariable() { 1139 auto *DS = getConditionVariableDeclStmt(); 1140 if (!DS) 1141 return nullptr; 1142 return cast<VarDecl>(DS->getSingleDecl()); 1143 } 1144 1145 void WhileStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) { 1146 assert(hasVarStorage() && 1147 "This while statement has no storage for a condition variable!"); 1148 1149 if (!V) { 1150 getTrailingObjects<Stmt *>()[varOffset()] = nullptr; 1151 return; 1152 } 1153 1154 SourceRange VarRange = V->getSourceRange(); 1155 getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx) 1156 DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd()); 1157 } 1158 1159 // IndirectGotoStmt 1160 LabelDecl *IndirectGotoStmt::getConstantTarget() { 1161 if (auto *E = dyn_cast<AddrLabelExpr>(getTarget()->IgnoreParenImpCasts())) 1162 return E->getLabel(); 1163 return nullptr; 1164 } 1165 1166 // ReturnStmt 1167 ReturnStmt::ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate) 1168 : Stmt(ReturnStmtClass), RetExpr(E) { 1169 bool HasNRVOCandidate = NRVOCandidate != nullptr; 1170 ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate; 1171 if (HasNRVOCandidate) 1172 setNRVOCandidate(NRVOCandidate); 1173 setReturnLoc(RL); 1174 } 1175 1176 ReturnStmt::ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate) 1177 : Stmt(ReturnStmtClass, Empty) { 1178 ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate; 1179 } 1180 1181 ReturnStmt *ReturnStmt::Create(const ASTContext &Ctx, SourceLocation RL, 1182 Expr *E, const VarDecl *NRVOCandidate) { 1183 bool HasNRVOCandidate = NRVOCandidate != nullptr; 1184 void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate), 1185 alignof(ReturnStmt)); 1186 return new (Mem) ReturnStmt(RL, E, NRVOCandidate); 1187 } 1188 1189 ReturnStmt *ReturnStmt::CreateEmpty(const ASTContext &Ctx, 1190 bool HasNRVOCandidate) { 1191 void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate), 1192 alignof(ReturnStmt)); 1193 return new (Mem) ReturnStmt(EmptyShell(), HasNRVOCandidate); 1194 } 1195 1196 // CaseStmt 1197 CaseStmt *CaseStmt::Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs, 1198 SourceLocation caseLoc, SourceLocation ellipsisLoc, 1199 SourceLocation colonLoc) { 1200 bool CaseStmtIsGNURange = rhs != nullptr; 1201 void *Mem = Ctx.Allocate( 1202 totalSizeToAlloc<Stmt *, SourceLocation>( 1203 NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange), 1204 alignof(CaseStmt)); 1205 return new (Mem) CaseStmt(lhs, rhs, caseLoc, ellipsisLoc, colonLoc); 1206 } 1207 1208 CaseStmt *CaseStmt::CreateEmpty(const ASTContext &Ctx, 1209 bool CaseStmtIsGNURange) { 1210 void *Mem = Ctx.Allocate( 1211 totalSizeToAlloc<Stmt *, SourceLocation>( 1212 NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange), 1213 alignof(CaseStmt)); 1214 return new (Mem) CaseStmt(EmptyShell(), CaseStmtIsGNURange); 1215 } 1216 1217 SEHTryStmt::SEHTryStmt(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock, 1218 Stmt *Handler) 1219 : Stmt(SEHTryStmtClass), IsCXXTry(IsCXXTry), TryLoc(TryLoc) { 1220 Children[TRY] = TryBlock; 1221 Children[HANDLER] = Handler; 1222 } 1223 1224 SEHTryStmt* SEHTryStmt::Create(const ASTContext &C, bool IsCXXTry, 1225 SourceLocation TryLoc, Stmt *TryBlock, 1226 Stmt *Handler) { 1227 return new(C) SEHTryStmt(IsCXXTry,TryLoc,TryBlock,Handler); 1228 } 1229 1230 SEHExceptStmt* SEHTryStmt::getExceptHandler() const { 1231 return dyn_cast<SEHExceptStmt>(getHandler()); 1232 } 1233 1234 SEHFinallyStmt* SEHTryStmt::getFinallyHandler() const { 1235 return dyn_cast<SEHFinallyStmt>(getHandler()); 1236 } 1237 1238 SEHExceptStmt::SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block) 1239 : Stmt(SEHExceptStmtClass), Loc(Loc) { 1240 Children[FILTER_EXPR] = FilterExpr; 1241 Children[BLOCK] = Block; 1242 } 1243 1244 SEHExceptStmt* SEHExceptStmt::Create(const ASTContext &C, SourceLocation Loc, 1245 Expr *FilterExpr, Stmt *Block) { 1246 return new(C) SEHExceptStmt(Loc,FilterExpr,Block); 1247 } 1248 1249 SEHFinallyStmt::SEHFinallyStmt(SourceLocation Loc, Stmt *Block) 1250 : Stmt(SEHFinallyStmtClass), Loc(Loc), Block(Block) {} 1251 1252 SEHFinallyStmt* SEHFinallyStmt::Create(const ASTContext &C, SourceLocation Loc, 1253 Stmt *Block) { 1254 return new(C)SEHFinallyStmt(Loc,Block); 1255 } 1256 1257 CapturedStmt::Capture::Capture(SourceLocation Loc, VariableCaptureKind Kind, 1258 VarDecl *Var) 1259 : VarAndKind(Var, Kind), Loc(Loc) { 1260 switch (Kind) { 1261 case VCK_This: 1262 assert(!Var && "'this' capture cannot have a variable!"); 1263 break; 1264 case VCK_ByRef: 1265 assert(Var && "capturing by reference must have a variable!"); 1266 break; 1267 case VCK_ByCopy: 1268 assert(Var && "capturing by copy must have a variable!"); 1269 assert( 1270 (Var->getType()->isScalarType() || (Var->getType()->isReferenceType() && 1271 Var->getType() 1272 ->castAs<ReferenceType>() 1273 ->getPointeeType() 1274 ->isScalarType())) && 1275 "captures by copy are expected to have a scalar type!"); 1276 break; 1277 case VCK_VLAType: 1278 assert(!Var && 1279 "Variable-length array type capture cannot have a variable!"); 1280 break; 1281 } 1282 } 1283 1284 CapturedStmt::VariableCaptureKind 1285 CapturedStmt::Capture::getCaptureKind() const { 1286 return VarAndKind.getInt(); 1287 } 1288 1289 VarDecl *CapturedStmt::Capture::getCapturedVar() const { 1290 assert((capturesVariable() || capturesVariableByCopy()) && 1291 "No variable available for 'this' or VAT capture"); 1292 return VarAndKind.getPointer(); 1293 } 1294 1295 CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const { 1296 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1); 1297 1298 // Offset of the first Capture object. 1299 unsigned FirstCaptureOffset = llvm::alignTo(Size, alignof(Capture)); 1300 1301 return reinterpret_cast<Capture *>( 1302 reinterpret_cast<char *>(const_cast<CapturedStmt *>(this)) 1303 + FirstCaptureOffset); 1304 } 1305 1306 CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind, 1307 ArrayRef<Capture> Captures, 1308 ArrayRef<Expr *> CaptureInits, 1309 CapturedDecl *CD, 1310 RecordDecl *RD) 1311 : Stmt(CapturedStmtClass), NumCaptures(Captures.size()), 1312 CapDeclAndKind(CD, Kind), TheRecordDecl(RD) { 1313 assert( S && "null captured statement"); 1314 assert(CD && "null captured declaration for captured statement"); 1315 assert(RD && "null record declaration for captured statement"); 1316 1317 // Copy initialization expressions. 1318 Stmt **Stored = getStoredStmts(); 1319 for (unsigned I = 0, N = NumCaptures; I != N; ++I) 1320 *Stored++ = CaptureInits[I]; 1321 1322 // Copy the statement being captured. 1323 *Stored = S; 1324 1325 // Copy all Capture objects. 1326 Capture *Buffer = getStoredCaptures(); 1327 std::copy(Captures.begin(), Captures.end(), Buffer); 1328 } 1329 1330 CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures) 1331 : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures), 1332 CapDeclAndKind(nullptr, CR_Default) { 1333 getStoredStmts()[NumCaptures] = nullptr; 1334 } 1335 1336 CapturedStmt *CapturedStmt::Create(const ASTContext &Context, Stmt *S, 1337 CapturedRegionKind Kind, 1338 ArrayRef<Capture> Captures, 1339 ArrayRef<Expr *> CaptureInits, 1340 CapturedDecl *CD, 1341 RecordDecl *RD) { 1342 // The layout is 1343 // 1344 // ----------------------------------------------------------- 1345 // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture | 1346 // ----------------^-------------------^---------------------- 1347 // getStoredStmts() getStoredCaptures() 1348 // 1349 // where S is the statement being captured. 1350 // 1351 assert(CaptureInits.size() == Captures.size() && "wrong number of arguments"); 1352 1353 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1); 1354 if (!Captures.empty()) { 1355 // Realign for the following Capture array. 1356 Size = llvm::alignTo(Size, alignof(Capture)); 1357 Size += sizeof(Capture) * Captures.size(); 1358 } 1359 1360 void *Mem = Context.Allocate(Size); 1361 return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD); 1362 } 1363 1364 CapturedStmt *CapturedStmt::CreateDeserialized(const ASTContext &Context, 1365 unsigned NumCaptures) { 1366 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1); 1367 if (NumCaptures > 0) { 1368 // Realign for the following Capture array. 1369 Size = llvm::alignTo(Size, alignof(Capture)); 1370 Size += sizeof(Capture) * NumCaptures; 1371 } 1372 1373 void *Mem = Context.Allocate(Size); 1374 return new (Mem) CapturedStmt(EmptyShell(), NumCaptures); 1375 } 1376 1377 Stmt::child_range CapturedStmt::children() { 1378 // Children are captured field initializers. 1379 return child_range(getStoredStmts(), getStoredStmts() + NumCaptures); 1380 } 1381 1382 Stmt::const_child_range CapturedStmt::children() const { 1383 return const_child_range(getStoredStmts(), getStoredStmts() + NumCaptures); 1384 } 1385 1386 CapturedDecl *CapturedStmt::getCapturedDecl() { 1387 return CapDeclAndKind.getPointer(); 1388 } 1389 1390 const CapturedDecl *CapturedStmt::getCapturedDecl() const { 1391 return CapDeclAndKind.getPointer(); 1392 } 1393 1394 /// Set the outlined function declaration. 1395 void CapturedStmt::setCapturedDecl(CapturedDecl *D) { 1396 assert(D && "null CapturedDecl"); 1397 CapDeclAndKind.setPointer(D); 1398 } 1399 1400 /// Retrieve the captured region kind. 1401 CapturedRegionKind CapturedStmt::getCapturedRegionKind() const { 1402 return CapDeclAndKind.getInt(); 1403 } 1404 1405 /// Set the captured region kind. 1406 void CapturedStmt::setCapturedRegionKind(CapturedRegionKind Kind) { 1407 CapDeclAndKind.setInt(Kind); 1408 } 1409 1410 bool CapturedStmt::capturesVariable(const VarDecl *Var) const { 1411 for (const auto &I : captures()) { 1412 if (!I.capturesVariable() && !I.capturesVariableByCopy()) 1413 continue; 1414 if (I.getCapturedVar()->getCanonicalDecl() == Var->getCanonicalDecl()) 1415 return true; 1416 } 1417 1418 return false; 1419 } 1420