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