1 //===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===// 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 // Instrumentation-based profile-guided optimization 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenPGO.h" 15 #include "CodeGenFunction.h" 16 #include "clang/AST/RecursiveASTVisitor.h" 17 #include "clang/AST/StmtVisitor.h" 18 #include "llvm/Config/config.h" // for strtoull()/strtoul() define 19 #include "llvm/IR/MDBuilder.h" 20 #include "llvm/Support/FileSystem.h" 21 22 using namespace clang; 23 using namespace CodeGen; 24 25 static void ReportBadPGOData(CodeGenModule &CGM, const char *Message) { 26 DiagnosticsEngine &Diags = CGM.getDiags(); 27 unsigned diagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0"); 28 Diags.Report(diagID) << Message; 29 } 30 31 PGOProfileData::PGOProfileData(CodeGenModule &CGM, std::string Path) 32 : CGM(CGM) { 33 if (llvm::MemoryBuffer::getFile(Path, DataBuffer)) { 34 ReportBadPGOData(CGM, "failed to open pgo data file"); 35 return; 36 } 37 38 if (DataBuffer->getBufferSize() > std::numeric_limits<unsigned>::max()) { 39 ReportBadPGOData(CGM, "pgo data file too big"); 40 return; 41 } 42 43 // Scan through the data file and map each function to the corresponding 44 // file offset where its counts are stored. 45 const char *BufferStart = DataBuffer->getBufferStart(); 46 const char *BufferEnd = DataBuffer->getBufferEnd(); 47 const char *CurPtr = BufferStart; 48 uint64_t MaxCount = 0; 49 while (CurPtr < BufferEnd) { 50 // Read the function name. 51 const char *FuncStart = CurPtr; 52 // For Objective-C methods, the name may include whitespace, so search 53 // backward from the end of the line to find the space that separates the 54 // name from the number of counters. (This is a temporary hack since we are 55 // going to completely replace this file format in the near future.) 56 CurPtr = strchr(CurPtr, '\n'); 57 if (!CurPtr) { 58 ReportBadPGOData(CGM, "pgo data file has malformed function entry"); 59 return; 60 } 61 StringRef FuncName(FuncStart, CurPtr - FuncStart); 62 63 // Skip over the function hash. 64 CurPtr = strchr(++CurPtr, '\n'); 65 if (!CurPtr) { 66 ReportBadPGOData(CGM, "pgo data file is missing the function hash"); 67 return; 68 } 69 70 // Read the number of counters. 71 char *EndPtr; 72 unsigned NumCounters = strtoul(++CurPtr, &EndPtr, 10); 73 if (EndPtr == CurPtr || *EndPtr != '\n' || NumCounters <= 0) { 74 ReportBadPGOData(CGM, "pgo data file has unexpected number of counters"); 75 return; 76 } 77 CurPtr = EndPtr; 78 79 // Read function count. 80 uint64_t Count = strtoull(CurPtr, &EndPtr, 10); 81 if (EndPtr == CurPtr || *EndPtr != '\n') { 82 ReportBadPGOData(CGM, "pgo-data file has bad count value"); 83 return; 84 } 85 CurPtr = EndPtr; // Point to '\n'. 86 FunctionCounts[FuncName] = Count; 87 MaxCount = Count > MaxCount ? Count : MaxCount; 88 89 // There is one line for each counter; skip over those lines. 90 // Since function count is already read, we start the loop from 1. 91 for (unsigned N = 1; N < NumCounters; ++N) { 92 CurPtr = strchr(++CurPtr, '\n'); 93 if (!CurPtr) { 94 ReportBadPGOData(CGM, "pgo data file is missing some counter info"); 95 return; 96 } 97 } 98 99 // Skip over the blank line separating functions. 100 CurPtr += 2; 101 102 DataOffsets[FuncName] = FuncStart - BufferStart; 103 } 104 MaxFunctionCount = MaxCount; 105 } 106 107 bool PGOProfileData::getFunctionCounts(StringRef FuncName, uint64_t &FuncHash, 108 std::vector<uint64_t> &Counts) { 109 // Find the relevant section of the pgo-data file. 110 llvm::StringMap<unsigned>::const_iterator OffsetIter = 111 DataOffsets.find(FuncName); 112 if (OffsetIter == DataOffsets.end()) 113 return true; 114 const char *CurPtr = DataBuffer->getBufferStart() + OffsetIter->getValue(); 115 116 // Skip over the function name. 117 CurPtr = strchr(CurPtr, '\n'); 118 assert(CurPtr && "pgo-data has corrupted function entry"); 119 120 char *EndPtr; 121 // Read the function hash. 122 FuncHash = strtoull(++CurPtr, &EndPtr, 10); 123 assert(EndPtr != CurPtr && *EndPtr == '\n' && 124 "pgo-data file has corrupted function hash"); 125 CurPtr = EndPtr; 126 127 // Read the number of counters. 128 unsigned NumCounters = strtoul(++CurPtr, &EndPtr, 10); 129 assert(EndPtr != CurPtr && *EndPtr == '\n' && NumCounters > 0 && 130 "pgo-data file has corrupted number of counters"); 131 CurPtr = EndPtr; 132 133 Counts.reserve(NumCounters); 134 135 for (unsigned N = 0; N < NumCounters; ++N) { 136 // Read the count value. 137 uint64_t Count = strtoull(CurPtr, &EndPtr, 10); 138 if (EndPtr == CurPtr || *EndPtr != '\n') { 139 ReportBadPGOData(CGM, "pgo-data file has bad count value"); 140 return true; 141 } 142 Counts.push_back(Count); 143 CurPtr = EndPtr + 1; 144 } 145 146 // Make sure the number of counters matches up. 147 if (Counts.size() != NumCounters) { 148 ReportBadPGOData(CGM, "pgo-data file has inconsistent counters"); 149 return true; 150 } 151 152 return false; 153 } 154 155 void CodeGenPGO::setFuncName(llvm::Function *Fn) { 156 RawFuncName = Fn->getName(); 157 158 // Function names may be prefixed with a binary '1' to indicate 159 // that the backend should not modify the symbols due to any platform 160 // naming convention. Do not include that '1' in the PGO profile name. 161 if (RawFuncName[0] == '\1') 162 RawFuncName = RawFuncName.substr(1); 163 164 if (!Fn->hasLocalLinkage()) { 165 PrefixedFuncName.reset(new std::string(RawFuncName)); 166 return; 167 } 168 169 // For local symbols, prepend the main file name to distinguish them. 170 // Do not include the full path in the file name since there's no guarantee 171 // that it will stay the same, e.g., if the files are checked out from 172 // version control in different locations. 173 PrefixedFuncName.reset(new std::string(CGM.getCodeGenOpts().MainFileName)); 174 if (PrefixedFuncName->empty()) 175 PrefixedFuncName->assign("<unknown>"); 176 PrefixedFuncName->append(":"); 177 PrefixedFuncName->append(RawFuncName); 178 } 179 180 static llvm::Function *getRegisterFunc(CodeGenModule &CGM) { 181 return CGM.getModule().getFunction("__llvm_profile_register_functions"); 182 } 183 184 static llvm::BasicBlock *getOrInsertRegisterBB(CodeGenModule &CGM) { 185 // Don't do this for Darwin. compiler-rt uses linker magic. 186 if (CGM.getTarget().getTriple().isOSDarwin()) 187 return nullptr; 188 189 // Only need to insert this once per module. 190 if (llvm::Function *RegisterF = getRegisterFunc(CGM)) 191 return &RegisterF->getEntryBlock(); 192 193 // Construct the function. 194 auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext()); 195 auto *RegisterFTy = llvm::FunctionType::get(VoidTy, false); 196 auto *RegisterF = llvm::Function::Create(RegisterFTy, 197 llvm::GlobalValue::InternalLinkage, 198 "__llvm_profile_register_functions", 199 &CGM.getModule()); 200 RegisterF->setUnnamedAddr(true); 201 if (CGM.getCodeGenOpts().DisableRedZone) 202 RegisterF->addFnAttr(llvm::Attribute::NoRedZone); 203 204 // Construct and return the entry block. 205 auto *BB = llvm::BasicBlock::Create(CGM.getLLVMContext(), "", RegisterF); 206 CGBuilderTy Builder(BB); 207 Builder.CreateRetVoid(); 208 return BB; 209 } 210 211 static llvm::Constant *getOrInsertRuntimeRegister(CodeGenModule &CGM) { 212 auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext()); 213 auto *VoidPtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext()); 214 auto *RuntimeRegisterTy = llvm::FunctionType::get(VoidTy, VoidPtrTy, false); 215 return CGM.getModule().getOrInsertFunction("__llvm_profile_register_function", 216 RuntimeRegisterTy); 217 } 218 219 static bool isMachO(const CodeGenModule &CGM) { 220 return CGM.getTarget().getTriple().isOSBinFormatMachO(); 221 } 222 223 static StringRef getCountersSection(const CodeGenModule &CGM) { 224 return isMachO(CGM) ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts"; 225 } 226 227 static StringRef getNameSection(const CodeGenModule &CGM) { 228 return isMachO(CGM) ? "__DATA,__llvm_prf_names" : "__llvm_prf_names"; 229 } 230 231 static StringRef getDataSection(const CodeGenModule &CGM) { 232 return isMachO(CGM) ? "__DATA,__llvm_prf_data" : "__llvm_prf_data"; 233 } 234 235 llvm::GlobalVariable *CodeGenPGO::buildDataVar() { 236 // Create name variable. 237 llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 238 auto *VarName = llvm::ConstantDataArray::getString(Ctx, getFuncName(), 239 false); 240 auto *Name = new llvm::GlobalVariable(CGM.getModule(), VarName->getType(), 241 true, VarLinkage, VarName, 242 getFuncVarName("name")); 243 Name->setSection(getNameSection(CGM)); 244 Name->setAlignment(1); 245 246 // Create data variable. 247 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx); 248 auto *Int64Ty = llvm::Type::getInt64Ty(Ctx); 249 auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx); 250 auto *Int64PtrTy = llvm::Type::getInt64PtrTy(Ctx); 251 llvm::Type *DataTypes[] = { 252 Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy 253 }; 254 auto *DataTy = llvm::StructType::get(Ctx, makeArrayRef(DataTypes)); 255 llvm::Constant *DataVals[] = { 256 llvm::ConstantInt::get(Int32Ty, getFuncName().size()), 257 llvm::ConstantInt::get(Int32Ty, NumRegionCounters), 258 llvm::ConstantInt::get(Int64Ty, FunctionHash), 259 llvm::ConstantExpr::getBitCast(Name, Int8PtrTy), 260 llvm::ConstantExpr::getBitCast(RegionCounters, Int64PtrTy) 261 }; 262 auto *Data = 263 new llvm::GlobalVariable(CGM.getModule(), DataTy, true, VarLinkage, 264 llvm::ConstantStruct::get(DataTy, DataVals), 265 getFuncVarName("data")); 266 267 // All the data should be packed into an array in its own section. 268 Data->setSection(getDataSection(CGM)); 269 Data->setAlignment(8); 270 271 // Make sure the data doesn't get deleted. 272 CGM.addUsedGlobal(Data); 273 return Data; 274 } 275 276 void CodeGenPGO::emitInstrumentationData() { 277 if (!CGM.getCodeGenOpts().ProfileInstrGenerate) 278 return; 279 280 // Build the data. 281 auto *Data = buildDataVar(); 282 283 // Register the data. 284 auto *RegisterBB = getOrInsertRegisterBB(CGM); 285 if (!RegisterBB) 286 return; 287 CGBuilderTy Builder(RegisterBB->getTerminator()); 288 auto *VoidPtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext()); 289 Builder.CreateCall(getOrInsertRuntimeRegister(CGM), 290 Builder.CreateBitCast(Data, VoidPtrTy)); 291 } 292 293 llvm::Function *CodeGenPGO::emitInitialization(CodeGenModule &CGM) { 294 if (!CGM.getCodeGenOpts().ProfileInstrGenerate) 295 return nullptr; 296 297 assert(CGM.getModule().getFunction("__llvm_profile_init") == nullptr && 298 "profile initialization already emitted"); 299 300 // Get the function to call at initialization. 301 llvm::Constant *RegisterF = getRegisterFunc(CGM); 302 if (!RegisterF) 303 return nullptr; 304 305 // Create the initialization function. 306 auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext()); 307 auto *F = llvm::Function::Create(llvm::FunctionType::get(VoidTy, false), 308 llvm::GlobalValue::InternalLinkage, 309 "__llvm_profile_init", &CGM.getModule()); 310 F->setUnnamedAddr(true); 311 F->addFnAttr(llvm::Attribute::NoInline); 312 if (CGM.getCodeGenOpts().DisableRedZone) 313 F->addFnAttr(llvm::Attribute::NoRedZone); 314 315 // Add the basic block and the necessary calls. 316 CGBuilderTy Builder(llvm::BasicBlock::Create(CGM.getLLVMContext(), "", F)); 317 Builder.CreateCall(RegisterF); 318 Builder.CreateRetVoid(); 319 320 return F; 321 } 322 323 namespace { 324 /// A RecursiveASTVisitor that fills a map of statements to PGO counters. 325 struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> { 326 /// The next counter value to assign. 327 unsigned NextCounter; 328 /// The map of statements to counters. 329 llvm::DenseMap<const Stmt *, unsigned> &CounterMap; 330 331 MapRegionCounters(llvm::DenseMap<const Stmt *, unsigned> &CounterMap) 332 : NextCounter(0), CounterMap(CounterMap) {} 333 334 // Blocks and lambdas are handled as separate functions, so we need not 335 // traverse them in the parent context. 336 bool TraverseBlockExpr(BlockExpr *BE) { return true; } 337 bool TraverseLambdaBody(LambdaExpr *LE) { return true; } 338 339 bool VisitDecl(const Decl *D) { 340 switch (D->getKind()) { 341 default: 342 break; 343 case Decl::Function: 344 case Decl::CXXMethod: 345 case Decl::CXXConstructor: 346 case Decl::CXXDestructor: 347 case Decl::CXXConversion: 348 case Decl::ObjCMethod: 349 case Decl::Block: 350 CounterMap[D->getBody()] = NextCounter++; 351 break; 352 } 353 return true; 354 } 355 356 bool VisitStmt(const Stmt *S) { 357 switch (S->getStmtClass()) { 358 default: 359 break; 360 case Stmt::LabelStmtClass: 361 case Stmt::WhileStmtClass: 362 case Stmt::DoStmtClass: 363 case Stmt::ForStmtClass: 364 case Stmt::CXXForRangeStmtClass: 365 case Stmt::ObjCForCollectionStmtClass: 366 case Stmt::SwitchStmtClass: 367 case Stmt::CaseStmtClass: 368 case Stmt::DefaultStmtClass: 369 case Stmt::IfStmtClass: 370 case Stmt::CXXTryStmtClass: 371 case Stmt::CXXCatchStmtClass: 372 case Stmt::ConditionalOperatorClass: 373 case Stmt::BinaryConditionalOperatorClass: 374 CounterMap[S] = NextCounter++; 375 break; 376 case Stmt::BinaryOperatorClass: { 377 const BinaryOperator *BO = cast<BinaryOperator>(S); 378 if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) 379 CounterMap[S] = NextCounter++; 380 break; 381 } 382 } 383 return true; 384 } 385 }; 386 387 /// A StmtVisitor that propagates the raw counts through the AST and 388 /// records the count at statements where the value may change. 389 struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> { 390 /// PGO state. 391 CodeGenPGO &PGO; 392 393 /// A flag that is set when the current count should be recorded on the 394 /// next statement, such as at the exit of a loop. 395 bool RecordNextStmtCount; 396 397 /// The map of statements to count values. 398 llvm::DenseMap<const Stmt *, uint64_t> &CountMap; 399 400 /// BreakContinueStack - Keep counts of breaks and continues inside loops. 401 struct BreakContinue { 402 uint64_t BreakCount; 403 uint64_t ContinueCount; 404 BreakContinue() : BreakCount(0), ContinueCount(0) {} 405 }; 406 SmallVector<BreakContinue, 8> BreakContinueStack; 407 408 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap, 409 CodeGenPGO &PGO) 410 : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {} 411 412 void RecordStmtCount(const Stmt *S) { 413 if (RecordNextStmtCount) { 414 CountMap[S] = PGO.getCurrentRegionCount(); 415 RecordNextStmtCount = false; 416 } 417 } 418 419 void VisitStmt(const Stmt *S) { 420 RecordStmtCount(S); 421 for (Stmt::const_child_range I = S->children(); I; ++I) { 422 if (*I) 423 this->Visit(*I); 424 } 425 } 426 427 void VisitFunctionDecl(const FunctionDecl *D) { 428 // Counter tracks entry to the function body. 429 RegionCounter Cnt(PGO, D->getBody()); 430 Cnt.beginRegion(); 431 CountMap[D->getBody()] = PGO.getCurrentRegionCount(); 432 Visit(D->getBody()); 433 } 434 435 // Skip lambda expressions. We visit these as FunctionDecls when we're 436 // generating them and aren't interested in the body when generating a 437 // parent context. 438 void VisitLambdaExpr(const LambdaExpr *LE) {} 439 440 void VisitObjCMethodDecl(const ObjCMethodDecl *D) { 441 // Counter tracks entry to the method body. 442 RegionCounter Cnt(PGO, D->getBody()); 443 Cnt.beginRegion(); 444 CountMap[D->getBody()] = PGO.getCurrentRegionCount(); 445 Visit(D->getBody()); 446 } 447 448 void VisitBlockDecl(const BlockDecl *D) { 449 // Counter tracks entry to the block body. 450 RegionCounter Cnt(PGO, D->getBody()); 451 Cnt.beginRegion(); 452 CountMap[D->getBody()] = PGO.getCurrentRegionCount(); 453 Visit(D->getBody()); 454 } 455 456 void VisitReturnStmt(const ReturnStmt *S) { 457 RecordStmtCount(S); 458 if (S->getRetValue()) 459 Visit(S->getRetValue()); 460 PGO.setCurrentRegionUnreachable(); 461 RecordNextStmtCount = true; 462 } 463 464 void VisitGotoStmt(const GotoStmt *S) { 465 RecordStmtCount(S); 466 PGO.setCurrentRegionUnreachable(); 467 RecordNextStmtCount = true; 468 } 469 470 void VisitLabelStmt(const LabelStmt *S) { 471 RecordNextStmtCount = false; 472 // Counter tracks the block following the label. 473 RegionCounter Cnt(PGO, S); 474 Cnt.beginRegion(); 475 CountMap[S] = PGO.getCurrentRegionCount(); 476 Visit(S->getSubStmt()); 477 } 478 479 void VisitBreakStmt(const BreakStmt *S) { 480 RecordStmtCount(S); 481 assert(!BreakContinueStack.empty() && "break not in a loop or switch!"); 482 BreakContinueStack.back().BreakCount += PGO.getCurrentRegionCount(); 483 PGO.setCurrentRegionUnreachable(); 484 RecordNextStmtCount = true; 485 } 486 487 void VisitContinueStmt(const ContinueStmt *S) { 488 RecordStmtCount(S); 489 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 490 BreakContinueStack.back().ContinueCount += PGO.getCurrentRegionCount(); 491 PGO.setCurrentRegionUnreachable(); 492 RecordNextStmtCount = true; 493 } 494 495 void VisitWhileStmt(const WhileStmt *S) { 496 RecordStmtCount(S); 497 // Counter tracks the body of the loop. 498 RegionCounter Cnt(PGO, S); 499 BreakContinueStack.push_back(BreakContinue()); 500 // Visit the body region first so the break/continue adjustments can be 501 // included when visiting the condition. 502 Cnt.beginRegion(); 503 CountMap[S->getBody()] = PGO.getCurrentRegionCount(); 504 Visit(S->getBody()); 505 Cnt.adjustForControlFlow(); 506 507 // ...then go back and propagate counts through the condition. The count 508 // at the start of the condition is the sum of the incoming edges, 509 // the backedge from the end of the loop body, and the edges from 510 // continue statements. 511 BreakContinue BC = BreakContinueStack.pop_back_val(); 512 Cnt.setCurrentRegionCount(Cnt.getParentCount() + 513 Cnt.getAdjustedCount() + BC.ContinueCount); 514 CountMap[S->getCond()] = PGO.getCurrentRegionCount(); 515 Visit(S->getCond()); 516 Cnt.adjustForControlFlow(); 517 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount); 518 RecordNextStmtCount = true; 519 } 520 521 void VisitDoStmt(const DoStmt *S) { 522 RecordStmtCount(S); 523 // Counter tracks the body of the loop. 524 RegionCounter Cnt(PGO, S); 525 BreakContinueStack.push_back(BreakContinue()); 526 Cnt.beginRegion(/*AddIncomingFallThrough=*/true); 527 CountMap[S->getBody()] = PGO.getCurrentRegionCount(); 528 Visit(S->getBody()); 529 Cnt.adjustForControlFlow(); 530 531 BreakContinue BC = BreakContinueStack.pop_back_val(); 532 // The count at the start of the condition is equal to the count at the 533 // end of the body. The adjusted count does not include either the 534 // fall-through count coming into the loop or the continue count, so add 535 // both of those separately. This is coincidentally the same equation as 536 // with while loops but for different reasons. 537 Cnt.setCurrentRegionCount(Cnt.getParentCount() + 538 Cnt.getAdjustedCount() + BC.ContinueCount); 539 CountMap[S->getCond()] = PGO.getCurrentRegionCount(); 540 Visit(S->getCond()); 541 Cnt.adjustForControlFlow(); 542 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount); 543 RecordNextStmtCount = true; 544 } 545 546 void VisitForStmt(const ForStmt *S) { 547 RecordStmtCount(S); 548 if (S->getInit()) 549 Visit(S->getInit()); 550 // Counter tracks the body of the loop. 551 RegionCounter Cnt(PGO, S); 552 BreakContinueStack.push_back(BreakContinue()); 553 // Visit the body region first. (This is basically the same as a while 554 // loop; see further comments in VisitWhileStmt.) 555 Cnt.beginRegion(); 556 CountMap[S->getBody()] = PGO.getCurrentRegionCount(); 557 Visit(S->getBody()); 558 Cnt.adjustForControlFlow(); 559 560 // The increment is essentially part of the body but it needs to include 561 // the count for all the continue statements. 562 if (S->getInc()) { 563 Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() + 564 BreakContinueStack.back().ContinueCount); 565 CountMap[S->getInc()] = PGO.getCurrentRegionCount(); 566 Visit(S->getInc()); 567 Cnt.adjustForControlFlow(); 568 } 569 570 BreakContinue BC = BreakContinueStack.pop_back_val(); 571 572 // ...then go back and propagate counts through the condition. 573 if (S->getCond()) { 574 Cnt.setCurrentRegionCount(Cnt.getParentCount() + 575 Cnt.getAdjustedCount() + 576 BC.ContinueCount); 577 CountMap[S->getCond()] = PGO.getCurrentRegionCount(); 578 Visit(S->getCond()); 579 Cnt.adjustForControlFlow(); 580 } 581 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount); 582 RecordNextStmtCount = true; 583 } 584 585 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 586 RecordStmtCount(S); 587 Visit(S->getRangeStmt()); 588 Visit(S->getBeginEndStmt()); 589 // Counter tracks the body of the loop. 590 RegionCounter Cnt(PGO, S); 591 BreakContinueStack.push_back(BreakContinue()); 592 // Visit the body region first. (This is basically the same as a while 593 // loop; see further comments in VisitWhileStmt.) 594 Cnt.beginRegion(); 595 CountMap[S->getLoopVarStmt()] = PGO.getCurrentRegionCount(); 596 Visit(S->getLoopVarStmt()); 597 Visit(S->getBody()); 598 Cnt.adjustForControlFlow(); 599 600 // The increment is essentially part of the body but it needs to include 601 // the count for all the continue statements. 602 Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() + 603 BreakContinueStack.back().ContinueCount); 604 CountMap[S->getInc()] = PGO.getCurrentRegionCount(); 605 Visit(S->getInc()); 606 Cnt.adjustForControlFlow(); 607 608 BreakContinue BC = BreakContinueStack.pop_back_val(); 609 610 // ...then go back and propagate counts through the condition. 611 Cnt.setCurrentRegionCount(Cnt.getParentCount() + 612 Cnt.getAdjustedCount() + 613 BC.ContinueCount); 614 CountMap[S->getCond()] = PGO.getCurrentRegionCount(); 615 Visit(S->getCond()); 616 Cnt.adjustForControlFlow(); 617 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount); 618 RecordNextStmtCount = true; 619 } 620 621 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { 622 RecordStmtCount(S); 623 Visit(S->getElement()); 624 // Counter tracks the body of the loop. 625 RegionCounter Cnt(PGO, S); 626 BreakContinueStack.push_back(BreakContinue()); 627 Cnt.beginRegion(); 628 CountMap[S->getBody()] = PGO.getCurrentRegionCount(); 629 Visit(S->getBody()); 630 BreakContinue BC = BreakContinueStack.pop_back_val(); 631 Cnt.adjustForControlFlow(); 632 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount); 633 RecordNextStmtCount = true; 634 } 635 636 void VisitSwitchStmt(const SwitchStmt *S) { 637 RecordStmtCount(S); 638 Visit(S->getCond()); 639 PGO.setCurrentRegionUnreachable(); 640 BreakContinueStack.push_back(BreakContinue()); 641 Visit(S->getBody()); 642 // If the switch is inside a loop, add the continue counts. 643 BreakContinue BC = BreakContinueStack.pop_back_val(); 644 if (!BreakContinueStack.empty()) 645 BreakContinueStack.back().ContinueCount += BC.ContinueCount; 646 // Counter tracks the exit block of the switch. 647 RegionCounter ExitCnt(PGO, S); 648 ExitCnt.beginRegion(); 649 RecordNextStmtCount = true; 650 } 651 652 void VisitCaseStmt(const CaseStmt *S) { 653 RecordNextStmtCount = false; 654 // Counter for this particular case. This counts only jumps from the 655 // switch header and does not include fallthrough from the case before 656 // this one. 657 RegionCounter Cnt(PGO, S); 658 Cnt.beginRegion(/*AddIncomingFallThrough=*/true); 659 CountMap[S] = Cnt.getCount(); 660 RecordNextStmtCount = true; 661 Visit(S->getSubStmt()); 662 } 663 664 void VisitDefaultStmt(const DefaultStmt *S) { 665 RecordNextStmtCount = false; 666 // Counter for this default case. This does not include fallthrough from 667 // the previous case. 668 RegionCounter Cnt(PGO, S); 669 Cnt.beginRegion(/*AddIncomingFallThrough=*/true); 670 CountMap[S] = Cnt.getCount(); 671 RecordNextStmtCount = true; 672 Visit(S->getSubStmt()); 673 } 674 675 void VisitIfStmt(const IfStmt *S) { 676 RecordStmtCount(S); 677 // Counter tracks the "then" part of an if statement. The count for 678 // the "else" part, if it exists, will be calculated from this counter. 679 RegionCounter Cnt(PGO, S); 680 Visit(S->getCond()); 681 682 Cnt.beginRegion(); 683 CountMap[S->getThen()] = PGO.getCurrentRegionCount(); 684 Visit(S->getThen()); 685 Cnt.adjustForControlFlow(); 686 687 if (S->getElse()) { 688 Cnt.beginElseRegion(); 689 CountMap[S->getElse()] = PGO.getCurrentRegionCount(); 690 Visit(S->getElse()); 691 Cnt.adjustForControlFlow(); 692 } 693 Cnt.applyAdjustmentsToRegion(0); 694 RecordNextStmtCount = true; 695 } 696 697 void VisitCXXTryStmt(const CXXTryStmt *S) { 698 RecordStmtCount(S); 699 Visit(S->getTryBlock()); 700 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) 701 Visit(S->getHandler(I)); 702 // Counter tracks the continuation block of the try statement. 703 RegionCounter Cnt(PGO, S); 704 Cnt.beginRegion(); 705 RecordNextStmtCount = true; 706 } 707 708 void VisitCXXCatchStmt(const CXXCatchStmt *S) { 709 RecordNextStmtCount = false; 710 // Counter tracks the catch statement's handler block. 711 RegionCounter Cnt(PGO, S); 712 Cnt.beginRegion(); 713 CountMap[S] = PGO.getCurrentRegionCount(); 714 Visit(S->getHandlerBlock()); 715 } 716 717 void VisitAbstractConditionalOperator( 718 const AbstractConditionalOperator *E) { 719 RecordStmtCount(E); 720 // Counter tracks the "true" part of a conditional operator. The 721 // count in the "false" part will be calculated from this counter. 722 RegionCounter Cnt(PGO, E); 723 Visit(E->getCond()); 724 725 Cnt.beginRegion(); 726 CountMap[E->getTrueExpr()] = PGO.getCurrentRegionCount(); 727 Visit(E->getTrueExpr()); 728 Cnt.adjustForControlFlow(); 729 730 Cnt.beginElseRegion(); 731 CountMap[E->getFalseExpr()] = PGO.getCurrentRegionCount(); 732 Visit(E->getFalseExpr()); 733 Cnt.adjustForControlFlow(); 734 735 Cnt.applyAdjustmentsToRegion(0); 736 RecordNextStmtCount = true; 737 } 738 739 void VisitBinLAnd(const BinaryOperator *E) { 740 RecordStmtCount(E); 741 // Counter tracks the right hand side of a logical and operator. 742 RegionCounter Cnt(PGO, E); 743 Visit(E->getLHS()); 744 Cnt.beginRegion(); 745 CountMap[E->getRHS()] = PGO.getCurrentRegionCount(); 746 Visit(E->getRHS()); 747 Cnt.adjustForControlFlow(); 748 Cnt.applyAdjustmentsToRegion(0); 749 RecordNextStmtCount = true; 750 } 751 752 void VisitBinLOr(const BinaryOperator *E) { 753 RecordStmtCount(E); 754 // Counter tracks the right hand side of a logical or operator. 755 RegionCounter Cnt(PGO, E); 756 Visit(E->getLHS()); 757 Cnt.beginRegion(); 758 CountMap[E->getRHS()] = PGO.getCurrentRegionCount(); 759 Visit(E->getRHS()); 760 Cnt.adjustForControlFlow(); 761 Cnt.applyAdjustmentsToRegion(0); 762 RecordNextStmtCount = true; 763 } 764 }; 765 } 766 767 static void emitRuntimeHook(CodeGenModule &CGM) { 768 const char *const RuntimeVarName = "__llvm_profile_runtime"; 769 const char *const RuntimeUserName = "__llvm_profile_runtime_user"; 770 if (CGM.getModule().getGlobalVariable(RuntimeVarName)) 771 return; 772 773 // Declare the runtime hook. 774 llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 775 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx); 776 auto *Var = new llvm::GlobalVariable(CGM.getModule(), Int32Ty, false, 777 llvm::GlobalValue::ExternalLinkage, 778 nullptr, RuntimeVarName); 779 780 // Make a function that uses it. 781 auto *User = llvm::Function::Create(llvm::FunctionType::get(Int32Ty, false), 782 llvm::GlobalValue::LinkOnceODRLinkage, 783 RuntimeUserName, &CGM.getModule()); 784 User->addFnAttr(llvm::Attribute::NoInline); 785 if (CGM.getCodeGenOpts().DisableRedZone) 786 User->addFnAttr(llvm::Attribute::NoRedZone); 787 CGBuilderTy Builder(llvm::BasicBlock::Create(CGM.getLLVMContext(), "", User)); 788 auto *Load = Builder.CreateLoad(Var); 789 Builder.CreateRet(Load); 790 791 // Create a use of the function. Now the definition of the runtime variable 792 // should get pulled in, along with any static initializears. 793 CGM.addUsedGlobal(User); 794 } 795 796 void CodeGenPGO::assignRegionCounters(const Decl *D, llvm::Function *Fn) { 797 bool InstrumentRegions = CGM.getCodeGenOpts().ProfileInstrGenerate; 798 PGOProfileData *PGOData = CGM.getPGOData(); 799 if (!InstrumentRegions && !PGOData) 800 return; 801 if (!D) 802 return; 803 setFuncName(Fn); 804 805 // Set the linkage for variables based on the function linkage. Usually, we 806 // want to match it, but available_externally and extern_weak both have the 807 // wrong semantics. 808 VarLinkage = Fn->getLinkage(); 809 switch (VarLinkage) { 810 case llvm::GlobalValue::ExternalWeakLinkage: 811 VarLinkage = llvm::GlobalValue::LinkOnceAnyLinkage; 812 break; 813 case llvm::GlobalValue::AvailableExternallyLinkage: 814 VarLinkage = llvm::GlobalValue::LinkOnceODRLinkage; 815 break; 816 default: 817 break; 818 } 819 820 mapRegionCounters(D); 821 if (InstrumentRegions) { 822 emitRuntimeHook(CGM); 823 emitCounterVariables(); 824 } 825 if (PGOData) { 826 loadRegionCounts(PGOData); 827 computeRegionCounts(D); 828 applyFunctionAttributes(PGOData, Fn); 829 } 830 } 831 832 void CodeGenPGO::mapRegionCounters(const Decl *D) { 833 RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>); 834 MapRegionCounters Walker(*RegionCounterMap); 835 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 836 Walker.TraverseDecl(const_cast<FunctionDecl *>(FD)); 837 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) 838 Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD)); 839 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D)) 840 Walker.TraverseDecl(const_cast<BlockDecl *>(BD)); 841 NumRegionCounters = Walker.NextCounter; 842 // FIXME: The number of counters isn't sufficient for the hash 843 FunctionHash = NumRegionCounters; 844 } 845 846 void CodeGenPGO::computeRegionCounts(const Decl *D) { 847 StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>); 848 ComputeRegionCounts Walker(*StmtCountMap, *this); 849 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 850 Walker.VisitFunctionDecl(FD); 851 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) 852 Walker.VisitObjCMethodDecl(MD); 853 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D)) 854 Walker.VisitBlockDecl(BD); 855 } 856 857 void CodeGenPGO::applyFunctionAttributes(PGOProfileData *PGOData, 858 llvm::Function *Fn) { 859 if (!haveRegionCounts()) 860 return; 861 862 uint64_t MaxFunctionCount = PGOData->getMaximumFunctionCount(); 863 uint64_t FunctionCount = getRegionCount(0); 864 if (FunctionCount >= (uint64_t)(0.3 * (double)MaxFunctionCount)) 865 // Turn on InlineHint attribute for hot functions. 866 // FIXME: 30% is from preliminary tuning on SPEC, it may not be optimal. 867 Fn->addFnAttr(llvm::Attribute::InlineHint); 868 else if (FunctionCount <= (uint64_t)(0.01 * (double)MaxFunctionCount)) 869 // Turn on Cold attribute for cold functions. 870 // FIXME: 1% is from preliminary tuning on SPEC, it may not be optimal. 871 Fn->addFnAttr(llvm::Attribute::Cold); 872 } 873 874 void CodeGenPGO::emitCounterVariables() { 875 llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 876 llvm::ArrayType *CounterTy = llvm::ArrayType::get(llvm::Type::getInt64Ty(Ctx), 877 NumRegionCounters); 878 RegionCounters = 879 new llvm::GlobalVariable(CGM.getModule(), CounterTy, false, VarLinkage, 880 llvm::Constant::getNullValue(CounterTy), 881 getFuncVarName("counters")); 882 RegionCounters->setAlignment(8); 883 RegionCounters->setSection(getCountersSection(CGM)); 884 } 885 886 void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, unsigned Counter) { 887 if (!RegionCounters) 888 return; 889 llvm::Value *Addr = 890 Builder.CreateConstInBoundsGEP2_64(RegionCounters, 0, Counter); 891 llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount"); 892 Count = Builder.CreateAdd(Count, Builder.getInt64(1)); 893 Builder.CreateStore(Count, Addr); 894 } 895 896 void CodeGenPGO::loadRegionCounts(PGOProfileData *PGOData) { 897 // For now, ignore the counts from the PGO data file only if the number of 898 // counters does not match. This could be tightened down in the future to 899 // ignore counts when the input changes in various ways, e.g., by comparing a 900 // hash value based on some characteristics of the input. 901 RegionCounts.reset(new std::vector<uint64_t>); 902 uint64_t Hash; 903 if (PGOData->getFunctionCounts(getFuncName(), Hash, *RegionCounts) || 904 Hash != FunctionHash || RegionCounts->size() != NumRegionCounters) 905 RegionCounts.reset(); 906 } 907 908 void CodeGenPGO::destroyRegionCounters() { 909 RegionCounterMap.reset(); 910 StmtCountMap.reset(); 911 RegionCounts.reset(); 912 } 913 914 /// \brief Calculate what to divide by to scale weights. 915 /// 916 /// Given the maximum weight, calculate a divisor that will scale all the 917 /// weights to strictly less than UINT32_MAX. 918 static uint64_t calculateWeightScale(uint64_t MaxWeight) { 919 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1; 920 } 921 922 /// \brief Scale an individual branch weight (and add 1). 923 /// 924 /// Scale a 64-bit weight down to 32-bits using \c Scale. 925 /// 926 /// According to Laplace's Rule of Succession, it is better to compute the 927 /// weight based on the count plus 1, so universally add 1 to the value. 928 /// 929 /// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no 930 /// greater than \c Weight. 931 static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) { 932 assert(Scale && "scale by 0?"); 933 uint64_t Scaled = Weight / Scale + 1; 934 assert(Scaled <= UINT32_MAX && "overflow 32-bits"); 935 return Scaled; 936 } 937 938 llvm::MDNode *CodeGenPGO::createBranchWeights(uint64_t TrueCount, 939 uint64_t FalseCount) { 940 // Check for empty weights. 941 if (!TrueCount && !FalseCount) 942 return nullptr; 943 944 // Calculate how to scale down to 32-bits. 945 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount)); 946 947 llvm::MDBuilder MDHelper(CGM.getLLVMContext()); 948 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale), 949 scaleBranchWeight(FalseCount, Scale)); 950 } 951 952 llvm::MDNode *CodeGenPGO::createBranchWeights(ArrayRef<uint64_t> Weights) { 953 // We need at least two elements to create meaningful weights. 954 if (Weights.size() < 2) 955 return nullptr; 956 957 // Check for empty weights. 958 uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end()); 959 if (MaxWeight == 0) 960 return nullptr; 961 962 // Calculate how to scale down to 32-bits. 963 uint64_t Scale = calculateWeightScale(MaxWeight); 964 965 SmallVector<uint32_t, 16> ScaledWeights; 966 ScaledWeights.reserve(Weights.size()); 967 for (uint64_t W : Weights) 968 ScaledWeights.push_back(scaleBranchWeight(W, Scale)); 969 970 llvm::MDBuilder MDHelper(CGM.getLLVMContext()); 971 return MDHelper.createBranchWeights(ScaledWeights); 972 } 973 974 llvm::MDNode *CodeGenPGO::createLoopWeights(const Stmt *Cond, 975 RegionCounter &Cnt) { 976 if (!haveRegionCounts()) 977 return nullptr; 978 uint64_t LoopCount = Cnt.getCount(); 979 uint64_t CondCount = 0; 980 bool Found = getStmtCount(Cond, CondCount); 981 assert(Found && "missing expected loop condition count"); 982 (void)Found; 983 if (CondCount == 0) 984 return nullptr; 985 return createBranchWeights(LoopCount, 986 std::max(CondCount, LoopCount) - LoopCount); 987 } 988