1 //===-- ControlHeightReduction.cpp - Control Height Reduction -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass merges conditional blocks of code and reduces the number of 10 // conditional branches in the hot paths based on profiles. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/DenseSet.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/StringSet.h" 19 #include "llvm/Analysis/BlockFrequencyInfo.h" 20 #include "llvm/Analysis/GlobalsModRef.h" 21 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 22 #include "llvm/Analysis/ProfileSummaryInfo.h" 23 #include "llvm/Analysis/RegionInfo.h" 24 #include "llvm/Analysis/RegionIterator.h" 25 #include "llvm/Analysis/ValueTracking.h" 26 #include "llvm/IR/CFG.h" 27 #include "llvm/IR/Dominators.h" 28 #include "llvm/IR/IRBuilder.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/IR/MDBuilder.h" 31 #include "llvm/IR/PassManager.h" 32 #include "llvm/InitializePasses.h" 33 #include "llvm/Support/BranchProbability.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/MemoryBuffer.h" 36 #include "llvm/Transforms/Utils.h" 37 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38 #include "llvm/Transforms/Utils/Cloning.h" 39 #include "llvm/Transforms/Utils/ValueMapper.h" 40 41 #include <set> 42 #include <sstream> 43 44 using namespace llvm; 45 46 #define DEBUG_TYPE "chr" 47 48 #define CHR_DEBUG(X) LLVM_DEBUG(X) 49 50 static cl::opt<bool> ForceCHR("force-chr", cl::init(false), cl::Hidden, 51 cl::desc("Apply CHR for all functions")); 52 53 static cl::opt<double> CHRBiasThreshold( 54 "chr-bias-threshold", cl::init(0.99), cl::Hidden, 55 cl::desc("CHR considers a branch bias greater than this ratio as biased")); 56 57 static cl::opt<unsigned> CHRMergeThreshold( 58 "chr-merge-threshold", cl::init(2), cl::Hidden, 59 cl::desc("CHR merges a group of N branches/selects where N >= this value")); 60 61 static cl::opt<std::string> CHRModuleList( 62 "chr-module-list", cl::init(""), cl::Hidden, 63 cl::desc("Specify file to retrieve the list of modules to apply CHR to")); 64 65 static cl::opt<std::string> CHRFunctionList( 66 "chr-function-list", cl::init(""), cl::Hidden, 67 cl::desc("Specify file to retrieve the list of functions to apply CHR to")); 68 69 static StringSet<> CHRModules; 70 static StringSet<> CHRFunctions; 71 72 static void parseCHRFilterFiles() { 73 if (!CHRModuleList.empty()) { 74 auto FileOrErr = MemoryBuffer::getFile(CHRModuleList); 75 if (!FileOrErr) { 76 errs() << "Error: Couldn't read the chr-module-list file " << CHRModuleList << "\n"; 77 std::exit(1); 78 } 79 StringRef Buf = FileOrErr->get()->getBuffer(); 80 SmallVector<StringRef, 0> Lines; 81 Buf.split(Lines, '\n'); 82 for (StringRef Line : Lines) { 83 Line = Line.trim(); 84 if (!Line.empty()) 85 CHRModules.insert(Line); 86 } 87 } 88 if (!CHRFunctionList.empty()) { 89 auto FileOrErr = MemoryBuffer::getFile(CHRFunctionList); 90 if (!FileOrErr) { 91 errs() << "Error: Couldn't read the chr-function-list file " << CHRFunctionList << "\n"; 92 std::exit(1); 93 } 94 StringRef Buf = FileOrErr->get()->getBuffer(); 95 SmallVector<StringRef, 0> Lines; 96 Buf.split(Lines, '\n'); 97 for (StringRef Line : Lines) { 98 Line = Line.trim(); 99 if (!Line.empty()) 100 CHRFunctions.insert(Line); 101 } 102 } 103 } 104 105 namespace { 106 107 struct CHRStats { 108 CHRStats() = default; 109 void print(raw_ostream &OS) const { 110 OS << "CHRStats: NumBranches " << NumBranches 111 << " NumBranchesDelta " << NumBranchesDelta 112 << " WeightedNumBranchesDelta " << WeightedNumBranchesDelta; 113 } 114 // The original number of conditional branches / selects 115 uint64_t NumBranches = 0; 116 // The decrease of the number of conditional branches / selects in the hot 117 // paths due to CHR. 118 uint64_t NumBranchesDelta = 0; 119 // NumBranchesDelta weighted by the profile count at the scope entry. 120 uint64_t WeightedNumBranchesDelta = 0; 121 }; 122 123 // RegInfo - some properties of a Region. 124 struct RegInfo { 125 RegInfo() = default; 126 RegInfo(Region *RegionIn) : R(RegionIn) {} 127 Region *R = nullptr; 128 bool HasBranch = false; 129 SmallVector<SelectInst *, 8> Selects; 130 }; 131 132 typedef DenseMap<Region *, DenseSet<Instruction *>> HoistStopMapTy; 133 134 // CHRScope - a sequence of regions to CHR together. It corresponds to a 135 // sequence of conditional blocks. It can have subscopes which correspond to 136 // nested conditional blocks. Nested CHRScopes form a tree. 137 class CHRScope { 138 public: 139 CHRScope(RegInfo RI) : BranchInsertPoint(nullptr) { 140 assert(RI.R && "Null RegionIn"); 141 RegInfos.push_back(RI); 142 } 143 144 Region *getParentRegion() { 145 assert(RegInfos.size() > 0 && "Empty CHRScope"); 146 Region *Parent = RegInfos[0].R->getParent(); 147 assert(Parent && "Unexpected to call this on the top-level region"); 148 return Parent; 149 } 150 151 BasicBlock *getEntryBlock() { 152 assert(RegInfos.size() > 0 && "Empty CHRScope"); 153 return RegInfos.front().R->getEntry(); 154 } 155 156 BasicBlock *getExitBlock() { 157 assert(RegInfos.size() > 0 && "Empty CHRScope"); 158 return RegInfos.back().R->getExit(); 159 } 160 161 bool appendable(CHRScope *Next) { 162 // The next scope is appendable only if this scope is directly connected to 163 // it (which implies it post-dominates this scope) and this scope dominates 164 // it (no edge to the next scope outside this scope). 165 BasicBlock *NextEntry = Next->getEntryBlock(); 166 if (getExitBlock() != NextEntry) 167 // Not directly connected. 168 return false; 169 Region *LastRegion = RegInfos.back().R; 170 for (BasicBlock *Pred : predecessors(NextEntry)) 171 if (!LastRegion->contains(Pred)) 172 // There's an edge going into the entry of the next scope from outside 173 // of this scope. 174 return false; 175 return true; 176 } 177 178 void append(CHRScope *Next) { 179 assert(RegInfos.size() > 0 && "Empty CHRScope"); 180 assert(Next->RegInfos.size() > 0 && "Empty CHRScope"); 181 assert(getParentRegion() == Next->getParentRegion() && 182 "Must be siblings"); 183 assert(getExitBlock() == Next->getEntryBlock() && 184 "Must be adjacent"); 185 RegInfos.append(Next->RegInfos.begin(), Next->RegInfos.end()); 186 Subs.append(Next->Subs.begin(), Next->Subs.end()); 187 } 188 189 void addSub(CHRScope *SubIn) { 190 #ifndef NDEBUG 191 bool IsChild = false; 192 for (RegInfo &RI : RegInfos) 193 if (RI.R == SubIn->getParentRegion()) { 194 IsChild = true; 195 break; 196 } 197 assert(IsChild && "Must be a child"); 198 #endif 199 Subs.push_back(SubIn); 200 } 201 202 // Split this scope at the boundary region into two, which will belong to the 203 // tail and returns the tail. 204 CHRScope *split(Region *Boundary) { 205 assert(Boundary && "Boundary null"); 206 assert(RegInfos.begin()->R != Boundary && 207 "Can't be split at beginning"); 208 auto BoundaryIt = llvm::find_if( 209 RegInfos, [&Boundary](const RegInfo &RI) { return Boundary == RI.R; }); 210 if (BoundaryIt == RegInfos.end()) 211 return nullptr; 212 ArrayRef<RegInfo> TailRegInfos(BoundaryIt, RegInfos.end()); 213 DenseSet<Region *> TailRegionSet; 214 for (const RegInfo &RI : TailRegInfos) 215 TailRegionSet.insert(RI.R); 216 217 auto TailIt = 218 std::stable_partition(Subs.begin(), Subs.end(), [&](CHRScope *Sub) { 219 assert(Sub && "null Sub"); 220 Region *Parent = Sub->getParentRegion(); 221 if (TailRegionSet.count(Parent)) 222 return false; 223 224 assert(llvm::any_of( 225 RegInfos, 226 [&Parent](const RegInfo &RI) { return Parent == RI.R; }) && 227 "Must be in head"); 228 return true; 229 }); 230 ArrayRef<CHRScope *> TailSubs(TailIt, Subs.end()); 231 232 assert(HoistStopMap.empty() && "MapHoistStops must be empty"); 233 auto *Scope = new CHRScope(TailRegInfos, TailSubs); 234 RegInfos.erase(BoundaryIt, RegInfos.end()); 235 Subs.erase(TailIt, Subs.end()); 236 return Scope; 237 } 238 239 bool contains(Instruction *I) const { 240 BasicBlock *Parent = I->getParent(); 241 for (const RegInfo &RI : RegInfos) 242 if (RI.R->contains(Parent)) 243 return true; 244 return false; 245 } 246 247 void print(raw_ostream &OS) const; 248 249 SmallVector<RegInfo, 8> RegInfos; // Regions that belong to this scope 250 SmallVector<CHRScope *, 8> Subs; // Subscopes. 251 252 // The instruction at which to insert the CHR conditional branch (and hoist 253 // the dependent condition values). 254 Instruction *BranchInsertPoint; 255 256 // True-biased and false-biased regions (conditional blocks), 257 // respectively. Used only for the outermost scope and includes regions in 258 // subscopes. The rest are unbiased. 259 DenseSet<Region *> TrueBiasedRegions; 260 DenseSet<Region *> FalseBiasedRegions; 261 // Among the biased regions, the regions that get CHRed. 262 SmallVector<RegInfo, 8> CHRRegions; 263 264 // True-biased and false-biased selects, respectively. Used only for the 265 // outermost scope and includes ones in subscopes. 266 DenseSet<SelectInst *> TrueBiasedSelects; 267 DenseSet<SelectInst *> FalseBiasedSelects; 268 269 // Map from one of the above regions to the instructions to stop 270 // hoisting instructions at through use-def chains. 271 HoistStopMapTy HoistStopMap; 272 273 private: 274 CHRScope(ArrayRef<RegInfo> RegInfosIn, ArrayRef<CHRScope *> SubsIn) 275 : RegInfos(RegInfosIn.begin(), RegInfosIn.end()), 276 Subs(SubsIn.begin(), SubsIn.end()), BranchInsertPoint(nullptr) {} 277 }; 278 279 class CHR { 280 public: 281 CHR(Function &Fin, BlockFrequencyInfo &BFIin, DominatorTree &DTin, 282 ProfileSummaryInfo &PSIin, RegionInfo &RIin, 283 OptimizationRemarkEmitter &OREin) 284 : F(Fin), BFI(BFIin), DT(DTin), PSI(PSIin), RI(RIin), ORE(OREin) {} 285 286 ~CHR() { 287 for (CHRScope *Scope : Scopes) { 288 delete Scope; 289 } 290 } 291 292 bool run(); 293 294 private: 295 // See the comments in CHR::run() for the high level flow of the algorithm and 296 // what the following functions do. 297 298 void findScopes(SmallVectorImpl<CHRScope *> &Output) { 299 Region *R = RI.getTopLevelRegion(); 300 if (CHRScope *Scope = findScopes(R, nullptr, nullptr, Output)) { 301 Output.push_back(Scope); 302 } 303 } 304 CHRScope *findScopes(Region *R, Region *NextRegion, Region *ParentRegion, 305 SmallVectorImpl<CHRScope *> &Scopes); 306 CHRScope *findScope(Region *R); 307 void checkScopeHoistable(CHRScope *Scope); 308 309 void splitScopes(SmallVectorImpl<CHRScope *> &Input, 310 SmallVectorImpl<CHRScope *> &Output); 311 SmallVector<CHRScope *, 8> splitScope(CHRScope *Scope, 312 CHRScope *Outer, 313 DenseSet<Value *> *OuterConditionValues, 314 Instruction *OuterInsertPoint, 315 SmallVectorImpl<CHRScope *> &Output, 316 DenseSet<Instruction *> &Unhoistables); 317 318 void classifyBiasedScopes(SmallVectorImpl<CHRScope *> &Scopes); 319 void classifyBiasedScopes(CHRScope *Scope, CHRScope *OutermostScope); 320 321 void filterScopes(SmallVectorImpl<CHRScope *> &Input, 322 SmallVectorImpl<CHRScope *> &Output); 323 324 void setCHRRegions(SmallVectorImpl<CHRScope *> &Input, 325 SmallVectorImpl<CHRScope *> &Output); 326 void setCHRRegions(CHRScope *Scope, CHRScope *OutermostScope); 327 328 void sortScopes(SmallVectorImpl<CHRScope *> &Input, 329 SmallVectorImpl<CHRScope *> &Output); 330 331 void transformScopes(SmallVectorImpl<CHRScope *> &CHRScopes); 332 void transformScopes(CHRScope *Scope, DenseSet<PHINode *> &TrivialPHIs); 333 void cloneScopeBlocks(CHRScope *Scope, 334 BasicBlock *PreEntryBlock, 335 BasicBlock *ExitBlock, 336 Region *LastRegion, 337 ValueToValueMapTy &VMap); 338 BranchInst *createMergedBranch(BasicBlock *PreEntryBlock, 339 BasicBlock *EntryBlock, 340 BasicBlock *NewEntryBlock, 341 ValueToValueMapTy &VMap); 342 void fixupBranchesAndSelects(CHRScope *Scope, 343 BasicBlock *PreEntryBlock, 344 BranchInst *MergedBR, 345 uint64_t ProfileCount); 346 void fixupBranch(Region *R, 347 CHRScope *Scope, 348 IRBuilder<> &IRB, 349 Value *&MergedCondition, BranchProbability &CHRBranchBias); 350 void fixupSelect(SelectInst* SI, 351 CHRScope *Scope, 352 IRBuilder<> &IRB, 353 Value *&MergedCondition, BranchProbability &CHRBranchBias); 354 void addToMergedCondition(bool IsTrueBiased, Value *Cond, 355 Instruction *BranchOrSelect, 356 CHRScope *Scope, 357 IRBuilder<> &IRB, 358 Value *&MergedCondition); 359 360 Function &F; 361 BlockFrequencyInfo &BFI; 362 DominatorTree &DT; 363 ProfileSummaryInfo &PSI; 364 RegionInfo &RI; 365 OptimizationRemarkEmitter &ORE; 366 CHRStats Stats; 367 368 // All the true-biased regions in the function 369 DenseSet<Region *> TrueBiasedRegionsGlobal; 370 // All the false-biased regions in the function 371 DenseSet<Region *> FalseBiasedRegionsGlobal; 372 // All the true-biased selects in the function 373 DenseSet<SelectInst *> TrueBiasedSelectsGlobal; 374 // All the false-biased selects in the function 375 DenseSet<SelectInst *> FalseBiasedSelectsGlobal; 376 // A map from biased regions to their branch bias 377 DenseMap<Region *, BranchProbability> BranchBiasMap; 378 // A map from biased selects to their branch bias 379 DenseMap<SelectInst *, BranchProbability> SelectBiasMap; 380 // All the scopes. 381 DenseSet<CHRScope *> Scopes; 382 }; 383 384 } // end anonymous namespace 385 386 static inline 387 raw_ostream LLVM_ATTRIBUTE_UNUSED &operator<<(raw_ostream &OS, 388 const CHRStats &Stats) { 389 Stats.print(OS); 390 return OS; 391 } 392 393 static inline 394 raw_ostream &operator<<(raw_ostream &OS, const CHRScope &Scope) { 395 Scope.print(OS); 396 return OS; 397 } 398 399 static bool shouldApply(Function &F, ProfileSummaryInfo& PSI) { 400 if (ForceCHR) 401 return true; 402 403 if (!CHRModuleList.empty() || !CHRFunctionList.empty()) { 404 if (CHRModules.count(F.getParent()->getName())) 405 return true; 406 return CHRFunctions.count(F.getName()); 407 } 408 409 return PSI.isFunctionEntryHot(&F); 410 } 411 412 static void LLVM_ATTRIBUTE_UNUSED dumpIR(Function &F, const char *Label, 413 CHRStats *Stats) { 414 StringRef FuncName = F.getName(); 415 StringRef ModuleName = F.getParent()->getName(); 416 (void)(FuncName); // Unused in release build. 417 (void)(ModuleName); // Unused in release build. 418 CHR_DEBUG(dbgs() << "CHR IR dump " << Label << " " << ModuleName << " " 419 << FuncName); 420 if (Stats) 421 CHR_DEBUG(dbgs() << " " << *Stats); 422 CHR_DEBUG(dbgs() << "\n"); 423 CHR_DEBUG(F.dump()); 424 } 425 426 void CHRScope::print(raw_ostream &OS) const { 427 assert(RegInfos.size() > 0 && "Empty CHRScope"); 428 OS << "CHRScope["; 429 OS << RegInfos.size() << ", Regions["; 430 for (const RegInfo &RI : RegInfos) { 431 OS << RI.R->getNameStr(); 432 if (RI.HasBranch) 433 OS << " B"; 434 if (RI.Selects.size() > 0) 435 OS << " S" << RI.Selects.size(); 436 OS << ", "; 437 } 438 if (RegInfos[0].R->getParent()) { 439 OS << "], Parent " << RegInfos[0].R->getParent()->getNameStr(); 440 } else { 441 // top level region 442 OS << "]"; 443 } 444 OS << ", Subs["; 445 for (CHRScope *Sub : Subs) { 446 OS << *Sub << ", "; 447 } 448 OS << "]]"; 449 } 450 451 // Return true if the given instruction type can be hoisted by CHR. 452 static bool isHoistableInstructionType(Instruction *I) { 453 return isa<BinaryOperator>(I) || isa<CastInst>(I) || isa<SelectInst>(I) || 454 isa<GetElementPtrInst>(I) || isa<CmpInst>(I) || 455 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) || 456 isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) || 457 isa<InsertValueInst>(I); 458 } 459 460 // Return true if the given instruction can be hoisted by CHR. 461 static bool isHoistable(Instruction *I, DominatorTree &DT) { 462 if (!isHoistableInstructionType(I)) 463 return false; 464 return isSafeToSpeculativelyExecute(I, nullptr, nullptr, &DT); 465 } 466 467 // Recursively traverse the use-def chains of the given value and return a set 468 // of the unhoistable base values defined within the scope (excluding the 469 // first-region entry block) or the (hoistable or unhoistable) base values that 470 // are defined outside (including the first-region entry block) of the 471 // scope. The returned set doesn't include constants. 472 static const std::set<Value *> & 473 getBaseValues(Value *V, DominatorTree &DT, 474 DenseMap<Value *, std::set<Value *>> &Visited) { 475 auto It = Visited.find(V); 476 if (It != Visited.end()) { 477 return It->second; 478 } 479 std::set<Value *> Result; 480 if (auto *I = dyn_cast<Instruction>(V)) { 481 // We don't stop at a block that's not in the Scope because we would miss 482 // some instructions that are based on the same base values if we stop 483 // there. 484 if (!isHoistable(I, DT)) { 485 Result.insert(I); 486 return Visited.insert(std::make_pair(V, std::move(Result))).first->second; 487 } 488 // I is hoistable above the Scope. 489 for (Value *Op : I->operands()) { 490 const std::set<Value *> &OpResult = getBaseValues(Op, DT, Visited); 491 Result.insert(OpResult.begin(), OpResult.end()); 492 } 493 return Visited.insert(std::make_pair(V, std::move(Result))).first->second; 494 } 495 if (isa<Argument>(V)) { 496 Result.insert(V); 497 } 498 // We don't include others like constants because those won't lead to any 499 // chance of folding of conditions (eg two bit checks merged into one check) 500 // after CHR. 501 return Visited.insert(std::make_pair(V, std::move(Result))).first->second; 502 } 503 504 // Return true if V is already hoisted or can be hoisted (along with its 505 // operands) above the insert point. When it returns true and HoistStops is 506 // non-null, the instructions to stop hoisting at through the use-def chains are 507 // inserted into HoistStops. 508 static bool 509 checkHoistValue(Value *V, Instruction *InsertPoint, DominatorTree &DT, 510 DenseSet<Instruction *> &Unhoistables, 511 DenseSet<Instruction *> *HoistStops, 512 DenseMap<Instruction *, bool> &Visited) { 513 assert(InsertPoint && "Null InsertPoint"); 514 if (auto *I = dyn_cast<Instruction>(V)) { 515 auto It = Visited.find(I); 516 if (It != Visited.end()) { 517 return It->second; 518 } 519 assert(DT.getNode(I->getParent()) && "DT must contain I's parent block"); 520 assert(DT.getNode(InsertPoint->getParent()) && "DT must contain Destination"); 521 if (Unhoistables.count(I)) { 522 // Don't hoist if they are not to be hoisted. 523 Visited[I] = false; 524 return false; 525 } 526 if (DT.dominates(I, InsertPoint)) { 527 // We are already above the insert point. Stop here. 528 if (HoistStops) 529 HoistStops->insert(I); 530 Visited[I] = true; 531 return true; 532 } 533 // We aren't not above the insert point, check if we can hoist it above the 534 // insert point. 535 if (isHoistable(I, DT)) { 536 // Check operands first. 537 DenseSet<Instruction *> OpsHoistStops; 538 bool AllOpsHoisted = true; 539 for (Value *Op : I->operands()) { 540 if (!checkHoistValue(Op, InsertPoint, DT, Unhoistables, &OpsHoistStops, 541 Visited)) { 542 AllOpsHoisted = false; 543 break; 544 } 545 } 546 if (AllOpsHoisted) { 547 CHR_DEBUG(dbgs() << "checkHoistValue " << *I << "\n"); 548 if (HoistStops) 549 HoistStops->insert(OpsHoistStops.begin(), OpsHoistStops.end()); 550 Visited[I] = true; 551 return true; 552 } 553 } 554 Visited[I] = false; 555 return false; 556 } 557 // Non-instructions are considered hoistable. 558 return true; 559 } 560 561 // Returns true and sets the true probability and false probability of an 562 // MD_prof metadata if it's well-formed. 563 static bool checkMDProf(MDNode *MD, BranchProbability &TrueProb, 564 BranchProbability &FalseProb) { 565 if (!MD) return false; 566 MDString *MDName = cast<MDString>(MD->getOperand(0)); 567 if (MDName->getString() != "branch_weights" || 568 MD->getNumOperands() != 3) 569 return false; 570 ConstantInt *TrueWeight = mdconst::extract<ConstantInt>(MD->getOperand(1)); 571 ConstantInt *FalseWeight = mdconst::extract<ConstantInt>(MD->getOperand(2)); 572 if (!TrueWeight || !FalseWeight) 573 return false; 574 uint64_t TrueWt = TrueWeight->getValue().getZExtValue(); 575 uint64_t FalseWt = FalseWeight->getValue().getZExtValue(); 576 uint64_t SumWt = TrueWt + FalseWt; 577 578 assert(SumWt >= TrueWt && SumWt >= FalseWt && 579 "Overflow calculating branch probabilities."); 580 581 // Guard against 0-to-0 branch weights to avoid a division-by-zero crash. 582 if (SumWt == 0) 583 return false; 584 585 TrueProb = BranchProbability::getBranchProbability(TrueWt, SumWt); 586 FalseProb = BranchProbability::getBranchProbability(FalseWt, SumWt); 587 return true; 588 } 589 590 static BranchProbability getCHRBiasThreshold() { 591 return BranchProbability::getBranchProbability( 592 static_cast<uint64_t>(CHRBiasThreshold * 1000000), 1000000); 593 } 594 595 // A helper for CheckBiasedBranch and CheckBiasedSelect. If TrueProb >= 596 // CHRBiasThreshold, put Key into TrueSet and return true. If FalseProb >= 597 // CHRBiasThreshold, put Key into FalseSet and return true. Otherwise, return 598 // false. 599 template <typename K, typename S, typename M> 600 static bool checkBias(K *Key, BranchProbability TrueProb, 601 BranchProbability FalseProb, S &TrueSet, S &FalseSet, 602 M &BiasMap) { 603 BranchProbability Threshold = getCHRBiasThreshold(); 604 if (TrueProb >= Threshold) { 605 TrueSet.insert(Key); 606 BiasMap[Key] = TrueProb; 607 return true; 608 } else if (FalseProb >= Threshold) { 609 FalseSet.insert(Key); 610 BiasMap[Key] = FalseProb; 611 return true; 612 } 613 return false; 614 } 615 616 // Returns true and insert a region into the right biased set and the map if the 617 // branch of the region is biased. 618 static bool checkBiasedBranch(BranchInst *BI, Region *R, 619 DenseSet<Region *> &TrueBiasedRegionsGlobal, 620 DenseSet<Region *> &FalseBiasedRegionsGlobal, 621 DenseMap<Region *, BranchProbability> &BranchBiasMap) { 622 if (!BI->isConditional()) 623 return false; 624 BranchProbability ThenProb, ElseProb; 625 if (!checkMDProf(BI->getMetadata(LLVMContext::MD_prof), 626 ThenProb, ElseProb)) 627 return false; 628 BasicBlock *IfThen = BI->getSuccessor(0); 629 BasicBlock *IfElse = BI->getSuccessor(1); 630 assert((IfThen == R->getExit() || IfElse == R->getExit()) && 631 IfThen != IfElse && 632 "Invariant from findScopes"); 633 if (IfThen == R->getExit()) { 634 // Swap them so that IfThen/ThenProb means going into the conditional code 635 // and IfElse/ElseProb means skipping it. 636 std::swap(IfThen, IfElse); 637 std::swap(ThenProb, ElseProb); 638 } 639 CHR_DEBUG(dbgs() << "BI " << *BI << " "); 640 CHR_DEBUG(dbgs() << "ThenProb " << ThenProb << " "); 641 CHR_DEBUG(dbgs() << "ElseProb " << ElseProb << "\n"); 642 return checkBias(R, ThenProb, ElseProb, 643 TrueBiasedRegionsGlobal, FalseBiasedRegionsGlobal, 644 BranchBiasMap); 645 } 646 647 // Returns true and insert a select into the right biased set and the map if the 648 // select is biased. 649 static bool checkBiasedSelect( 650 SelectInst *SI, Region *R, 651 DenseSet<SelectInst *> &TrueBiasedSelectsGlobal, 652 DenseSet<SelectInst *> &FalseBiasedSelectsGlobal, 653 DenseMap<SelectInst *, BranchProbability> &SelectBiasMap) { 654 BranchProbability TrueProb, FalseProb; 655 if (!checkMDProf(SI->getMetadata(LLVMContext::MD_prof), 656 TrueProb, FalseProb)) 657 return false; 658 CHR_DEBUG(dbgs() << "SI " << *SI << " "); 659 CHR_DEBUG(dbgs() << "TrueProb " << TrueProb << " "); 660 CHR_DEBUG(dbgs() << "FalseProb " << FalseProb << "\n"); 661 return checkBias(SI, TrueProb, FalseProb, 662 TrueBiasedSelectsGlobal, FalseBiasedSelectsGlobal, 663 SelectBiasMap); 664 } 665 666 // Returns the instruction at which to hoist the dependent condition values and 667 // insert the CHR branch for a region. This is the terminator branch in the 668 // entry block or the first select in the entry block, if any. 669 static Instruction* getBranchInsertPoint(RegInfo &RI) { 670 Region *R = RI.R; 671 BasicBlock *EntryBB = R->getEntry(); 672 // The hoist point is by default the terminator of the entry block, which is 673 // the same as the branch instruction if RI.HasBranch is true. 674 Instruction *HoistPoint = EntryBB->getTerminator(); 675 for (SelectInst *SI : RI.Selects) { 676 if (SI->getParent() == EntryBB) { 677 // Pick the first select in Selects in the entry block. Note Selects is 678 // sorted in the instruction order within a block (asserted below). 679 HoistPoint = SI; 680 break; 681 } 682 } 683 assert(HoistPoint && "Null HoistPoint"); 684 #ifndef NDEBUG 685 // Check that HoistPoint is the first one in Selects in the entry block, 686 // if any. 687 DenseSet<Instruction *> EntryBlockSelectSet; 688 for (SelectInst *SI : RI.Selects) { 689 if (SI->getParent() == EntryBB) { 690 EntryBlockSelectSet.insert(SI); 691 } 692 } 693 for (Instruction &I : *EntryBB) { 694 if (EntryBlockSelectSet.contains(&I)) { 695 assert(&I == HoistPoint && 696 "HoistPoint must be the first one in Selects"); 697 break; 698 } 699 } 700 #endif 701 return HoistPoint; 702 } 703 704 // Find a CHR scope in the given region. 705 CHRScope * CHR::findScope(Region *R) { 706 CHRScope *Result = nullptr; 707 BasicBlock *Entry = R->getEntry(); 708 BasicBlock *Exit = R->getExit(); // null if top level. 709 assert(Entry && "Entry must not be null"); 710 assert((Exit == nullptr) == (R->isTopLevelRegion()) && 711 "Only top level region has a null exit"); 712 if (Entry) 713 CHR_DEBUG(dbgs() << "Entry " << Entry->getName() << "\n"); 714 else 715 CHR_DEBUG(dbgs() << "Entry null\n"); 716 if (Exit) 717 CHR_DEBUG(dbgs() << "Exit " << Exit->getName() << "\n"); 718 else 719 CHR_DEBUG(dbgs() << "Exit null\n"); 720 // Exclude cases where Entry is part of a subregion (hence it doesn't belong 721 // to this region). 722 bool EntryInSubregion = RI.getRegionFor(Entry) != R; 723 if (EntryInSubregion) 724 return nullptr; 725 // Exclude loops 726 for (BasicBlock *Pred : predecessors(Entry)) 727 if (R->contains(Pred)) 728 return nullptr; 729 // If any of the basic blocks have address taken, we must skip this region 730 // because we cannot clone basic blocks that have address taken. 731 for (BasicBlock *BB : R->blocks()) { 732 if (BB->hasAddressTaken()) 733 return nullptr; 734 // If we encounter llvm.coro.id, skip this region because if the basic block 735 // is cloned, we end up inserting a token type PHI node to the block with 736 // llvm.coro.begin. 737 // FIXME: This could lead to less optimal codegen, because the region is 738 // excluded, it can prevent CHR from merging adjacent regions into bigger 739 // scope and hoisting more branches. 740 for (Instruction &I : *BB) 741 if (auto *II = dyn_cast<IntrinsicInst>(&I)) 742 if (II->getIntrinsicID() == Intrinsic::coro_id) 743 return nullptr; 744 } 745 746 if (Exit) { 747 // Try to find an if-then block (check if R is an if-then). 748 // if (cond) { 749 // ... 750 // } 751 auto *BI = dyn_cast<BranchInst>(Entry->getTerminator()); 752 if (BI) 753 CHR_DEBUG(dbgs() << "BI.isConditional " << BI->isConditional() << "\n"); 754 else 755 CHR_DEBUG(dbgs() << "BI null\n"); 756 if (BI && BI->isConditional()) { 757 BasicBlock *S0 = BI->getSuccessor(0); 758 BasicBlock *S1 = BI->getSuccessor(1); 759 CHR_DEBUG(dbgs() << "S0 " << S0->getName() << "\n"); 760 CHR_DEBUG(dbgs() << "S1 " << S1->getName() << "\n"); 761 if (S0 != S1 && (S0 == Exit || S1 == Exit)) { 762 RegInfo RI(R); 763 RI.HasBranch = checkBiasedBranch( 764 BI, R, TrueBiasedRegionsGlobal, FalseBiasedRegionsGlobal, 765 BranchBiasMap); 766 Result = new CHRScope(RI); 767 Scopes.insert(Result); 768 CHR_DEBUG(dbgs() << "Found a region with a branch\n"); 769 ++Stats.NumBranches; 770 if (!RI.HasBranch) { 771 ORE.emit([&]() { 772 return OptimizationRemarkMissed(DEBUG_TYPE, "BranchNotBiased", BI) 773 << "Branch not biased"; 774 }); 775 } 776 } 777 } 778 } 779 { 780 // Try to look for selects in the direct child blocks (as opposed to in 781 // subregions) of R. 782 // ... 783 // if (..) { // Some subregion 784 // ... 785 // } 786 // if (..) { // Some subregion 787 // ... 788 // } 789 // ... 790 // a = cond ? b : c; 791 // ... 792 SmallVector<SelectInst *, 8> Selects; 793 for (RegionNode *E : R->elements()) { 794 if (E->isSubRegion()) 795 continue; 796 // This returns the basic block of E if E is a direct child of R (not a 797 // subregion.) 798 BasicBlock *BB = E->getEntry(); 799 // Need to push in the order to make it easier to find the first Select 800 // later. 801 for (Instruction &I : *BB) { 802 if (auto *SI = dyn_cast<SelectInst>(&I)) { 803 Selects.push_back(SI); 804 ++Stats.NumBranches; 805 } 806 } 807 } 808 if (Selects.size() > 0) { 809 auto AddSelects = [&](RegInfo &RI) { 810 for (auto *SI : Selects) 811 if (checkBiasedSelect(SI, RI.R, 812 TrueBiasedSelectsGlobal, 813 FalseBiasedSelectsGlobal, 814 SelectBiasMap)) 815 RI.Selects.push_back(SI); 816 else 817 ORE.emit([&]() { 818 return OptimizationRemarkMissed(DEBUG_TYPE, "SelectNotBiased", SI) 819 << "Select not biased"; 820 }); 821 }; 822 if (!Result) { 823 CHR_DEBUG(dbgs() << "Found a select-only region\n"); 824 RegInfo RI(R); 825 AddSelects(RI); 826 Result = new CHRScope(RI); 827 Scopes.insert(Result); 828 } else { 829 CHR_DEBUG(dbgs() << "Found select(s) in a region with a branch\n"); 830 AddSelects(Result->RegInfos[0]); 831 } 832 } 833 } 834 835 if (Result) { 836 checkScopeHoistable(Result); 837 } 838 return Result; 839 } 840 841 // Check that any of the branch and the selects in the region could be 842 // hoisted above the the CHR branch insert point (the most dominating of 843 // them, either the branch (at the end of the first block) or the first 844 // select in the first block). If the branch can't be hoisted, drop the 845 // selects in the first blocks. 846 // 847 // For example, for the following scope/region with selects, we want to insert 848 // the merged branch right before the first select in the first/entry block by 849 // hoisting c1, c2, c3, and c4. 850 // 851 // // Branch insert point here. 852 // a = c1 ? b : c; // Select 1 853 // d = c2 ? e : f; // Select 2 854 // if (c3) { // Branch 855 // ... 856 // c4 = foo() // A call. 857 // g = c4 ? h : i; // Select 3 858 // } 859 // 860 // But suppose we can't hoist c4 because it's dependent on the preceding 861 // call. Then, we drop Select 3. Furthermore, if we can't hoist c2, we also drop 862 // Select 2. If we can't hoist c3, we drop Selects 1 & 2. 863 void CHR::checkScopeHoistable(CHRScope *Scope) { 864 RegInfo &RI = Scope->RegInfos[0]; 865 Region *R = RI.R; 866 BasicBlock *EntryBB = R->getEntry(); 867 auto *Branch = RI.HasBranch ? 868 cast<BranchInst>(EntryBB->getTerminator()) : nullptr; 869 SmallVector<SelectInst *, 8> &Selects = RI.Selects; 870 if (RI.HasBranch || !Selects.empty()) { 871 Instruction *InsertPoint = getBranchInsertPoint(RI); 872 CHR_DEBUG(dbgs() << "InsertPoint " << *InsertPoint << "\n"); 873 // Avoid a data dependence from a select or a branch to a(nother) 874 // select. Note no instruction can't data-depend on a branch (a branch 875 // instruction doesn't produce a value). 876 DenseSet<Instruction *> Unhoistables; 877 // Initialize Unhoistables with the selects. 878 for (SelectInst *SI : Selects) { 879 Unhoistables.insert(SI); 880 } 881 // Remove Selects that can't be hoisted. 882 for (auto it = Selects.begin(); it != Selects.end(); ) { 883 SelectInst *SI = *it; 884 if (SI == InsertPoint) { 885 ++it; 886 continue; 887 } 888 DenseMap<Instruction *, bool> Visited; 889 bool IsHoistable = checkHoistValue(SI->getCondition(), InsertPoint, 890 DT, Unhoistables, nullptr, Visited); 891 if (!IsHoistable) { 892 CHR_DEBUG(dbgs() << "Dropping select " << *SI << "\n"); 893 ORE.emit([&]() { 894 return OptimizationRemarkMissed(DEBUG_TYPE, 895 "DropUnhoistableSelect", SI) 896 << "Dropped unhoistable select"; 897 }); 898 it = Selects.erase(it); 899 // Since we are dropping the select here, we also drop it from 900 // Unhoistables. 901 Unhoistables.erase(SI); 902 } else 903 ++it; 904 } 905 // Update InsertPoint after potentially removing selects. 906 InsertPoint = getBranchInsertPoint(RI); 907 CHR_DEBUG(dbgs() << "InsertPoint " << *InsertPoint << "\n"); 908 if (RI.HasBranch && InsertPoint != Branch) { 909 DenseMap<Instruction *, bool> Visited; 910 bool IsHoistable = checkHoistValue(Branch->getCondition(), InsertPoint, 911 DT, Unhoistables, nullptr, Visited); 912 if (!IsHoistable) { 913 // If the branch isn't hoistable, drop the selects in the entry 914 // block, preferring the branch, which makes the branch the hoist 915 // point. 916 assert(InsertPoint != Branch && "Branch must not be the hoist point"); 917 CHR_DEBUG(dbgs() << "Dropping selects in entry block \n"); 918 CHR_DEBUG( 919 for (SelectInst *SI : Selects) { 920 dbgs() << "SI " << *SI << "\n"; 921 }); 922 for (SelectInst *SI : Selects) { 923 ORE.emit([&]() { 924 return OptimizationRemarkMissed(DEBUG_TYPE, 925 "DropSelectUnhoistableBranch", SI) 926 << "Dropped select due to unhoistable branch"; 927 }); 928 } 929 llvm::erase_if(Selects, [EntryBB](SelectInst *SI) { 930 return SI->getParent() == EntryBB; 931 }); 932 Unhoistables.clear(); 933 InsertPoint = Branch; 934 } 935 } 936 CHR_DEBUG(dbgs() << "InsertPoint " << *InsertPoint << "\n"); 937 #ifndef NDEBUG 938 if (RI.HasBranch) { 939 assert(!DT.dominates(Branch, InsertPoint) && 940 "Branch can't be already above the hoist point"); 941 DenseMap<Instruction *, bool> Visited; 942 assert(checkHoistValue(Branch->getCondition(), InsertPoint, 943 DT, Unhoistables, nullptr, Visited) && 944 "checkHoistValue for branch"); 945 } 946 for (auto *SI : Selects) { 947 assert(!DT.dominates(SI, InsertPoint) && 948 "SI can't be already above the hoist point"); 949 DenseMap<Instruction *, bool> Visited; 950 assert(checkHoistValue(SI->getCondition(), InsertPoint, DT, 951 Unhoistables, nullptr, Visited) && 952 "checkHoistValue for selects"); 953 } 954 CHR_DEBUG(dbgs() << "Result\n"); 955 if (RI.HasBranch) { 956 CHR_DEBUG(dbgs() << "BI " << *Branch << "\n"); 957 } 958 for (auto *SI : Selects) { 959 CHR_DEBUG(dbgs() << "SI " << *SI << "\n"); 960 } 961 #endif 962 } 963 } 964 965 // Traverse the region tree, find all nested scopes and merge them if possible. 966 CHRScope * CHR::findScopes(Region *R, Region *NextRegion, Region *ParentRegion, 967 SmallVectorImpl<CHRScope *> &Scopes) { 968 CHR_DEBUG(dbgs() << "findScopes " << R->getNameStr() << "\n"); 969 CHRScope *Result = findScope(R); 970 // Visit subscopes. 971 CHRScope *ConsecutiveSubscope = nullptr; 972 SmallVector<CHRScope *, 8> Subscopes; 973 for (auto It = R->begin(); It != R->end(); ++It) { 974 const std::unique_ptr<Region> &SubR = *It; 975 auto NextIt = std::next(It); 976 Region *NextSubR = NextIt != R->end() ? NextIt->get() : nullptr; 977 CHR_DEBUG(dbgs() << "Looking at subregion " << SubR.get()->getNameStr() 978 << "\n"); 979 CHRScope *SubCHRScope = findScopes(SubR.get(), NextSubR, R, Scopes); 980 if (SubCHRScope) { 981 CHR_DEBUG(dbgs() << "Subregion Scope " << *SubCHRScope << "\n"); 982 } else { 983 CHR_DEBUG(dbgs() << "Subregion Scope null\n"); 984 } 985 if (SubCHRScope) { 986 if (!ConsecutiveSubscope) 987 ConsecutiveSubscope = SubCHRScope; 988 else if (!ConsecutiveSubscope->appendable(SubCHRScope)) { 989 Subscopes.push_back(ConsecutiveSubscope); 990 ConsecutiveSubscope = SubCHRScope; 991 } else 992 ConsecutiveSubscope->append(SubCHRScope); 993 } else { 994 if (ConsecutiveSubscope) { 995 Subscopes.push_back(ConsecutiveSubscope); 996 } 997 ConsecutiveSubscope = nullptr; 998 } 999 } 1000 if (ConsecutiveSubscope) { 1001 Subscopes.push_back(ConsecutiveSubscope); 1002 } 1003 for (CHRScope *Sub : Subscopes) { 1004 if (Result) { 1005 // Combine it with the parent. 1006 Result->addSub(Sub); 1007 } else { 1008 // Push Subscopes as they won't be combined with the parent. 1009 Scopes.push_back(Sub); 1010 } 1011 } 1012 return Result; 1013 } 1014 1015 static DenseSet<Value *> getCHRConditionValuesForRegion(RegInfo &RI) { 1016 DenseSet<Value *> ConditionValues; 1017 if (RI.HasBranch) { 1018 auto *BI = cast<BranchInst>(RI.R->getEntry()->getTerminator()); 1019 ConditionValues.insert(BI->getCondition()); 1020 } 1021 for (SelectInst *SI : RI.Selects) { 1022 ConditionValues.insert(SI->getCondition()); 1023 } 1024 return ConditionValues; 1025 } 1026 1027 1028 // Determine whether to split a scope depending on the sets of the branch 1029 // condition values of the previous region and the current region. We split 1030 // (return true) it if 1) the condition values of the inner/lower scope can't be 1031 // hoisted up to the outer/upper scope, or 2) the two sets of the condition 1032 // values have an empty intersection (because the combined branch conditions 1033 // won't probably lead to a simpler combined condition). 1034 static bool shouldSplit(Instruction *InsertPoint, 1035 DenseSet<Value *> &PrevConditionValues, 1036 DenseSet<Value *> &ConditionValues, 1037 DominatorTree &DT, 1038 DenseSet<Instruction *> &Unhoistables) { 1039 assert(InsertPoint && "Null InsertPoint"); 1040 CHR_DEBUG( 1041 dbgs() << "shouldSplit " << *InsertPoint << " PrevConditionValues "; 1042 for (Value *V : PrevConditionValues) { 1043 dbgs() << *V << ", "; 1044 } 1045 dbgs() << " ConditionValues "; 1046 for (Value *V : ConditionValues) { 1047 dbgs() << *V << ", "; 1048 } 1049 dbgs() << "\n"); 1050 // If any of Bases isn't hoistable to the hoist point, split. 1051 for (Value *V : ConditionValues) { 1052 DenseMap<Instruction *, bool> Visited; 1053 if (!checkHoistValue(V, InsertPoint, DT, Unhoistables, nullptr, Visited)) { 1054 CHR_DEBUG(dbgs() << "Split. checkHoistValue false " << *V << "\n"); 1055 return true; // Not hoistable, split. 1056 } 1057 } 1058 // If PrevConditionValues or ConditionValues is empty, don't split to avoid 1059 // unnecessary splits at scopes with no branch/selects. If 1060 // PrevConditionValues and ConditionValues don't intersect at all, split. 1061 if (!PrevConditionValues.empty() && !ConditionValues.empty()) { 1062 // Use std::set as DenseSet doesn't work with set_intersection. 1063 std::set<Value *> PrevBases, Bases; 1064 DenseMap<Value *, std::set<Value *>> Visited; 1065 for (Value *V : PrevConditionValues) { 1066 const std::set<Value *> &BaseValues = getBaseValues(V, DT, Visited); 1067 PrevBases.insert(BaseValues.begin(), BaseValues.end()); 1068 } 1069 for (Value *V : ConditionValues) { 1070 const std::set<Value *> &BaseValues = getBaseValues(V, DT, Visited); 1071 Bases.insert(BaseValues.begin(), BaseValues.end()); 1072 } 1073 CHR_DEBUG( 1074 dbgs() << "PrevBases "; 1075 for (Value *V : PrevBases) { 1076 dbgs() << *V << ", "; 1077 } 1078 dbgs() << " Bases "; 1079 for (Value *V : Bases) { 1080 dbgs() << *V << ", "; 1081 } 1082 dbgs() << "\n"); 1083 std::vector<Value *> Intersection; 1084 std::set_intersection(PrevBases.begin(), PrevBases.end(), Bases.begin(), 1085 Bases.end(), std::back_inserter(Intersection)); 1086 if (Intersection.empty()) { 1087 // Empty intersection, split. 1088 CHR_DEBUG(dbgs() << "Split. Intersection empty\n"); 1089 return true; 1090 } 1091 } 1092 CHR_DEBUG(dbgs() << "No split\n"); 1093 return false; // Don't split. 1094 } 1095 1096 static void getSelectsInScope(CHRScope *Scope, 1097 DenseSet<Instruction *> &Output) { 1098 for (RegInfo &RI : Scope->RegInfos) 1099 for (SelectInst *SI : RI.Selects) 1100 Output.insert(SI); 1101 for (CHRScope *Sub : Scope->Subs) 1102 getSelectsInScope(Sub, Output); 1103 } 1104 1105 void CHR::splitScopes(SmallVectorImpl<CHRScope *> &Input, 1106 SmallVectorImpl<CHRScope *> &Output) { 1107 for (CHRScope *Scope : Input) { 1108 assert(!Scope->BranchInsertPoint && 1109 "BranchInsertPoint must not be set"); 1110 DenseSet<Instruction *> Unhoistables; 1111 getSelectsInScope(Scope, Unhoistables); 1112 splitScope(Scope, nullptr, nullptr, nullptr, Output, Unhoistables); 1113 } 1114 #ifndef NDEBUG 1115 for (CHRScope *Scope : Output) { 1116 assert(Scope->BranchInsertPoint && "BranchInsertPoint must be set"); 1117 } 1118 #endif 1119 } 1120 1121 SmallVector<CHRScope *, 8> CHR::splitScope( 1122 CHRScope *Scope, 1123 CHRScope *Outer, 1124 DenseSet<Value *> *OuterConditionValues, 1125 Instruction *OuterInsertPoint, 1126 SmallVectorImpl<CHRScope *> &Output, 1127 DenseSet<Instruction *> &Unhoistables) { 1128 if (Outer) { 1129 assert(OuterConditionValues && "Null OuterConditionValues"); 1130 assert(OuterInsertPoint && "Null OuterInsertPoint"); 1131 } 1132 bool PrevSplitFromOuter = true; 1133 DenseSet<Value *> PrevConditionValues; 1134 Instruction *PrevInsertPoint = nullptr; 1135 SmallVector<CHRScope *, 8> Splits; 1136 SmallVector<bool, 8> SplitsSplitFromOuter; 1137 SmallVector<DenseSet<Value *>, 8> SplitsConditionValues; 1138 SmallVector<Instruction *, 8> SplitsInsertPoints; 1139 SmallVector<RegInfo, 8> RegInfos(Scope->RegInfos); // Copy 1140 for (RegInfo &RI : RegInfos) { 1141 Instruction *InsertPoint = getBranchInsertPoint(RI); 1142 DenseSet<Value *> ConditionValues = getCHRConditionValuesForRegion(RI); 1143 CHR_DEBUG( 1144 dbgs() << "ConditionValues "; 1145 for (Value *V : ConditionValues) { 1146 dbgs() << *V << ", "; 1147 } 1148 dbgs() << "\n"); 1149 if (RI.R == RegInfos[0].R) { 1150 // First iteration. Check to see if we should split from the outer. 1151 if (Outer) { 1152 CHR_DEBUG(dbgs() << "Outer " << *Outer << "\n"); 1153 CHR_DEBUG(dbgs() << "Should split from outer at " 1154 << RI.R->getNameStr() << "\n"); 1155 if (shouldSplit(OuterInsertPoint, *OuterConditionValues, 1156 ConditionValues, DT, Unhoistables)) { 1157 PrevConditionValues = ConditionValues; 1158 PrevInsertPoint = InsertPoint; 1159 ORE.emit([&]() { 1160 return OptimizationRemarkMissed(DEBUG_TYPE, 1161 "SplitScopeFromOuter", 1162 RI.R->getEntry()->getTerminator()) 1163 << "Split scope from outer due to unhoistable branch/select " 1164 << "and/or lack of common condition values"; 1165 }); 1166 } else { 1167 // Not splitting from the outer. Use the outer bases and insert 1168 // point. Union the bases. 1169 PrevSplitFromOuter = false; 1170 PrevConditionValues = *OuterConditionValues; 1171 PrevConditionValues.insert(ConditionValues.begin(), 1172 ConditionValues.end()); 1173 PrevInsertPoint = OuterInsertPoint; 1174 } 1175 } else { 1176 CHR_DEBUG(dbgs() << "Outer null\n"); 1177 PrevConditionValues = ConditionValues; 1178 PrevInsertPoint = InsertPoint; 1179 } 1180 } else { 1181 CHR_DEBUG(dbgs() << "Should split from prev at " 1182 << RI.R->getNameStr() << "\n"); 1183 if (shouldSplit(PrevInsertPoint, PrevConditionValues, ConditionValues, 1184 DT, Unhoistables)) { 1185 CHRScope *Tail = Scope->split(RI.R); 1186 Scopes.insert(Tail); 1187 Splits.push_back(Scope); 1188 SplitsSplitFromOuter.push_back(PrevSplitFromOuter); 1189 SplitsConditionValues.push_back(PrevConditionValues); 1190 SplitsInsertPoints.push_back(PrevInsertPoint); 1191 Scope = Tail; 1192 PrevConditionValues = ConditionValues; 1193 PrevInsertPoint = InsertPoint; 1194 PrevSplitFromOuter = true; 1195 ORE.emit([&]() { 1196 return OptimizationRemarkMissed(DEBUG_TYPE, 1197 "SplitScopeFromPrev", 1198 RI.R->getEntry()->getTerminator()) 1199 << "Split scope from previous due to unhoistable branch/select " 1200 << "and/or lack of common condition values"; 1201 }); 1202 } else { 1203 // Not splitting. Union the bases. Keep the hoist point. 1204 PrevConditionValues.insert(ConditionValues.begin(), ConditionValues.end()); 1205 } 1206 } 1207 } 1208 Splits.push_back(Scope); 1209 SplitsSplitFromOuter.push_back(PrevSplitFromOuter); 1210 SplitsConditionValues.push_back(PrevConditionValues); 1211 assert(PrevInsertPoint && "Null PrevInsertPoint"); 1212 SplitsInsertPoints.push_back(PrevInsertPoint); 1213 assert(Splits.size() == SplitsConditionValues.size() && 1214 Splits.size() == SplitsSplitFromOuter.size() && 1215 Splits.size() == SplitsInsertPoints.size() && "Mismatching sizes"); 1216 for (size_t I = 0; I < Splits.size(); ++I) { 1217 CHRScope *Split = Splits[I]; 1218 DenseSet<Value *> &SplitConditionValues = SplitsConditionValues[I]; 1219 Instruction *SplitInsertPoint = SplitsInsertPoints[I]; 1220 SmallVector<CHRScope *, 8> NewSubs; 1221 DenseSet<Instruction *> SplitUnhoistables; 1222 getSelectsInScope(Split, SplitUnhoistables); 1223 for (CHRScope *Sub : Split->Subs) { 1224 SmallVector<CHRScope *, 8> SubSplits = splitScope( 1225 Sub, Split, &SplitConditionValues, SplitInsertPoint, Output, 1226 SplitUnhoistables); 1227 llvm::append_range(NewSubs, SubSplits); 1228 } 1229 Split->Subs = NewSubs; 1230 } 1231 SmallVector<CHRScope *, 8> Result; 1232 for (size_t I = 0; I < Splits.size(); ++I) { 1233 CHRScope *Split = Splits[I]; 1234 if (SplitsSplitFromOuter[I]) { 1235 // Split from the outer. 1236 Output.push_back(Split); 1237 Split->BranchInsertPoint = SplitsInsertPoints[I]; 1238 CHR_DEBUG(dbgs() << "BranchInsertPoint " << *SplitsInsertPoints[I] 1239 << "\n"); 1240 } else { 1241 // Connected to the outer. 1242 Result.push_back(Split); 1243 } 1244 } 1245 if (!Outer) 1246 assert(Result.empty() && 1247 "If no outer (top-level), must return no nested ones"); 1248 return Result; 1249 } 1250 1251 void CHR::classifyBiasedScopes(SmallVectorImpl<CHRScope *> &Scopes) { 1252 for (CHRScope *Scope : Scopes) { 1253 assert(Scope->TrueBiasedRegions.empty() && Scope->FalseBiasedRegions.empty() && "Empty"); 1254 classifyBiasedScopes(Scope, Scope); 1255 CHR_DEBUG( 1256 dbgs() << "classifyBiasedScopes " << *Scope << "\n"; 1257 dbgs() << "TrueBiasedRegions "; 1258 for (Region *R : Scope->TrueBiasedRegions) { 1259 dbgs() << R->getNameStr() << ", "; 1260 } 1261 dbgs() << "\n"; 1262 dbgs() << "FalseBiasedRegions "; 1263 for (Region *R : Scope->FalseBiasedRegions) { 1264 dbgs() << R->getNameStr() << ", "; 1265 } 1266 dbgs() << "\n"; 1267 dbgs() << "TrueBiasedSelects "; 1268 for (SelectInst *SI : Scope->TrueBiasedSelects) { 1269 dbgs() << *SI << ", "; 1270 } 1271 dbgs() << "\n"; 1272 dbgs() << "FalseBiasedSelects "; 1273 for (SelectInst *SI : Scope->FalseBiasedSelects) { 1274 dbgs() << *SI << ", "; 1275 } 1276 dbgs() << "\n";); 1277 } 1278 } 1279 1280 void CHR::classifyBiasedScopes(CHRScope *Scope, CHRScope *OutermostScope) { 1281 for (RegInfo &RI : Scope->RegInfos) { 1282 if (RI.HasBranch) { 1283 Region *R = RI.R; 1284 if (TrueBiasedRegionsGlobal.contains(R)) 1285 OutermostScope->TrueBiasedRegions.insert(R); 1286 else if (FalseBiasedRegionsGlobal.contains(R)) 1287 OutermostScope->FalseBiasedRegions.insert(R); 1288 else 1289 llvm_unreachable("Must be biased"); 1290 } 1291 for (SelectInst *SI : RI.Selects) { 1292 if (TrueBiasedSelectsGlobal.contains(SI)) 1293 OutermostScope->TrueBiasedSelects.insert(SI); 1294 else if (FalseBiasedSelectsGlobal.contains(SI)) 1295 OutermostScope->FalseBiasedSelects.insert(SI); 1296 else 1297 llvm_unreachable("Must be biased"); 1298 } 1299 } 1300 for (CHRScope *Sub : Scope->Subs) { 1301 classifyBiasedScopes(Sub, OutermostScope); 1302 } 1303 } 1304 1305 static bool hasAtLeastTwoBiasedBranches(CHRScope *Scope) { 1306 unsigned NumBiased = Scope->TrueBiasedRegions.size() + 1307 Scope->FalseBiasedRegions.size() + 1308 Scope->TrueBiasedSelects.size() + 1309 Scope->FalseBiasedSelects.size(); 1310 return NumBiased >= CHRMergeThreshold; 1311 } 1312 1313 void CHR::filterScopes(SmallVectorImpl<CHRScope *> &Input, 1314 SmallVectorImpl<CHRScope *> &Output) { 1315 for (CHRScope *Scope : Input) { 1316 // Filter out the ones with only one region and no subs. 1317 if (!hasAtLeastTwoBiasedBranches(Scope)) { 1318 CHR_DEBUG(dbgs() << "Filtered out by biased branches truthy-regions " 1319 << Scope->TrueBiasedRegions.size() 1320 << " falsy-regions " << Scope->FalseBiasedRegions.size() 1321 << " true-selects " << Scope->TrueBiasedSelects.size() 1322 << " false-selects " << Scope->FalseBiasedSelects.size() << "\n"); 1323 ORE.emit([&]() { 1324 return OptimizationRemarkMissed( 1325 DEBUG_TYPE, 1326 "DropScopeWithOneBranchOrSelect", 1327 Scope->RegInfos[0].R->getEntry()->getTerminator()) 1328 << "Drop scope with < " 1329 << ore::NV("CHRMergeThreshold", CHRMergeThreshold) 1330 << " biased branch(es) or select(s)"; 1331 }); 1332 continue; 1333 } 1334 Output.push_back(Scope); 1335 } 1336 } 1337 1338 void CHR::setCHRRegions(SmallVectorImpl<CHRScope *> &Input, 1339 SmallVectorImpl<CHRScope *> &Output) { 1340 for (CHRScope *Scope : Input) { 1341 assert(Scope->HoistStopMap.empty() && Scope->CHRRegions.empty() && 1342 "Empty"); 1343 setCHRRegions(Scope, Scope); 1344 Output.push_back(Scope); 1345 CHR_DEBUG( 1346 dbgs() << "setCHRRegions HoistStopMap " << *Scope << "\n"; 1347 for (auto pair : Scope->HoistStopMap) { 1348 Region *R = pair.first; 1349 dbgs() << "Region " << R->getNameStr() << "\n"; 1350 for (Instruction *I : pair.second) { 1351 dbgs() << "HoistStop " << *I << "\n"; 1352 } 1353 } 1354 dbgs() << "CHRRegions" << "\n"; 1355 for (RegInfo &RI : Scope->CHRRegions) { 1356 dbgs() << RI.R->getNameStr() << "\n"; 1357 }); 1358 } 1359 } 1360 1361 void CHR::setCHRRegions(CHRScope *Scope, CHRScope *OutermostScope) { 1362 DenseSet<Instruction *> Unhoistables; 1363 // Put the biased selects in Unhoistables because they should stay where they 1364 // are and constant-folded after CHR (in case one biased select or a branch 1365 // can depend on another biased select.) 1366 for (RegInfo &RI : Scope->RegInfos) { 1367 for (SelectInst *SI : RI.Selects) { 1368 Unhoistables.insert(SI); 1369 } 1370 } 1371 Instruction *InsertPoint = OutermostScope->BranchInsertPoint; 1372 for (RegInfo &RI : Scope->RegInfos) { 1373 Region *R = RI.R; 1374 DenseSet<Instruction *> HoistStops; 1375 bool IsHoisted = false; 1376 if (RI.HasBranch) { 1377 assert((OutermostScope->TrueBiasedRegions.contains(R) || 1378 OutermostScope->FalseBiasedRegions.contains(R)) && 1379 "Must be truthy or falsy"); 1380 auto *BI = cast<BranchInst>(R->getEntry()->getTerminator()); 1381 // Note checkHoistValue fills in HoistStops. 1382 DenseMap<Instruction *, bool> Visited; 1383 bool IsHoistable = checkHoistValue(BI->getCondition(), InsertPoint, DT, 1384 Unhoistables, &HoistStops, Visited); 1385 assert(IsHoistable && "Must be hoistable"); 1386 (void)(IsHoistable); // Unused in release build 1387 IsHoisted = true; 1388 } 1389 for (SelectInst *SI : RI.Selects) { 1390 assert((OutermostScope->TrueBiasedSelects.contains(SI) || 1391 OutermostScope->FalseBiasedSelects.contains(SI)) && 1392 "Must be true or false biased"); 1393 // Note checkHoistValue fills in HoistStops. 1394 DenseMap<Instruction *, bool> Visited; 1395 bool IsHoistable = checkHoistValue(SI->getCondition(), InsertPoint, DT, 1396 Unhoistables, &HoistStops, Visited); 1397 assert(IsHoistable && "Must be hoistable"); 1398 (void)(IsHoistable); // Unused in release build 1399 IsHoisted = true; 1400 } 1401 if (IsHoisted) { 1402 OutermostScope->CHRRegions.push_back(RI); 1403 OutermostScope->HoistStopMap[R] = HoistStops; 1404 } 1405 } 1406 for (CHRScope *Sub : Scope->Subs) 1407 setCHRRegions(Sub, OutermostScope); 1408 } 1409 1410 static bool CHRScopeSorter(CHRScope *Scope1, CHRScope *Scope2) { 1411 return Scope1->RegInfos[0].R->getDepth() < Scope2->RegInfos[0].R->getDepth(); 1412 } 1413 1414 void CHR::sortScopes(SmallVectorImpl<CHRScope *> &Input, 1415 SmallVectorImpl<CHRScope *> &Output) { 1416 Output.resize(Input.size()); 1417 llvm::copy(Input, Output.begin()); 1418 llvm::stable_sort(Output, CHRScopeSorter); 1419 } 1420 1421 // Return true if V is already hoisted or was hoisted (along with its operands) 1422 // to the insert point. 1423 static void hoistValue(Value *V, Instruction *HoistPoint, Region *R, 1424 HoistStopMapTy &HoistStopMap, 1425 DenseSet<Instruction *> &HoistedSet, 1426 DenseSet<PHINode *> &TrivialPHIs, 1427 DominatorTree &DT) { 1428 auto IT = HoistStopMap.find(R); 1429 assert(IT != HoistStopMap.end() && "Region must be in hoist stop map"); 1430 DenseSet<Instruction *> &HoistStops = IT->second; 1431 if (auto *I = dyn_cast<Instruction>(V)) { 1432 if (I == HoistPoint) 1433 return; 1434 if (HoistStops.count(I)) 1435 return; 1436 if (auto *PN = dyn_cast<PHINode>(I)) 1437 if (TrivialPHIs.count(PN)) 1438 // The trivial phi inserted by the previous CHR scope could replace a 1439 // non-phi in HoistStops. Note that since this phi is at the exit of a 1440 // previous CHR scope, which dominates this scope, it's safe to stop 1441 // hoisting there. 1442 return; 1443 if (HoistedSet.count(I)) 1444 // Already hoisted, return. 1445 return; 1446 assert(isHoistableInstructionType(I) && "Unhoistable instruction type"); 1447 assert(DT.getNode(I->getParent()) && "DT must contain I's block"); 1448 assert(DT.getNode(HoistPoint->getParent()) && 1449 "DT must contain HoistPoint block"); 1450 if (DT.dominates(I, HoistPoint)) 1451 // We are already above the hoist point. Stop here. This may be necessary 1452 // when multiple scopes would independently hoist the same 1453 // instruction. Since an outer (dominating) scope would hoist it to its 1454 // entry before an inner (dominated) scope would to its entry, the inner 1455 // scope may see the instruction already hoisted, in which case it 1456 // potentially wrong for the inner scope to hoist it and could cause bad 1457 // IR (non-dominating def), but safe to skip hoisting it instead because 1458 // it's already in a block that dominates the inner scope. 1459 return; 1460 for (Value *Op : I->operands()) { 1461 hoistValue(Op, HoistPoint, R, HoistStopMap, HoistedSet, TrivialPHIs, DT); 1462 } 1463 I->moveBefore(HoistPoint); 1464 HoistedSet.insert(I); 1465 CHR_DEBUG(dbgs() << "hoistValue " << *I << "\n"); 1466 } 1467 } 1468 1469 // Hoist the dependent condition values of the branches and the selects in the 1470 // scope to the insert point. 1471 static void hoistScopeConditions(CHRScope *Scope, Instruction *HoistPoint, 1472 DenseSet<PHINode *> &TrivialPHIs, 1473 DominatorTree &DT) { 1474 DenseSet<Instruction *> HoistedSet; 1475 for (const RegInfo &RI : Scope->CHRRegions) { 1476 Region *R = RI.R; 1477 bool IsTrueBiased = Scope->TrueBiasedRegions.count(R); 1478 bool IsFalseBiased = Scope->FalseBiasedRegions.count(R); 1479 if (RI.HasBranch && (IsTrueBiased || IsFalseBiased)) { 1480 auto *BI = cast<BranchInst>(R->getEntry()->getTerminator()); 1481 hoistValue(BI->getCondition(), HoistPoint, R, Scope->HoistStopMap, 1482 HoistedSet, TrivialPHIs, DT); 1483 } 1484 for (SelectInst *SI : RI.Selects) { 1485 bool IsTrueBiased = Scope->TrueBiasedSelects.count(SI); 1486 bool IsFalseBiased = Scope->FalseBiasedSelects.count(SI); 1487 if (!(IsTrueBiased || IsFalseBiased)) 1488 continue; 1489 hoistValue(SI->getCondition(), HoistPoint, R, Scope->HoistStopMap, 1490 HoistedSet, TrivialPHIs, DT); 1491 } 1492 } 1493 } 1494 1495 // Negate the predicate if an ICmp if it's used only by branches or selects by 1496 // swapping the operands of the branches or the selects. Returns true if success. 1497 static bool negateICmpIfUsedByBranchOrSelectOnly(ICmpInst *ICmp, 1498 Instruction *ExcludedUser, 1499 CHRScope *Scope) { 1500 for (User *U : ICmp->users()) { 1501 if (U == ExcludedUser) 1502 continue; 1503 if (isa<BranchInst>(U) && cast<BranchInst>(U)->isConditional()) 1504 continue; 1505 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == ICmp) 1506 continue; 1507 return false; 1508 } 1509 for (User *U : ICmp->users()) { 1510 if (U == ExcludedUser) 1511 continue; 1512 if (auto *BI = dyn_cast<BranchInst>(U)) { 1513 assert(BI->isConditional() && "Must be conditional"); 1514 BI->swapSuccessors(); 1515 // Don't need to swap this in terms of 1516 // TrueBiasedRegions/FalseBiasedRegions because true-based/false-based 1517 // mean whehter the branch is likely go into the if-then rather than 1518 // successor0/successor1 and because we can tell which edge is the then or 1519 // the else one by comparing the destination to the region exit block. 1520 continue; 1521 } 1522 if (auto *SI = dyn_cast<SelectInst>(U)) { 1523 // Swap operands 1524 SI->swapValues(); 1525 SI->swapProfMetadata(); 1526 if (Scope->TrueBiasedSelects.count(SI)) { 1527 assert(!Scope->FalseBiasedSelects.contains(SI) && 1528 "Must not be already in"); 1529 Scope->FalseBiasedSelects.insert(SI); 1530 } else if (Scope->FalseBiasedSelects.count(SI)) { 1531 assert(!Scope->TrueBiasedSelects.contains(SI) && 1532 "Must not be already in"); 1533 Scope->TrueBiasedSelects.insert(SI); 1534 } 1535 continue; 1536 } 1537 llvm_unreachable("Must be a branch or a select"); 1538 } 1539 ICmp->setPredicate(CmpInst::getInversePredicate(ICmp->getPredicate())); 1540 return true; 1541 } 1542 1543 // A helper for transformScopes. Insert a trivial phi at the scope exit block 1544 // for a value that's defined in the scope but used outside it (meaning it's 1545 // alive at the exit block). 1546 static void insertTrivialPHIs(CHRScope *Scope, 1547 BasicBlock *EntryBlock, BasicBlock *ExitBlock, 1548 DenseSet<PHINode *> &TrivialPHIs) { 1549 SmallSetVector<BasicBlock *, 8> BlocksInScope; 1550 for (RegInfo &RI : Scope->RegInfos) { 1551 for (BasicBlock *BB : RI.R->blocks()) { // This includes the blocks in the 1552 // sub-Scopes. 1553 BlocksInScope.insert(BB); 1554 } 1555 } 1556 CHR_DEBUG({ 1557 dbgs() << "Inserting redundant phis\n"; 1558 for (BasicBlock *BB : BlocksInScope) 1559 dbgs() << "BlockInScope " << BB->getName() << "\n"; 1560 }); 1561 for (BasicBlock *BB : BlocksInScope) { 1562 for (Instruction &I : *BB) { 1563 SmallVector<Instruction *, 8> Users; 1564 for (User *U : I.users()) { 1565 if (auto *UI = dyn_cast<Instruction>(U)) { 1566 if (!BlocksInScope.contains(UI->getParent()) && 1567 // Unless there's already a phi for I at the exit block. 1568 !(isa<PHINode>(UI) && UI->getParent() == ExitBlock)) { 1569 CHR_DEBUG(dbgs() << "V " << I << "\n"); 1570 CHR_DEBUG(dbgs() << "Used outside scope by user " << *UI << "\n"); 1571 Users.push_back(UI); 1572 } else if (UI->getParent() == EntryBlock && isa<PHINode>(UI)) { 1573 // There's a loop backedge from a block that's dominated by this 1574 // scope to the entry block. 1575 CHR_DEBUG(dbgs() << "V " << I << "\n"); 1576 CHR_DEBUG(dbgs() 1577 << "Used at entry block (for a back edge) by a phi user " 1578 << *UI << "\n"); 1579 Users.push_back(UI); 1580 } 1581 } 1582 } 1583 if (Users.size() > 0) { 1584 // Insert a trivial phi for I (phi [&I, P0], [&I, P1], ...) at 1585 // ExitBlock. Replace I with the new phi in UI unless UI is another 1586 // phi at ExitBlock. 1587 PHINode *PN = PHINode::Create(I.getType(), pred_size(ExitBlock), "", 1588 &ExitBlock->front()); 1589 for (BasicBlock *Pred : predecessors(ExitBlock)) { 1590 PN->addIncoming(&I, Pred); 1591 } 1592 TrivialPHIs.insert(PN); 1593 CHR_DEBUG(dbgs() << "Insert phi " << *PN << "\n"); 1594 for (Instruction *UI : Users) { 1595 for (unsigned J = 0, NumOps = UI->getNumOperands(); J < NumOps; ++J) { 1596 if (UI->getOperand(J) == &I) { 1597 UI->setOperand(J, PN); 1598 } 1599 } 1600 CHR_DEBUG(dbgs() << "Updated user " << *UI << "\n"); 1601 } 1602 } 1603 } 1604 } 1605 } 1606 1607 // Assert that all the CHR regions of the scope have a biased branch or select. 1608 static void LLVM_ATTRIBUTE_UNUSED 1609 assertCHRRegionsHaveBiasedBranchOrSelect(CHRScope *Scope) { 1610 #ifndef NDEBUG 1611 auto HasBiasedBranchOrSelect = [](RegInfo &RI, CHRScope *Scope) { 1612 if (Scope->TrueBiasedRegions.count(RI.R) || 1613 Scope->FalseBiasedRegions.count(RI.R)) 1614 return true; 1615 for (SelectInst *SI : RI.Selects) 1616 if (Scope->TrueBiasedSelects.count(SI) || 1617 Scope->FalseBiasedSelects.count(SI)) 1618 return true; 1619 return false; 1620 }; 1621 for (RegInfo &RI : Scope->CHRRegions) { 1622 assert(HasBiasedBranchOrSelect(RI, Scope) && 1623 "Must have biased branch or select"); 1624 } 1625 #endif 1626 } 1627 1628 // Assert that all the condition values of the biased branches and selects have 1629 // been hoisted to the pre-entry block or outside of the scope. 1630 static void LLVM_ATTRIBUTE_UNUSED assertBranchOrSelectConditionHoisted( 1631 CHRScope *Scope, BasicBlock *PreEntryBlock) { 1632 CHR_DEBUG(dbgs() << "Biased regions condition values \n"); 1633 for (RegInfo &RI : Scope->CHRRegions) { 1634 Region *R = RI.R; 1635 bool IsTrueBiased = Scope->TrueBiasedRegions.count(R); 1636 bool IsFalseBiased = Scope->FalseBiasedRegions.count(R); 1637 if (RI.HasBranch && (IsTrueBiased || IsFalseBiased)) { 1638 auto *BI = cast<BranchInst>(R->getEntry()->getTerminator()); 1639 Value *V = BI->getCondition(); 1640 CHR_DEBUG(dbgs() << *V << "\n"); 1641 if (auto *I = dyn_cast<Instruction>(V)) { 1642 (void)(I); // Unused in release build. 1643 assert((I->getParent() == PreEntryBlock || 1644 !Scope->contains(I)) && 1645 "Must have been hoisted to PreEntryBlock or outside the scope"); 1646 } 1647 } 1648 for (SelectInst *SI : RI.Selects) { 1649 bool IsTrueBiased = Scope->TrueBiasedSelects.count(SI); 1650 bool IsFalseBiased = Scope->FalseBiasedSelects.count(SI); 1651 if (!(IsTrueBiased || IsFalseBiased)) 1652 continue; 1653 Value *V = SI->getCondition(); 1654 CHR_DEBUG(dbgs() << *V << "\n"); 1655 if (auto *I = dyn_cast<Instruction>(V)) { 1656 (void)(I); // Unused in release build. 1657 assert((I->getParent() == PreEntryBlock || 1658 !Scope->contains(I)) && 1659 "Must have been hoisted to PreEntryBlock or outside the scope"); 1660 } 1661 } 1662 } 1663 } 1664 1665 void CHR::transformScopes(CHRScope *Scope, DenseSet<PHINode *> &TrivialPHIs) { 1666 CHR_DEBUG(dbgs() << "transformScopes " << *Scope << "\n"); 1667 1668 assert(Scope->RegInfos.size() >= 1 && "Should have at least one Region"); 1669 Region *FirstRegion = Scope->RegInfos[0].R; 1670 BasicBlock *EntryBlock = FirstRegion->getEntry(); 1671 Region *LastRegion = Scope->RegInfos[Scope->RegInfos.size() - 1].R; 1672 BasicBlock *ExitBlock = LastRegion->getExit(); 1673 Optional<uint64_t> ProfileCount = BFI.getBlockProfileCount(EntryBlock); 1674 1675 if (ExitBlock) { 1676 // Insert a trivial phi at the exit block (where the CHR hot path and the 1677 // cold path merges) for a value that's defined in the scope but used 1678 // outside it (meaning it's alive at the exit block). We will add the 1679 // incoming values for the CHR cold paths to it below. Without this, we'd 1680 // miss updating phi's for such values unless there happens to already be a 1681 // phi for that value there. 1682 insertTrivialPHIs(Scope, EntryBlock, ExitBlock, TrivialPHIs); 1683 } 1684 1685 // Split the entry block of the first region. The new block becomes the new 1686 // entry block of the first region. The old entry block becomes the block to 1687 // insert the CHR branch into. Note DT gets updated. Since DT gets updated 1688 // through the split, we update the entry of the first region after the split, 1689 // and Region only points to the entry and the exit blocks, rather than 1690 // keeping everything in a list or set, the blocks membership and the 1691 // entry/exit blocks of the region are still valid after the split. 1692 CHR_DEBUG(dbgs() << "Splitting entry block " << EntryBlock->getName() 1693 << " at " << *Scope->BranchInsertPoint << "\n"); 1694 BasicBlock *NewEntryBlock = 1695 SplitBlock(EntryBlock, Scope->BranchInsertPoint, &DT); 1696 assert(NewEntryBlock->getSinglePredecessor() == EntryBlock && 1697 "NewEntryBlock's only pred must be EntryBlock"); 1698 FirstRegion->replaceEntryRecursive(NewEntryBlock); 1699 BasicBlock *PreEntryBlock = EntryBlock; 1700 1701 ValueToValueMapTy VMap; 1702 // Clone the blocks in the scope (excluding the PreEntryBlock) to split into a 1703 // hot path (originals) and a cold path (clones) and update the PHIs at the 1704 // exit block. 1705 cloneScopeBlocks(Scope, PreEntryBlock, ExitBlock, LastRegion, VMap); 1706 1707 // Replace the old (placeholder) branch with the new (merged) conditional 1708 // branch. 1709 BranchInst *MergedBr = createMergedBranch(PreEntryBlock, EntryBlock, 1710 NewEntryBlock, VMap); 1711 1712 #ifndef NDEBUG 1713 assertCHRRegionsHaveBiasedBranchOrSelect(Scope); 1714 #endif 1715 1716 // Hoist the conditional values of the branches/selects. 1717 hoistScopeConditions(Scope, PreEntryBlock->getTerminator(), TrivialPHIs, DT); 1718 1719 #ifndef NDEBUG 1720 assertBranchOrSelectConditionHoisted(Scope, PreEntryBlock); 1721 #endif 1722 1723 // Create the combined branch condition and constant-fold the branches/selects 1724 // in the hot path. 1725 fixupBranchesAndSelects(Scope, PreEntryBlock, MergedBr, 1726 ProfileCount.value_or(0)); 1727 } 1728 1729 // A helper for transformScopes. Clone the blocks in the scope (excluding the 1730 // PreEntryBlock) to split into a hot path and a cold path and update the PHIs 1731 // at the exit block. 1732 void CHR::cloneScopeBlocks(CHRScope *Scope, 1733 BasicBlock *PreEntryBlock, 1734 BasicBlock *ExitBlock, 1735 Region *LastRegion, 1736 ValueToValueMapTy &VMap) { 1737 // Clone all the blocks. The original blocks will be the hot-path 1738 // CHR-optimized code and the cloned blocks will be the original unoptimized 1739 // code. This is so that the block pointers from the 1740 // CHRScope/Region/RegionInfo can stay valid in pointing to the hot-path code 1741 // which CHR should apply to. 1742 SmallVector<BasicBlock*, 8> NewBlocks; 1743 for (RegInfo &RI : Scope->RegInfos) 1744 for (BasicBlock *BB : RI.R->blocks()) { // This includes the blocks in the 1745 // sub-Scopes. 1746 assert(BB != PreEntryBlock && "Don't copy the preetntry block"); 1747 BasicBlock *NewBB = CloneBasicBlock(BB, VMap, ".nonchr", &F); 1748 NewBlocks.push_back(NewBB); 1749 VMap[BB] = NewBB; 1750 } 1751 1752 // Place the cloned blocks right after the original blocks (right before the 1753 // exit block of.) 1754 if (ExitBlock) 1755 F.getBasicBlockList().splice(ExitBlock->getIterator(), 1756 F.getBasicBlockList(), 1757 NewBlocks[0]->getIterator(), F.end()); 1758 1759 // Update the cloned blocks/instructions to refer to themselves. 1760 for (BasicBlock *NewBB : NewBlocks) 1761 for (Instruction &I : *NewBB) 1762 RemapInstruction(&I, VMap, 1763 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 1764 1765 // Add the cloned blocks to the PHIs of the exit blocks. ExitBlock is null for 1766 // the top-level region but we don't need to add PHIs. The trivial PHIs 1767 // inserted above will be updated here. 1768 if (ExitBlock) 1769 for (PHINode &PN : ExitBlock->phis()) 1770 for (unsigned I = 0, NumOps = PN.getNumIncomingValues(); I < NumOps; 1771 ++I) { 1772 BasicBlock *Pred = PN.getIncomingBlock(I); 1773 if (LastRegion->contains(Pred)) { 1774 Value *V = PN.getIncomingValue(I); 1775 auto It = VMap.find(V); 1776 if (It != VMap.end()) V = It->second; 1777 assert(VMap.find(Pred) != VMap.end() && "Pred must have been cloned"); 1778 PN.addIncoming(V, cast<BasicBlock>(VMap[Pred])); 1779 } 1780 } 1781 } 1782 1783 // A helper for transformScope. Replace the old (placeholder) branch with the 1784 // new (merged) conditional branch. 1785 BranchInst *CHR::createMergedBranch(BasicBlock *PreEntryBlock, 1786 BasicBlock *EntryBlock, 1787 BasicBlock *NewEntryBlock, 1788 ValueToValueMapTy &VMap) { 1789 BranchInst *OldBR = cast<BranchInst>(PreEntryBlock->getTerminator()); 1790 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == NewEntryBlock && 1791 "SplitBlock did not work correctly!"); 1792 assert(NewEntryBlock->getSinglePredecessor() == EntryBlock && 1793 "NewEntryBlock's only pred must be EntryBlock"); 1794 assert(VMap.find(NewEntryBlock) != VMap.end() && 1795 "NewEntryBlock must have been copied"); 1796 OldBR->dropAllReferences(); 1797 OldBR->eraseFromParent(); 1798 // The true predicate is a placeholder. It will be replaced later in 1799 // fixupBranchesAndSelects(). 1800 BranchInst *NewBR = BranchInst::Create(NewEntryBlock, 1801 cast<BasicBlock>(VMap[NewEntryBlock]), 1802 ConstantInt::getTrue(F.getContext())); 1803 PreEntryBlock->getInstList().push_back(NewBR); 1804 assert(NewEntryBlock->getSinglePredecessor() == EntryBlock && 1805 "NewEntryBlock's only pred must be EntryBlock"); 1806 return NewBR; 1807 } 1808 1809 // A helper for transformScopes. Create the combined branch condition and 1810 // constant-fold the branches/selects in the hot path. 1811 void CHR::fixupBranchesAndSelects(CHRScope *Scope, 1812 BasicBlock *PreEntryBlock, 1813 BranchInst *MergedBR, 1814 uint64_t ProfileCount) { 1815 Value *MergedCondition = ConstantInt::getTrue(F.getContext()); 1816 BranchProbability CHRBranchBias(1, 1); 1817 uint64_t NumCHRedBranches = 0; 1818 IRBuilder<> IRB(PreEntryBlock->getTerminator()); 1819 for (RegInfo &RI : Scope->CHRRegions) { 1820 Region *R = RI.R; 1821 if (RI.HasBranch) { 1822 fixupBranch(R, Scope, IRB, MergedCondition, CHRBranchBias); 1823 ++NumCHRedBranches; 1824 } 1825 for (SelectInst *SI : RI.Selects) { 1826 fixupSelect(SI, Scope, IRB, MergedCondition, CHRBranchBias); 1827 ++NumCHRedBranches; 1828 } 1829 } 1830 Stats.NumBranchesDelta += NumCHRedBranches - 1; 1831 Stats.WeightedNumBranchesDelta += (NumCHRedBranches - 1) * ProfileCount; 1832 ORE.emit([&]() { 1833 return OptimizationRemark(DEBUG_TYPE, 1834 "CHR", 1835 // Refer to the hot (original) path 1836 MergedBR->getSuccessor(0)->getTerminator()) 1837 << "Merged " << ore::NV("NumCHRedBranches", NumCHRedBranches) 1838 << " branches or selects"; 1839 }); 1840 MergedBR->setCondition(MergedCondition); 1841 uint32_t Weights[] = { 1842 static_cast<uint32_t>(CHRBranchBias.scale(1000)), 1843 static_cast<uint32_t>(CHRBranchBias.getCompl().scale(1000)), 1844 }; 1845 MDBuilder MDB(F.getContext()); 1846 MergedBR->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights)); 1847 CHR_DEBUG(dbgs() << "CHR branch bias " << Weights[0] << ":" << Weights[1] 1848 << "\n"); 1849 } 1850 1851 // A helper for fixupBranchesAndSelects. Add to the combined branch condition 1852 // and constant-fold a branch in the hot path. 1853 void CHR::fixupBranch(Region *R, CHRScope *Scope, 1854 IRBuilder<> &IRB, 1855 Value *&MergedCondition, 1856 BranchProbability &CHRBranchBias) { 1857 bool IsTrueBiased = Scope->TrueBiasedRegions.count(R); 1858 assert((IsTrueBiased || Scope->FalseBiasedRegions.count(R)) && 1859 "Must be truthy or falsy"); 1860 auto *BI = cast<BranchInst>(R->getEntry()->getTerminator()); 1861 assert(BranchBiasMap.find(R) != BranchBiasMap.end() && 1862 "Must be in the bias map"); 1863 BranchProbability Bias = BranchBiasMap[R]; 1864 assert(Bias >= getCHRBiasThreshold() && "Must be highly biased"); 1865 // Take the min. 1866 if (CHRBranchBias > Bias) 1867 CHRBranchBias = Bias; 1868 BasicBlock *IfThen = BI->getSuccessor(1); 1869 BasicBlock *IfElse = BI->getSuccessor(0); 1870 BasicBlock *RegionExitBlock = R->getExit(); 1871 assert(RegionExitBlock && "Null ExitBlock"); 1872 assert((IfThen == RegionExitBlock || IfElse == RegionExitBlock) && 1873 IfThen != IfElse && "Invariant from findScopes"); 1874 if (IfThen == RegionExitBlock) { 1875 // Swap them so that IfThen means going into it and IfElse means skipping 1876 // it. 1877 std::swap(IfThen, IfElse); 1878 } 1879 CHR_DEBUG(dbgs() << "IfThen " << IfThen->getName() 1880 << " IfElse " << IfElse->getName() << "\n"); 1881 Value *Cond = BI->getCondition(); 1882 BasicBlock *HotTarget = IsTrueBiased ? IfThen : IfElse; 1883 bool ConditionTrue = HotTarget == BI->getSuccessor(0); 1884 addToMergedCondition(ConditionTrue, Cond, BI, Scope, IRB, 1885 MergedCondition); 1886 // Constant-fold the branch at ClonedEntryBlock. 1887 assert(ConditionTrue == (HotTarget == BI->getSuccessor(0)) && 1888 "The successor shouldn't change"); 1889 Value *NewCondition = ConditionTrue ? 1890 ConstantInt::getTrue(F.getContext()) : 1891 ConstantInt::getFalse(F.getContext()); 1892 BI->setCondition(NewCondition); 1893 } 1894 1895 // A helper for fixupBranchesAndSelects. Add to the combined branch condition 1896 // and constant-fold a select in the hot path. 1897 void CHR::fixupSelect(SelectInst *SI, CHRScope *Scope, 1898 IRBuilder<> &IRB, 1899 Value *&MergedCondition, 1900 BranchProbability &CHRBranchBias) { 1901 bool IsTrueBiased = Scope->TrueBiasedSelects.count(SI); 1902 assert((IsTrueBiased || 1903 Scope->FalseBiasedSelects.count(SI)) && "Must be biased"); 1904 assert(SelectBiasMap.find(SI) != SelectBiasMap.end() && 1905 "Must be in the bias map"); 1906 BranchProbability Bias = SelectBiasMap[SI]; 1907 assert(Bias >= getCHRBiasThreshold() && "Must be highly biased"); 1908 // Take the min. 1909 if (CHRBranchBias > Bias) 1910 CHRBranchBias = Bias; 1911 Value *Cond = SI->getCondition(); 1912 addToMergedCondition(IsTrueBiased, Cond, SI, Scope, IRB, 1913 MergedCondition); 1914 Value *NewCondition = IsTrueBiased ? 1915 ConstantInt::getTrue(F.getContext()) : 1916 ConstantInt::getFalse(F.getContext()); 1917 SI->setCondition(NewCondition); 1918 } 1919 1920 // A helper for fixupBranch/fixupSelect. Add a branch condition to the merged 1921 // condition. 1922 void CHR::addToMergedCondition(bool IsTrueBiased, Value *Cond, 1923 Instruction *BranchOrSelect, CHRScope *Scope, 1924 IRBuilder<> &IRB, Value *&MergedCondition) { 1925 if (!IsTrueBiased) { 1926 // If Cond is an icmp and all users of V except for BranchOrSelect is a 1927 // branch, negate the icmp predicate and swap the branch targets and avoid 1928 // inserting an Xor to negate Cond. 1929 auto *ICmp = dyn_cast<ICmpInst>(Cond); 1930 if (!ICmp || 1931 !negateICmpIfUsedByBranchOrSelectOnly(ICmp, BranchOrSelect, Scope)) 1932 Cond = IRB.CreateXor(ConstantInt::getTrue(F.getContext()), Cond); 1933 } 1934 1935 // Select conditions can be poison, while branching on poison is immediate 1936 // undefined behavior. As such, we need to freeze potentially poisonous 1937 // conditions derived from selects. 1938 if (isa<SelectInst>(BranchOrSelect) && 1939 !isGuaranteedNotToBeUndefOrPoison(Cond)) 1940 Cond = IRB.CreateFreeze(Cond); 1941 1942 // Use logical and to avoid propagating poison from later conditions. 1943 MergedCondition = IRB.CreateLogicalAnd(MergedCondition, Cond); 1944 } 1945 1946 void CHR::transformScopes(SmallVectorImpl<CHRScope *> &CHRScopes) { 1947 unsigned I = 0; 1948 DenseSet<PHINode *> TrivialPHIs; 1949 for (CHRScope *Scope : CHRScopes) { 1950 transformScopes(Scope, TrivialPHIs); 1951 CHR_DEBUG( 1952 std::ostringstream oss; 1953 oss << " after transformScopes " << I++; 1954 dumpIR(F, oss.str().c_str(), nullptr)); 1955 (void)I; 1956 } 1957 } 1958 1959 static void LLVM_ATTRIBUTE_UNUSED 1960 dumpScopes(SmallVectorImpl<CHRScope *> &Scopes, const char *Label) { 1961 dbgs() << Label << " " << Scopes.size() << "\n"; 1962 for (CHRScope *Scope : Scopes) { 1963 dbgs() << *Scope << "\n"; 1964 } 1965 } 1966 1967 bool CHR::run() { 1968 if (!shouldApply(F, PSI)) 1969 return false; 1970 1971 CHR_DEBUG(dumpIR(F, "before", nullptr)); 1972 1973 bool Changed = false; 1974 { 1975 CHR_DEBUG( 1976 dbgs() << "RegionInfo:\n"; 1977 RI.print(dbgs())); 1978 1979 // Recursively traverse the region tree and find regions that have biased 1980 // branches and/or selects and create scopes. 1981 SmallVector<CHRScope *, 8> AllScopes; 1982 findScopes(AllScopes); 1983 CHR_DEBUG(dumpScopes(AllScopes, "All scopes")); 1984 1985 // Split the scopes if 1) the conditional values of the biased 1986 // branches/selects of the inner/lower scope can't be hoisted up to the 1987 // outermost/uppermost scope entry, or 2) the condition values of the biased 1988 // branches/selects in a scope (including subscopes) don't share at least 1989 // one common value. 1990 SmallVector<CHRScope *, 8> SplitScopes; 1991 splitScopes(AllScopes, SplitScopes); 1992 CHR_DEBUG(dumpScopes(SplitScopes, "Split scopes")); 1993 1994 // After splitting, set the biased regions and selects of a scope (a tree 1995 // root) that include those of the subscopes. 1996 classifyBiasedScopes(SplitScopes); 1997 CHR_DEBUG(dbgs() << "Set per-scope bias " << SplitScopes.size() << "\n"); 1998 1999 // Filter out the scopes that has only one biased region or select (CHR 2000 // isn't useful in such a case). 2001 SmallVector<CHRScope *, 8> FilteredScopes; 2002 filterScopes(SplitScopes, FilteredScopes); 2003 CHR_DEBUG(dumpScopes(FilteredScopes, "Filtered scopes")); 2004 2005 // Set the regions to be CHR'ed and their hoist stops for each scope. 2006 SmallVector<CHRScope *, 8> SetScopes; 2007 setCHRRegions(FilteredScopes, SetScopes); 2008 CHR_DEBUG(dumpScopes(SetScopes, "Set CHR regions")); 2009 2010 // Sort CHRScopes by the depth so that outer CHRScopes comes before inner 2011 // ones. We need to apply CHR from outer to inner so that we apply CHR only 2012 // to the hot path, rather than both hot and cold paths. 2013 SmallVector<CHRScope *, 8> SortedScopes; 2014 sortScopes(SetScopes, SortedScopes); 2015 CHR_DEBUG(dumpScopes(SortedScopes, "Sorted scopes")); 2016 2017 CHR_DEBUG( 2018 dbgs() << "RegionInfo:\n"; 2019 RI.print(dbgs())); 2020 2021 // Apply the CHR transformation. 2022 if (!SortedScopes.empty()) { 2023 transformScopes(SortedScopes); 2024 Changed = true; 2025 } 2026 } 2027 2028 if (Changed) { 2029 CHR_DEBUG(dumpIR(F, "after", &Stats)); 2030 ORE.emit([&]() { 2031 return OptimizationRemark(DEBUG_TYPE, "Stats", &F) 2032 << ore::NV("Function", &F) << " " 2033 << "Reduced the number of branches in hot paths by " 2034 << ore::NV("NumBranchesDelta", Stats.NumBranchesDelta) 2035 << " (static) and " 2036 << ore::NV("WeightedNumBranchesDelta", Stats.WeightedNumBranchesDelta) 2037 << " (weighted by PGO count)"; 2038 }); 2039 } 2040 2041 return Changed; 2042 } 2043 2044 namespace llvm { 2045 2046 ControlHeightReductionPass::ControlHeightReductionPass() { 2047 parseCHRFilterFiles(); 2048 } 2049 2050 PreservedAnalyses ControlHeightReductionPass::run( 2051 Function &F, 2052 FunctionAnalysisManager &FAM) { 2053 auto &BFI = FAM.getResult<BlockFrequencyAnalysis>(F); 2054 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F); 2055 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F); 2056 auto &PSI = *MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent()); 2057 auto &RI = FAM.getResult<RegionInfoAnalysis>(F); 2058 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 2059 bool Changed = CHR(F, BFI, DT, PSI, RI, ORE).run(); 2060 if (!Changed) 2061 return PreservedAnalyses::all(); 2062 return PreservedAnalyses::none(); 2063 } 2064 2065 } // namespace llvm 2066