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