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()/strtoll() 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 = strtol(++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 = strtoll(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 = strtoll(++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 = strtol(++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 = strtoll(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 = 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 = 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 // Only need to create this once per module. 298 if (CGM.getModule().getFunction("__llvm_profile_init")) 299 return nullptr; 300 301 // Get the function to call at initialization. 302 llvm::Constant *RegisterF = getRegisterFunc(CGM); 303 if (!RegisterF) 304 return nullptr; 305 306 // Create the initialization function. 307 auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext()); 308 auto *F = llvm::Function::Create(llvm::FunctionType::get(VoidTy, false), 309 llvm::GlobalValue::InternalLinkage, 310 "__llvm_profile_init", &CGM.getModule()); 311 F->setUnnamedAddr(true); 312 F->addFnAttr(llvm::Attribute::NoInline); 313 if (CGM.getCodeGenOpts().DisableRedZone) 314 F->addFnAttr(llvm::Attribute::NoRedZone); 315 316 // Add the basic block and the necessary calls. 317 CGBuilderTy Builder(llvm::BasicBlock::Create(CGM.getLLVMContext(), "", F)); 318 Builder.CreateCall(RegisterF); 319 Builder.CreateRetVoid(); 320 321 return F; 322 } 323 324 namespace { 325 /// A StmtVisitor that fills a map of statements to PGO counters. 326 struct MapRegionCounters : public ConstStmtVisitor<MapRegionCounters> { 327 /// The next counter value to assign. 328 unsigned NextCounter; 329 /// The map of statements to counters. 330 llvm::DenseMap<const Stmt*, unsigned> *CounterMap; 331 332 MapRegionCounters(llvm::DenseMap<const Stmt*, unsigned> *CounterMap) : 333 NextCounter(0), CounterMap(CounterMap) { 334 } 335 336 void VisitChildren(const Stmt *S) { 337 for (Stmt::const_child_range I = S->children(); I; ++I) 338 if (*I) 339 this->Visit(*I); 340 } 341 void VisitStmt(const Stmt *S) { VisitChildren(S); } 342 343 /// Assign a counter to track entry to the function body. 344 void VisitFunctionDecl(const FunctionDecl *S) { 345 (*CounterMap)[S->getBody()] = NextCounter++; 346 Visit(S->getBody()); 347 } 348 void VisitObjCMethodDecl(const ObjCMethodDecl *S) { 349 (*CounterMap)[S->getBody()] = NextCounter++; 350 Visit(S->getBody()); 351 } 352 void VisitBlockDecl(const BlockDecl *S) { 353 (*CounterMap)[S->getBody()] = NextCounter++; 354 Visit(S->getBody()); 355 } 356 /// Assign a counter to track the block following a label. 357 void VisitLabelStmt(const LabelStmt *S) { 358 (*CounterMap)[S] = NextCounter++; 359 Visit(S->getSubStmt()); 360 } 361 /// Assign a counter for the body of a while loop. 362 void VisitWhileStmt(const WhileStmt *S) { 363 (*CounterMap)[S] = NextCounter++; 364 Visit(S->getCond()); 365 Visit(S->getBody()); 366 } 367 /// Assign a counter for the body of a do-while loop. 368 void VisitDoStmt(const DoStmt *S) { 369 (*CounterMap)[S] = NextCounter++; 370 Visit(S->getBody()); 371 Visit(S->getCond()); 372 } 373 /// Assign a counter for the body of a for loop. 374 void VisitForStmt(const ForStmt *S) { 375 (*CounterMap)[S] = NextCounter++; 376 if (S->getInit()) 377 Visit(S->getInit()); 378 const Expr *E; 379 if ((E = S->getCond())) 380 Visit(E); 381 if ((E = S->getInc())) 382 Visit(E); 383 Visit(S->getBody()); 384 } 385 /// Assign a counter for the body of a for-range loop. 386 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 387 (*CounterMap)[S] = NextCounter++; 388 Visit(S->getRangeStmt()); 389 Visit(S->getBeginEndStmt()); 390 Visit(S->getCond()); 391 Visit(S->getLoopVarStmt()); 392 Visit(S->getBody()); 393 Visit(S->getInc()); 394 } 395 /// Assign a counter for the body of a for-collection loop. 396 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { 397 (*CounterMap)[S] = NextCounter++; 398 Visit(S->getElement()); 399 Visit(S->getBody()); 400 } 401 /// Assign a counter for the exit block of the switch statement. 402 void VisitSwitchStmt(const SwitchStmt *S) { 403 (*CounterMap)[S] = NextCounter++; 404 Visit(S->getCond()); 405 Visit(S->getBody()); 406 } 407 /// Assign a counter for a particular case in a switch. This counts jumps 408 /// from the switch header as well as fallthrough from the case before this 409 /// one. 410 void VisitCaseStmt(const CaseStmt *S) { 411 (*CounterMap)[S] = NextCounter++; 412 Visit(S->getSubStmt()); 413 } 414 /// Assign a counter for the default case of a switch statement. The count 415 /// is the number of branches from the loop header to the default, and does 416 /// not include fallthrough from previous cases. If we have multiple 417 /// conditional branch blocks from the switch instruction to the default 418 /// block, as with large GNU case ranges, this is the counter for the last 419 /// edge in that series, rather than the first. 420 void VisitDefaultStmt(const DefaultStmt *S) { 421 (*CounterMap)[S] = NextCounter++; 422 Visit(S->getSubStmt()); 423 } 424 /// Assign a counter for the "then" part of an if statement. The count for 425 /// the "else" part, if it exists, will be calculated from this counter. 426 void VisitIfStmt(const IfStmt *S) { 427 (*CounterMap)[S] = NextCounter++; 428 Visit(S->getCond()); 429 Visit(S->getThen()); 430 if (S->getElse()) 431 Visit(S->getElse()); 432 } 433 /// Assign a counter for the continuation block of a C++ try statement. 434 void VisitCXXTryStmt(const CXXTryStmt *S) { 435 (*CounterMap)[S] = NextCounter++; 436 Visit(S->getTryBlock()); 437 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) 438 Visit(S->getHandler(I)); 439 } 440 /// Assign a counter for a catch statement's handler block. 441 void VisitCXXCatchStmt(const CXXCatchStmt *S) { 442 (*CounterMap)[S] = NextCounter++; 443 Visit(S->getHandlerBlock()); 444 } 445 /// Assign a counter for the "true" part of a conditional operator. The 446 /// count in the "false" part will be calculated from this counter. 447 void VisitConditionalOperator(const ConditionalOperator *E) { 448 (*CounterMap)[E] = NextCounter++; 449 Visit(E->getCond()); 450 Visit(E->getTrueExpr()); 451 Visit(E->getFalseExpr()); 452 } 453 /// Assign a counter for the right hand side of a logical and operator. 454 void VisitBinLAnd(const BinaryOperator *E) { 455 (*CounterMap)[E] = NextCounter++; 456 Visit(E->getLHS()); 457 Visit(E->getRHS()); 458 } 459 /// Assign a counter for the right hand side of a logical or operator. 460 void VisitBinLOr(const BinaryOperator *E) { 461 (*CounterMap)[E] = NextCounter++; 462 Visit(E->getLHS()); 463 Visit(E->getRHS()); 464 } 465 }; 466 467 /// A StmtVisitor that propagates the raw counts through the AST and 468 /// records the count at statements where the value may change. 469 struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> { 470 /// PGO state. 471 CodeGenPGO &PGO; 472 473 /// A flag that is set when the current count should be recorded on the 474 /// next statement, such as at the exit of a loop. 475 bool RecordNextStmtCount; 476 477 /// The map of statements to count values. 478 llvm::DenseMap<const Stmt*, uint64_t> *CountMap; 479 480 /// BreakContinueStack - Keep counts of breaks and continues inside loops. 481 struct BreakContinue { 482 uint64_t BreakCount; 483 uint64_t ContinueCount; 484 BreakContinue() : BreakCount(0), ContinueCount(0) {} 485 }; 486 SmallVector<BreakContinue, 8> BreakContinueStack; 487 488 ComputeRegionCounts(llvm::DenseMap<const Stmt*, uint64_t> *CountMap, 489 CodeGenPGO &PGO) : 490 PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) { 491 } 492 493 void RecordStmtCount(const Stmt *S) { 494 if (RecordNextStmtCount) { 495 (*CountMap)[S] = PGO.getCurrentRegionCount(); 496 RecordNextStmtCount = false; 497 } 498 } 499 500 void VisitStmt(const Stmt *S) { 501 RecordStmtCount(S); 502 for (Stmt::const_child_range I = S->children(); I; ++I) { 503 if (*I) 504 this->Visit(*I); 505 } 506 } 507 508 void VisitFunctionDecl(const FunctionDecl *S) { 509 RegionCounter Cnt(PGO, S->getBody()); 510 Cnt.beginRegion(); 511 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount(); 512 Visit(S->getBody()); 513 } 514 515 void VisitObjCMethodDecl(const ObjCMethodDecl *S) { 516 RegionCounter Cnt(PGO, S->getBody()); 517 Cnt.beginRegion(); 518 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount(); 519 Visit(S->getBody()); 520 } 521 522 void VisitBlockDecl(const BlockDecl *S) { 523 RegionCounter Cnt(PGO, S->getBody()); 524 Cnt.beginRegion(); 525 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount(); 526 Visit(S->getBody()); 527 } 528 529 void VisitReturnStmt(const ReturnStmt *S) { 530 RecordStmtCount(S); 531 if (S->getRetValue()) 532 Visit(S->getRetValue()); 533 PGO.setCurrentRegionUnreachable(); 534 RecordNextStmtCount = true; 535 } 536 537 void VisitGotoStmt(const GotoStmt *S) { 538 RecordStmtCount(S); 539 PGO.setCurrentRegionUnreachable(); 540 RecordNextStmtCount = true; 541 } 542 543 void VisitLabelStmt(const LabelStmt *S) { 544 RecordNextStmtCount = false; 545 RegionCounter Cnt(PGO, S); 546 Cnt.beginRegion(); 547 (*CountMap)[S] = PGO.getCurrentRegionCount(); 548 Visit(S->getSubStmt()); 549 } 550 551 void VisitBreakStmt(const BreakStmt *S) { 552 RecordStmtCount(S); 553 assert(!BreakContinueStack.empty() && "break not in a loop or switch!"); 554 BreakContinueStack.back().BreakCount += PGO.getCurrentRegionCount(); 555 PGO.setCurrentRegionUnreachable(); 556 RecordNextStmtCount = true; 557 } 558 559 void VisitContinueStmt(const ContinueStmt *S) { 560 RecordStmtCount(S); 561 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 562 BreakContinueStack.back().ContinueCount += PGO.getCurrentRegionCount(); 563 PGO.setCurrentRegionUnreachable(); 564 RecordNextStmtCount = true; 565 } 566 567 void VisitWhileStmt(const WhileStmt *S) { 568 RecordStmtCount(S); 569 RegionCounter Cnt(PGO, S); 570 BreakContinueStack.push_back(BreakContinue()); 571 // Visit the body region first so the break/continue adjustments can be 572 // included when visiting the condition. 573 Cnt.beginRegion(); 574 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount(); 575 Visit(S->getBody()); 576 Cnt.adjustForControlFlow(); 577 578 // ...then go back and propagate counts through the condition. The count 579 // at the start of the condition is the sum of the incoming edges, 580 // the backedge from the end of the loop body, and the edges from 581 // continue statements. 582 BreakContinue BC = BreakContinueStack.pop_back_val(); 583 Cnt.setCurrentRegionCount(Cnt.getParentCount() + 584 Cnt.getAdjustedCount() + BC.ContinueCount); 585 (*CountMap)[S->getCond()] = PGO.getCurrentRegionCount(); 586 Visit(S->getCond()); 587 Cnt.adjustForControlFlow(); 588 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount); 589 RecordNextStmtCount = true; 590 } 591 592 void VisitDoStmt(const DoStmt *S) { 593 RecordStmtCount(S); 594 RegionCounter Cnt(PGO, S); 595 BreakContinueStack.push_back(BreakContinue()); 596 Cnt.beginRegion(/*AddIncomingFallThrough=*/true); 597 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount(); 598 Visit(S->getBody()); 599 Cnt.adjustForControlFlow(); 600 601 BreakContinue BC = BreakContinueStack.pop_back_val(); 602 // The count at the start of the condition is equal to the count at the 603 // end of the body. The adjusted count does not include either the 604 // fall-through count coming into the loop or the continue count, so add 605 // both of those separately. This is coincidentally the same equation as 606 // with while loops but for different reasons. 607 Cnt.setCurrentRegionCount(Cnt.getParentCount() + 608 Cnt.getAdjustedCount() + BC.ContinueCount); 609 (*CountMap)[S->getCond()] = PGO.getCurrentRegionCount(); 610 Visit(S->getCond()); 611 Cnt.adjustForControlFlow(); 612 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount); 613 RecordNextStmtCount = true; 614 } 615 616 void VisitForStmt(const ForStmt *S) { 617 RecordStmtCount(S); 618 if (S->getInit()) 619 Visit(S->getInit()); 620 RegionCounter Cnt(PGO, S); 621 BreakContinueStack.push_back(BreakContinue()); 622 // Visit the body region first. (This is basically the same as a while 623 // loop; see further comments in VisitWhileStmt.) 624 Cnt.beginRegion(); 625 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount(); 626 Visit(S->getBody()); 627 Cnt.adjustForControlFlow(); 628 629 // The increment is essentially part of the body but it needs to include 630 // the count for all the continue statements. 631 if (S->getInc()) { 632 Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() + 633 BreakContinueStack.back().ContinueCount); 634 (*CountMap)[S->getInc()] = PGO.getCurrentRegionCount(); 635 Visit(S->getInc()); 636 Cnt.adjustForControlFlow(); 637 } 638 639 BreakContinue BC = BreakContinueStack.pop_back_val(); 640 641 // ...then go back and propagate counts through the condition. 642 if (S->getCond()) { 643 Cnt.setCurrentRegionCount(Cnt.getParentCount() + 644 Cnt.getAdjustedCount() + 645 BC.ContinueCount); 646 (*CountMap)[S->getCond()] = PGO.getCurrentRegionCount(); 647 Visit(S->getCond()); 648 Cnt.adjustForControlFlow(); 649 } 650 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount); 651 RecordNextStmtCount = true; 652 } 653 654 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 655 RecordStmtCount(S); 656 Visit(S->getRangeStmt()); 657 Visit(S->getBeginEndStmt()); 658 RegionCounter Cnt(PGO, S); 659 BreakContinueStack.push_back(BreakContinue()); 660 // Visit the body region first. (This is basically the same as a while 661 // loop; see further comments in VisitWhileStmt.) 662 Cnt.beginRegion(); 663 (*CountMap)[S->getLoopVarStmt()] = PGO.getCurrentRegionCount(); 664 Visit(S->getLoopVarStmt()); 665 Visit(S->getBody()); 666 Cnt.adjustForControlFlow(); 667 668 // The increment is essentially part of the body but it needs to include 669 // the count for all the continue statements. 670 Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() + 671 BreakContinueStack.back().ContinueCount); 672 (*CountMap)[S->getInc()] = PGO.getCurrentRegionCount(); 673 Visit(S->getInc()); 674 Cnt.adjustForControlFlow(); 675 676 BreakContinue BC = BreakContinueStack.pop_back_val(); 677 678 // ...then go back and propagate counts through the condition. 679 Cnt.setCurrentRegionCount(Cnt.getParentCount() + 680 Cnt.getAdjustedCount() + 681 BC.ContinueCount); 682 (*CountMap)[S->getCond()] = PGO.getCurrentRegionCount(); 683 Visit(S->getCond()); 684 Cnt.adjustForControlFlow(); 685 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount); 686 RecordNextStmtCount = true; 687 } 688 689 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { 690 RecordStmtCount(S); 691 Visit(S->getElement()); 692 RegionCounter Cnt(PGO, S); 693 BreakContinueStack.push_back(BreakContinue()); 694 Cnt.beginRegion(); 695 (*CountMap)[S->getBody()] = PGO.getCurrentRegionCount(); 696 Visit(S->getBody()); 697 BreakContinue BC = BreakContinueStack.pop_back_val(); 698 Cnt.adjustForControlFlow(); 699 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount); 700 RecordNextStmtCount = true; 701 } 702 703 void VisitSwitchStmt(const SwitchStmt *S) { 704 RecordStmtCount(S); 705 Visit(S->getCond()); 706 PGO.setCurrentRegionUnreachable(); 707 BreakContinueStack.push_back(BreakContinue()); 708 Visit(S->getBody()); 709 // If the switch is inside a loop, add the continue counts. 710 BreakContinue BC = BreakContinueStack.pop_back_val(); 711 if (!BreakContinueStack.empty()) 712 BreakContinueStack.back().ContinueCount += BC.ContinueCount; 713 RegionCounter ExitCnt(PGO, S); 714 ExitCnt.beginRegion(); 715 RecordNextStmtCount = true; 716 } 717 718 void VisitCaseStmt(const CaseStmt *S) { 719 RecordNextStmtCount = false; 720 RegionCounter Cnt(PGO, S); 721 Cnt.beginRegion(/*AddIncomingFallThrough=*/true); 722 (*CountMap)[S] = Cnt.getCount(); 723 RecordNextStmtCount = true; 724 Visit(S->getSubStmt()); 725 } 726 727 void VisitDefaultStmt(const DefaultStmt *S) { 728 RecordNextStmtCount = false; 729 RegionCounter Cnt(PGO, S); 730 Cnt.beginRegion(/*AddIncomingFallThrough=*/true); 731 (*CountMap)[S] = Cnt.getCount(); 732 RecordNextStmtCount = true; 733 Visit(S->getSubStmt()); 734 } 735 736 void VisitIfStmt(const IfStmt *S) { 737 RecordStmtCount(S); 738 RegionCounter Cnt(PGO, S); 739 Visit(S->getCond()); 740 741 Cnt.beginRegion(); 742 (*CountMap)[S->getThen()] = PGO.getCurrentRegionCount(); 743 Visit(S->getThen()); 744 Cnt.adjustForControlFlow(); 745 746 if (S->getElse()) { 747 Cnt.beginElseRegion(); 748 (*CountMap)[S->getElse()] = PGO.getCurrentRegionCount(); 749 Visit(S->getElse()); 750 Cnt.adjustForControlFlow(); 751 } 752 Cnt.applyAdjustmentsToRegion(0); 753 RecordNextStmtCount = true; 754 } 755 756 void VisitCXXTryStmt(const CXXTryStmt *S) { 757 RecordStmtCount(S); 758 Visit(S->getTryBlock()); 759 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) 760 Visit(S->getHandler(I)); 761 RegionCounter Cnt(PGO, S); 762 Cnt.beginRegion(); 763 RecordNextStmtCount = true; 764 } 765 766 void VisitCXXCatchStmt(const CXXCatchStmt *S) { 767 RecordNextStmtCount = false; 768 RegionCounter Cnt(PGO, S); 769 Cnt.beginRegion(); 770 (*CountMap)[S] = PGO.getCurrentRegionCount(); 771 Visit(S->getHandlerBlock()); 772 } 773 774 void VisitConditionalOperator(const ConditionalOperator *E) { 775 RecordStmtCount(E); 776 RegionCounter Cnt(PGO, E); 777 Visit(E->getCond()); 778 779 Cnt.beginRegion(); 780 (*CountMap)[E->getTrueExpr()] = PGO.getCurrentRegionCount(); 781 Visit(E->getTrueExpr()); 782 Cnt.adjustForControlFlow(); 783 784 Cnt.beginElseRegion(); 785 (*CountMap)[E->getFalseExpr()] = PGO.getCurrentRegionCount(); 786 Visit(E->getFalseExpr()); 787 Cnt.adjustForControlFlow(); 788 789 Cnt.applyAdjustmentsToRegion(0); 790 RecordNextStmtCount = true; 791 } 792 793 void VisitBinLAnd(const BinaryOperator *E) { 794 RecordStmtCount(E); 795 RegionCounter Cnt(PGO, E); 796 Visit(E->getLHS()); 797 Cnt.beginRegion(); 798 (*CountMap)[E->getRHS()] = PGO.getCurrentRegionCount(); 799 Visit(E->getRHS()); 800 Cnt.adjustForControlFlow(); 801 Cnt.applyAdjustmentsToRegion(0); 802 RecordNextStmtCount = true; 803 } 804 805 void VisitBinLOr(const BinaryOperator *E) { 806 RecordStmtCount(E); 807 RegionCounter Cnt(PGO, E); 808 Visit(E->getLHS()); 809 Cnt.beginRegion(); 810 (*CountMap)[E->getRHS()] = PGO.getCurrentRegionCount(); 811 Visit(E->getRHS()); 812 Cnt.adjustForControlFlow(); 813 Cnt.applyAdjustmentsToRegion(0); 814 RecordNextStmtCount = true; 815 } 816 }; 817 } 818 819 void CodeGenPGO::assignRegionCounters(const Decl *D, llvm::Function *Fn) { 820 bool InstrumentRegions = CGM.getCodeGenOpts().ProfileInstrGenerate; 821 PGOProfileData *PGOData = CGM.getPGOData(); 822 if (!InstrumentRegions && !PGOData) 823 return; 824 if (!D) 825 return; 826 setFuncName(Fn); 827 828 // Set the linkage for variables based on the function linkage. Usually, we 829 // want to match it, but available_externally and extern_weak both have the 830 // wrong semantics. 831 VarLinkage = Fn->getLinkage(); 832 switch (VarLinkage) { 833 case llvm::GlobalValue::ExternalWeakLinkage: 834 VarLinkage = llvm::GlobalValue::LinkOnceAnyLinkage; 835 break; 836 case llvm::GlobalValue::AvailableExternallyLinkage: 837 VarLinkage = llvm::GlobalValue::LinkOnceODRLinkage; 838 break; 839 default: 840 break; 841 } 842 843 mapRegionCounters(D); 844 if (InstrumentRegions) 845 emitCounterVariables(); 846 if (PGOData) { 847 loadRegionCounts(PGOData); 848 computeRegionCounts(D); 849 applyFunctionAttributes(PGOData, Fn); 850 } 851 } 852 853 void CodeGenPGO::mapRegionCounters(const Decl *D) { 854 RegionCounterMap = new llvm::DenseMap<const Stmt*, unsigned>(); 855 MapRegionCounters Walker(RegionCounterMap); 856 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 857 Walker.VisitFunctionDecl(FD); 858 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) 859 Walker.VisitObjCMethodDecl(MD); 860 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D)) 861 Walker.VisitBlockDecl(BD); 862 NumRegionCounters = Walker.NextCounter; 863 // FIXME: The number of counters isn't sufficient for the hash 864 FunctionHash = NumRegionCounters; 865 } 866 867 void CodeGenPGO::computeRegionCounts(const Decl *D) { 868 StmtCountMap = new llvm::DenseMap<const Stmt*, uint64_t>(); 869 ComputeRegionCounts Walker(StmtCountMap, *this); 870 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 871 Walker.VisitFunctionDecl(FD); 872 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) 873 Walker.VisitObjCMethodDecl(MD); 874 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D)) 875 Walker.VisitBlockDecl(BD); 876 } 877 878 void CodeGenPGO::applyFunctionAttributes(PGOProfileData *PGOData, 879 llvm::Function *Fn) { 880 if (!haveRegionCounts()) 881 return; 882 883 uint64_t MaxFunctionCount = PGOData->getMaximumFunctionCount(); 884 uint64_t FunctionCount = getRegionCount(0); 885 if (FunctionCount >= (uint64_t)(0.3 * (double)MaxFunctionCount)) 886 // Turn on InlineHint attribute for hot functions. 887 // FIXME: 30% is from preliminary tuning on SPEC, it may not be optimal. 888 Fn->addFnAttr(llvm::Attribute::InlineHint); 889 else if (FunctionCount <= (uint64_t)(0.01 * (double)MaxFunctionCount)) 890 // Turn on Cold attribute for cold functions. 891 // FIXME: 1% is from preliminary tuning on SPEC, it may not be optimal. 892 Fn->addFnAttr(llvm::Attribute::Cold); 893 } 894 895 void CodeGenPGO::emitCounterVariables() { 896 llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 897 llvm::ArrayType *CounterTy = llvm::ArrayType::get(llvm::Type::getInt64Ty(Ctx), 898 NumRegionCounters); 899 RegionCounters = 900 new llvm::GlobalVariable(CGM.getModule(), CounterTy, false, VarLinkage, 901 llvm::Constant::getNullValue(CounterTy), 902 getFuncVarName("counters")); 903 RegionCounters->setAlignment(8); 904 RegionCounters->setSection(getCountersSection(CGM)); 905 } 906 907 void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, unsigned Counter) { 908 if (!RegionCounters) 909 return; 910 llvm::Value *Addr = 911 Builder.CreateConstInBoundsGEP2_64(RegionCounters, 0, Counter); 912 llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount"); 913 Count = Builder.CreateAdd(Count, Builder.getInt64(1)); 914 Builder.CreateStore(Count, Addr); 915 } 916 917 void CodeGenPGO::loadRegionCounts(PGOProfileData *PGOData) { 918 // For now, ignore the counts from the PGO data file only if the number of 919 // counters does not match. This could be tightened down in the future to 920 // ignore counts when the input changes in various ways, e.g., by comparing a 921 // hash value based on some characteristics of the input. 922 RegionCounts = new std::vector<uint64_t>(); 923 uint64_t Hash; 924 if (PGOData->getFunctionCounts(getFuncName(), Hash, *RegionCounts) || 925 Hash != FunctionHash || RegionCounts->size() != NumRegionCounters) { 926 delete RegionCounts; 927 RegionCounts = 0; 928 } 929 } 930 931 void CodeGenPGO::destroyRegionCounters() { 932 if (RegionCounterMap != 0) 933 delete RegionCounterMap; 934 if (StmtCountMap != 0) 935 delete StmtCountMap; 936 if (RegionCounts != 0) 937 delete RegionCounts; 938 } 939 940 /// \brief Calculate what to divide by to scale weights. 941 /// 942 /// Given the maximum weight, calculate a divisor that will scale all the 943 /// weights to strictly less than UINT32_MAX. 944 static uint64_t calculateWeightScale(uint64_t MaxWeight) { 945 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1; 946 } 947 948 /// \brief Scale an individual branch weight (and add 1). 949 /// 950 /// Scale a 64-bit weight down to 32-bits using \c Scale. 951 /// 952 /// According to Laplace's Rule of Succession, it is better to compute the 953 /// weight based on the count plus 1, so universally add 1 to the value. 954 /// 955 /// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no 956 /// greater than \c Weight. 957 static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) { 958 assert(Scale && "scale by 0?"); 959 uint64_t Scaled = Weight / Scale + 1; 960 assert(Scaled <= UINT32_MAX && "overflow 32-bits"); 961 return Scaled; 962 } 963 964 llvm::MDNode *CodeGenPGO::createBranchWeights(uint64_t TrueCount, 965 uint64_t FalseCount) { 966 // Check for empty weights. 967 if (!TrueCount && !FalseCount) 968 return nullptr; 969 970 // Calculate how to scale down to 32-bits. 971 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount)); 972 973 llvm::MDBuilder MDHelper(CGM.getLLVMContext()); 974 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale), 975 scaleBranchWeight(FalseCount, Scale)); 976 } 977 978 llvm::MDNode *CodeGenPGO::createBranchWeights(ArrayRef<uint64_t> Weights) { 979 // We need at least two elements to create meaningful weights. 980 if (Weights.size() < 2) 981 return nullptr; 982 983 // Calculate how to scale down to 32-bits. 984 uint64_t Scale = calculateWeightScale(*std::max_element(Weights.begin(), 985 Weights.end())); 986 987 SmallVector<uint32_t, 16> ScaledWeights; 988 ScaledWeights.reserve(Weights.size()); 989 for (uint64_t W : Weights) 990 ScaledWeights.push_back(scaleBranchWeight(W, Scale)); 991 992 llvm::MDBuilder MDHelper(CGM.getLLVMContext()); 993 return MDHelper.createBranchWeights(ScaledWeights); 994 } 995 996 llvm::MDNode *CodeGenPGO::createLoopWeights(const Stmt *Cond, 997 RegionCounter &Cnt) { 998 if (!haveRegionCounts()) 999 return nullptr; 1000 uint64_t LoopCount = Cnt.getCount(); 1001 uint64_t CondCount = 0; 1002 bool Found = getStmtCount(Cond, CondCount); 1003 assert(Found && "missing expected loop condition count"); 1004 (void)Found; 1005 if (CondCount == 0) 1006 return nullptr; 1007 return createBranchWeights(LoopCount, 1008 std::max(CondCount, LoopCount) - LoopCount); 1009 } 1010