Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Instrumentation/ControlHeightReduction.cpp
35266 views
//===-- ControlHeightReduction.cpp - Control Height Reduction -------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This pass merges conditional blocks of code and reduces the number of9// conditional branches in the hot paths based on profiles.10//11//===----------------------------------------------------------------------===//1213#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"14#include "llvm/ADT/DenseMap.h"15#include "llvm/ADT/DenseSet.h"16#include "llvm/ADT/SmallVector.h"17#include "llvm/ADT/StringSet.h"18#include "llvm/Analysis/BlockFrequencyInfo.h"19#include "llvm/Analysis/GlobalsModRef.h"20#include "llvm/Analysis/OptimizationRemarkEmitter.h"21#include "llvm/Analysis/ProfileSummaryInfo.h"22#include "llvm/Analysis/RegionInfo.h"23#include "llvm/Analysis/RegionIterator.h"24#include "llvm/Analysis/ValueTracking.h"25#include "llvm/IR/CFG.h"26#include "llvm/IR/Dominators.h"27#include "llvm/IR/IRBuilder.h"28#include "llvm/IR/IntrinsicInst.h"29#include "llvm/IR/MDBuilder.h"30#include "llvm/IR/Module.h"31#include "llvm/IR/PassManager.h"32#include "llvm/IR/ProfDataUtils.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"4041#include <optional>42#include <set>43#include <sstream>4445using namespace llvm;4647#define DEBUG_TYPE "chr"4849#define CHR_DEBUG(X) LLVM_DEBUG(X)5051static cl::opt<bool> DisableCHR("disable-chr", cl::init(false), cl::Hidden,52cl::desc("Disable CHR for all functions"));5354static cl::opt<bool> ForceCHR("force-chr", cl::init(false), cl::Hidden,55cl::desc("Apply CHR for all functions"));5657static cl::opt<double> CHRBiasThreshold(58"chr-bias-threshold", cl::init(0.99), cl::Hidden,59cl::desc("CHR considers a branch bias greater than this ratio as biased"));6061static cl::opt<unsigned> CHRMergeThreshold(62"chr-merge-threshold", cl::init(2), cl::Hidden,63cl::desc("CHR merges a group of N branches/selects where N >= this value"));6465static cl::opt<std::string> CHRModuleList(66"chr-module-list", cl::init(""), cl::Hidden,67cl::desc("Specify file to retrieve the list of modules to apply CHR to"));6869static cl::opt<std::string> CHRFunctionList(70"chr-function-list", cl::init(""), cl::Hidden,71cl::desc("Specify file to retrieve the list of functions to apply CHR to"));7273static cl::opt<unsigned> CHRDupThreshsold(74"chr-dup-threshold", cl::init(3), cl::Hidden,75cl::desc("Max number of duplications by CHR for a region"));7677static StringSet<> CHRModules;78static StringSet<> CHRFunctions;7980static void parseCHRFilterFiles() {81if (!CHRModuleList.empty()) {82auto FileOrErr = MemoryBuffer::getFile(CHRModuleList);83if (!FileOrErr) {84errs() << "Error: Couldn't read the chr-module-list file " << CHRModuleList << "\n";85std::exit(1);86}87StringRef Buf = FileOrErr->get()->getBuffer();88SmallVector<StringRef, 0> Lines;89Buf.split(Lines, '\n');90for (StringRef Line : Lines) {91Line = Line.trim();92if (!Line.empty())93CHRModules.insert(Line);94}95}96if (!CHRFunctionList.empty()) {97auto FileOrErr = MemoryBuffer::getFile(CHRFunctionList);98if (!FileOrErr) {99errs() << "Error: Couldn't read the chr-function-list file " << CHRFunctionList << "\n";100std::exit(1);101}102StringRef Buf = FileOrErr->get()->getBuffer();103SmallVector<StringRef, 0> Lines;104Buf.split(Lines, '\n');105for (StringRef Line : Lines) {106Line = Line.trim();107if (!Line.empty())108CHRFunctions.insert(Line);109}110}111}112113namespace {114115struct CHRStats {116CHRStats() = default;117void print(raw_ostream &OS) const {118OS << "CHRStats: NumBranches " << NumBranches119<< " NumBranchesDelta " << NumBranchesDelta120<< " WeightedNumBranchesDelta " << WeightedNumBranchesDelta;121}122// The original number of conditional branches / selects123uint64_t NumBranches = 0;124// The decrease of the number of conditional branches / selects in the hot125// paths due to CHR.126uint64_t NumBranchesDelta = 0;127// NumBranchesDelta weighted by the profile count at the scope entry.128uint64_t WeightedNumBranchesDelta = 0;129};130131// RegInfo - some properties of a Region.132struct RegInfo {133RegInfo() = default;134RegInfo(Region *RegionIn) : R(RegionIn) {}135Region *R = nullptr;136bool HasBranch = false;137SmallVector<SelectInst *, 8> Selects;138};139140typedef DenseMap<Region *, DenseSet<Instruction *>> HoistStopMapTy;141142// CHRScope - a sequence of regions to CHR together. It corresponds to a143// sequence of conditional blocks. It can have subscopes which correspond to144// nested conditional blocks. Nested CHRScopes form a tree.145class CHRScope {146public:147CHRScope(RegInfo RI) : BranchInsertPoint(nullptr) {148assert(RI.R && "Null RegionIn");149RegInfos.push_back(RI);150}151152Region *getParentRegion() {153assert(RegInfos.size() > 0 && "Empty CHRScope");154Region *Parent = RegInfos[0].R->getParent();155assert(Parent && "Unexpected to call this on the top-level region");156return Parent;157}158159BasicBlock *getEntryBlock() {160assert(RegInfos.size() > 0 && "Empty CHRScope");161return RegInfos.front().R->getEntry();162}163164BasicBlock *getExitBlock() {165assert(RegInfos.size() > 0 && "Empty CHRScope");166return RegInfos.back().R->getExit();167}168169bool appendable(CHRScope *Next) {170// The next scope is appendable only if this scope is directly connected to171// it (which implies it post-dominates this scope) and this scope dominates172// it (no edge to the next scope outside this scope).173BasicBlock *NextEntry = Next->getEntryBlock();174if (getExitBlock() != NextEntry)175// Not directly connected.176return false;177Region *LastRegion = RegInfos.back().R;178for (BasicBlock *Pred : predecessors(NextEntry))179if (!LastRegion->contains(Pred))180// There's an edge going into the entry of the next scope from outside181// of this scope.182return false;183return true;184}185186void append(CHRScope *Next) {187assert(RegInfos.size() > 0 && "Empty CHRScope");188assert(Next->RegInfos.size() > 0 && "Empty CHRScope");189assert(getParentRegion() == Next->getParentRegion() &&190"Must be siblings");191assert(getExitBlock() == Next->getEntryBlock() &&192"Must be adjacent");193RegInfos.append(Next->RegInfos.begin(), Next->RegInfos.end());194Subs.append(Next->Subs.begin(), Next->Subs.end());195}196197void addSub(CHRScope *SubIn) {198#ifndef NDEBUG199bool IsChild = false;200for (RegInfo &RI : RegInfos)201if (RI.R == SubIn->getParentRegion()) {202IsChild = true;203break;204}205assert(IsChild && "Must be a child");206#endif207Subs.push_back(SubIn);208}209210// Split this scope at the boundary region into two, which will belong to the211// tail and returns the tail.212CHRScope *split(Region *Boundary) {213assert(Boundary && "Boundary null");214assert(RegInfos.begin()->R != Boundary &&215"Can't be split at beginning");216auto BoundaryIt = llvm::find_if(217RegInfos, [&Boundary](const RegInfo &RI) { return Boundary == RI.R; });218if (BoundaryIt == RegInfos.end())219return nullptr;220ArrayRef<RegInfo> TailRegInfos(BoundaryIt, RegInfos.end());221DenseSet<Region *> TailRegionSet;222for (const RegInfo &RI : TailRegInfos)223TailRegionSet.insert(RI.R);224225auto TailIt =226std::stable_partition(Subs.begin(), Subs.end(), [&](CHRScope *Sub) {227assert(Sub && "null Sub");228Region *Parent = Sub->getParentRegion();229if (TailRegionSet.count(Parent))230return false;231232assert(llvm::any_of(233RegInfos,234[&Parent](const RegInfo &RI) { return Parent == RI.R; }) &&235"Must be in head");236return true;237});238ArrayRef<CHRScope *> TailSubs(TailIt, Subs.end());239240assert(HoistStopMap.empty() && "MapHoistStops must be empty");241auto *Scope = new CHRScope(TailRegInfos, TailSubs);242RegInfos.erase(BoundaryIt, RegInfos.end());243Subs.erase(TailIt, Subs.end());244return Scope;245}246247bool contains(Instruction *I) const {248BasicBlock *Parent = I->getParent();249for (const RegInfo &RI : RegInfos)250if (RI.R->contains(Parent))251return true;252return false;253}254255void print(raw_ostream &OS) const;256257SmallVector<RegInfo, 8> RegInfos; // Regions that belong to this scope258SmallVector<CHRScope *, 8> Subs; // Subscopes.259260// The instruction at which to insert the CHR conditional branch (and hoist261// the dependent condition values).262Instruction *BranchInsertPoint;263264// True-biased and false-biased regions (conditional blocks),265// respectively. Used only for the outermost scope and includes regions in266// subscopes. The rest are unbiased.267DenseSet<Region *> TrueBiasedRegions;268DenseSet<Region *> FalseBiasedRegions;269// Among the biased regions, the regions that get CHRed.270SmallVector<RegInfo, 8> CHRRegions;271272// True-biased and false-biased selects, respectively. Used only for the273// outermost scope and includes ones in subscopes.274DenseSet<SelectInst *> TrueBiasedSelects;275DenseSet<SelectInst *> FalseBiasedSelects;276277// Map from one of the above regions to the instructions to stop278// hoisting instructions at through use-def chains.279HoistStopMapTy HoistStopMap;280281private:282CHRScope(ArrayRef<RegInfo> RegInfosIn, ArrayRef<CHRScope *> SubsIn)283: RegInfos(RegInfosIn.begin(), RegInfosIn.end()),284Subs(SubsIn.begin(), SubsIn.end()), BranchInsertPoint(nullptr) {}285};286287class CHR {288public:289CHR(Function &Fin, BlockFrequencyInfo &BFIin, DominatorTree &DTin,290ProfileSummaryInfo &PSIin, RegionInfo &RIin,291OptimizationRemarkEmitter &OREin)292: F(Fin), BFI(BFIin), DT(DTin), PSI(PSIin), RI(RIin), ORE(OREin) {}293294~CHR() {295for (CHRScope *Scope : Scopes) {296delete Scope;297}298}299300bool run();301302private:303// See the comments in CHR::run() for the high level flow of the algorithm and304// what the following functions do.305306void findScopes(SmallVectorImpl<CHRScope *> &Output) {307Region *R = RI.getTopLevelRegion();308if (CHRScope *Scope = findScopes(R, nullptr, nullptr, Output)) {309Output.push_back(Scope);310}311}312CHRScope *findScopes(Region *R, Region *NextRegion, Region *ParentRegion,313SmallVectorImpl<CHRScope *> &Scopes);314CHRScope *findScope(Region *R);315void checkScopeHoistable(CHRScope *Scope);316317void splitScopes(SmallVectorImpl<CHRScope *> &Input,318SmallVectorImpl<CHRScope *> &Output);319SmallVector<CHRScope *, 8> splitScope(CHRScope *Scope,320CHRScope *Outer,321DenseSet<Value *> *OuterConditionValues,322Instruction *OuterInsertPoint,323SmallVectorImpl<CHRScope *> &Output,324DenseSet<Instruction *> &Unhoistables);325326void classifyBiasedScopes(SmallVectorImpl<CHRScope *> &Scopes);327void classifyBiasedScopes(CHRScope *Scope, CHRScope *OutermostScope);328329void filterScopes(SmallVectorImpl<CHRScope *> &Input,330SmallVectorImpl<CHRScope *> &Output);331332void setCHRRegions(SmallVectorImpl<CHRScope *> &Input,333SmallVectorImpl<CHRScope *> &Output);334void setCHRRegions(CHRScope *Scope, CHRScope *OutermostScope);335336void sortScopes(SmallVectorImpl<CHRScope *> &Input,337SmallVectorImpl<CHRScope *> &Output);338339void transformScopes(SmallVectorImpl<CHRScope *> &CHRScopes);340void transformScopes(CHRScope *Scope, DenseSet<PHINode *> &TrivialPHIs);341void cloneScopeBlocks(CHRScope *Scope,342BasicBlock *PreEntryBlock,343BasicBlock *ExitBlock,344Region *LastRegion,345ValueToValueMapTy &VMap);346BranchInst *createMergedBranch(BasicBlock *PreEntryBlock,347BasicBlock *EntryBlock,348BasicBlock *NewEntryBlock,349ValueToValueMapTy &VMap);350void fixupBranchesAndSelects(CHRScope *Scope, BasicBlock *PreEntryBlock,351BranchInst *MergedBR, uint64_t ProfileCount);352void fixupBranch(Region *R, CHRScope *Scope, IRBuilder<> &IRB,353Value *&MergedCondition, BranchProbability &CHRBranchBias);354void fixupSelect(SelectInst *SI, CHRScope *Scope, IRBuilder<> &IRB,355Value *&MergedCondition, BranchProbability &CHRBranchBias);356void addToMergedCondition(bool IsTrueBiased, Value *Cond,357Instruction *BranchOrSelect, CHRScope *Scope,358IRBuilder<> &IRB, Value *&MergedCondition);359unsigned getRegionDuplicationCount(const Region *R) {360unsigned Count = 0;361// Find out how many times region R is cloned. Note that if the parent362// of R is cloned, R is also cloned, but R's clone count is not updated363// from the clone of the parent. We need to accumlate all the counts364// from the ancestors to get the clone count.365while (R) {366Count += DuplicationCount[R];367R = R->getParent();368}369return Count;370}371372Function &F;373BlockFrequencyInfo &BFI;374DominatorTree &DT;375ProfileSummaryInfo &PSI;376RegionInfo &RI;377OptimizationRemarkEmitter &ORE;378CHRStats Stats;379380// All the true-biased regions in the function381DenseSet<Region *> TrueBiasedRegionsGlobal;382// All the false-biased regions in the function383DenseSet<Region *> FalseBiasedRegionsGlobal;384// All the true-biased selects in the function385DenseSet<SelectInst *> TrueBiasedSelectsGlobal;386// All the false-biased selects in the function387DenseSet<SelectInst *> FalseBiasedSelectsGlobal;388// A map from biased regions to their branch bias389DenseMap<Region *, BranchProbability> BranchBiasMap;390// A map from biased selects to their branch bias391DenseMap<SelectInst *, BranchProbability> SelectBiasMap;392// All the scopes.393DenseSet<CHRScope *> Scopes;394// This maps records how many times this region is cloned.395DenseMap<const Region *, unsigned> DuplicationCount;396};397398} // end anonymous namespace399400static inline401raw_ostream LLVM_ATTRIBUTE_UNUSED &operator<<(raw_ostream &OS,402const CHRStats &Stats) {403Stats.print(OS);404return OS;405}406407static inline408raw_ostream &operator<<(raw_ostream &OS, const CHRScope &Scope) {409Scope.print(OS);410return OS;411}412413static bool shouldApply(Function &F, ProfileSummaryInfo &PSI) {414if (DisableCHR)415return false;416417if (ForceCHR)418return true;419420if (!CHRModuleList.empty() || !CHRFunctionList.empty()) {421if (CHRModules.count(F.getParent()->getName()))422return true;423return CHRFunctions.count(F.getName());424}425426return PSI.isFunctionEntryHot(&F);427}428429static void LLVM_ATTRIBUTE_UNUSED dumpIR(Function &F, const char *Label,430CHRStats *Stats) {431StringRef FuncName = F.getName();432StringRef ModuleName = F.getParent()->getName();433(void)(FuncName); // Unused in release build.434(void)(ModuleName); // Unused in release build.435CHR_DEBUG(dbgs() << "CHR IR dump " << Label << " " << ModuleName << " "436<< FuncName);437if (Stats)438CHR_DEBUG(dbgs() << " " << *Stats);439CHR_DEBUG(dbgs() << "\n");440CHR_DEBUG(F.dump());441}442443void CHRScope::print(raw_ostream &OS) const {444assert(RegInfos.size() > 0 && "Empty CHRScope");445OS << "CHRScope[";446OS << RegInfos.size() << ", Regions[";447for (const RegInfo &RI : RegInfos) {448OS << RI.R->getNameStr();449if (RI.HasBranch)450OS << " B";451if (RI.Selects.size() > 0)452OS << " S" << RI.Selects.size();453OS << ", ";454}455if (RegInfos[0].R->getParent()) {456OS << "], Parent " << RegInfos[0].R->getParent()->getNameStr();457} else {458// top level region459OS << "]";460}461OS << ", Subs[";462for (CHRScope *Sub : Subs) {463OS << *Sub << ", ";464}465OS << "]]";466}467468// Return true if the given instruction type can be hoisted by CHR.469static bool isHoistableInstructionType(Instruction *I) {470return isa<BinaryOperator>(I) || isa<CastInst>(I) || isa<SelectInst>(I) ||471isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||472isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||473isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) ||474isa<InsertValueInst>(I);475}476477// Return true if the given instruction can be hoisted by CHR.478static bool isHoistable(Instruction *I, DominatorTree &DT) {479if (!isHoistableInstructionType(I))480return false;481return isSafeToSpeculativelyExecute(I, nullptr, nullptr, &DT);482}483484// Recursively traverse the use-def chains of the given value and return a set485// of the unhoistable base values defined within the scope (excluding the486// first-region entry block) or the (hoistable or unhoistable) base values that487// are defined outside (including the first-region entry block) of the488// scope. The returned set doesn't include constants.489static const std::set<Value *> &490getBaseValues(Value *V, DominatorTree &DT,491DenseMap<Value *, std::set<Value *>> &Visited) {492auto It = Visited.find(V);493if (It != Visited.end()) {494return It->second;495}496std::set<Value *> Result;497if (auto *I = dyn_cast<Instruction>(V)) {498// We don't stop at a block that's not in the Scope because we would miss499// some instructions that are based on the same base values if we stop500// there.501if (!isHoistable(I, DT)) {502Result.insert(I);503return Visited.insert(std::make_pair(V, std::move(Result))).first->second;504}505// I is hoistable above the Scope.506for (Value *Op : I->operands()) {507const std::set<Value *> &OpResult = getBaseValues(Op, DT, Visited);508Result.insert(OpResult.begin(), OpResult.end());509}510return Visited.insert(std::make_pair(V, std::move(Result))).first->second;511}512if (isa<Argument>(V)) {513Result.insert(V);514}515// We don't include others like constants because those won't lead to any516// chance of folding of conditions (eg two bit checks merged into one check)517// after CHR.518return Visited.insert(std::make_pair(V, std::move(Result))).first->second;519}520521// Return true if V is already hoisted or can be hoisted (along with its522// operands) above the insert point. When it returns true and HoistStops is523// non-null, the instructions to stop hoisting at through the use-def chains are524// inserted into HoistStops.525static bool526checkHoistValue(Value *V, Instruction *InsertPoint, DominatorTree &DT,527DenseSet<Instruction *> &Unhoistables,528DenseSet<Instruction *> *HoistStops,529DenseMap<Instruction *, bool> &Visited) {530assert(InsertPoint && "Null InsertPoint");531if (auto *I = dyn_cast<Instruction>(V)) {532auto It = Visited.find(I);533if (It != Visited.end()) {534return It->second;535}536assert(DT.getNode(I->getParent()) && "DT must contain I's parent block");537assert(DT.getNode(InsertPoint->getParent()) && "DT must contain Destination");538if (Unhoistables.count(I)) {539// Don't hoist if they are not to be hoisted.540Visited[I] = false;541return false;542}543if (DT.dominates(I, InsertPoint)) {544// We are already above the insert point. Stop here.545if (HoistStops)546HoistStops->insert(I);547Visited[I] = true;548return true;549}550// We aren't not above the insert point, check if we can hoist it above the551// insert point.552if (isHoistable(I, DT)) {553// Check operands first.554DenseSet<Instruction *> OpsHoistStops;555bool AllOpsHoisted = true;556for (Value *Op : I->operands()) {557if (!checkHoistValue(Op, InsertPoint, DT, Unhoistables, &OpsHoistStops,558Visited)) {559AllOpsHoisted = false;560break;561}562}563if (AllOpsHoisted) {564CHR_DEBUG(dbgs() << "checkHoistValue " << *I << "\n");565if (HoistStops)566HoistStops->insert(OpsHoistStops.begin(), OpsHoistStops.end());567Visited[I] = true;568return true;569}570}571Visited[I] = false;572return false;573}574// Non-instructions are considered hoistable.575return true;576}577578// Constructs the true and false branch probabilities if the the instruction has579// valid branch weights. Returns true when this was successful, false otherwise.580static bool extractBranchProbabilities(Instruction *I,581BranchProbability &TrueProb,582BranchProbability &FalseProb) {583uint64_t TrueWeight;584uint64_t FalseWeight;585if (!extractBranchWeights(*I, TrueWeight, FalseWeight))586return false;587uint64_t SumWeight = TrueWeight + FalseWeight;588589assert(SumWeight >= TrueWeight && SumWeight >= FalseWeight &&590"Overflow calculating branch probabilities.");591592// Guard against 0-to-0 branch weights to avoid a division-by-zero crash.593if (SumWeight == 0)594return false;595596TrueProb = BranchProbability::getBranchProbability(TrueWeight, SumWeight);597FalseProb = BranchProbability::getBranchProbability(FalseWeight, SumWeight);598return true;599}600601static BranchProbability getCHRBiasThreshold() {602return BranchProbability::getBranchProbability(603static_cast<uint64_t>(CHRBiasThreshold * 1000000), 1000000);604}605606// A helper for CheckBiasedBranch and CheckBiasedSelect. If TrueProb >=607// CHRBiasThreshold, put Key into TrueSet and return true. If FalseProb >=608// CHRBiasThreshold, put Key into FalseSet and return true. Otherwise, return609// false.610template <typename K, typename S, typename M>611static bool checkBias(K *Key, BranchProbability TrueProb,612BranchProbability FalseProb, S &TrueSet, S &FalseSet,613M &BiasMap) {614BranchProbability Threshold = getCHRBiasThreshold();615if (TrueProb >= Threshold) {616TrueSet.insert(Key);617BiasMap[Key] = TrueProb;618return true;619} else if (FalseProb >= Threshold) {620FalseSet.insert(Key);621BiasMap[Key] = FalseProb;622return true;623}624return false;625}626627// Returns true and insert a region into the right biased set and the map if the628// branch of the region is biased.629static bool checkBiasedBranch(BranchInst *BI, Region *R,630DenseSet<Region *> &TrueBiasedRegionsGlobal,631DenseSet<Region *> &FalseBiasedRegionsGlobal,632DenseMap<Region *, BranchProbability> &BranchBiasMap) {633if (!BI->isConditional())634return false;635BranchProbability ThenProb, ElseProb;636if (!extractBranchProbabilities(BI, ThenProb, ElseProb))637return false;638BasicBlock *IfThen = BI->getSuccessor(0);639BasicBlock *IfElse = BI->getSuccessor(1);640assert((IfThen == R->getExit() || IfElse == R->getExit()) &&641IfThen != IfElse &&642"Invariant from findScopes");643if (IfThen == R->getExit()) {644// Swap them so that IfThen/ThenProb means going into the conditional code645// and IfElse/ElseProb means skipping it.646std::swap(IfThen, IfElse);647std::swap(ThenProb, ElseProb);648}649CHR_DEBUG(dbgs() << "BI " << *BI << " ");650CHR_DEBUG(dbgs() << "ThenProb " << ThenProb << " ");651CHR_DEBUG(dbgs() << "ElseProb " << ElseProb << "\n");652return checkBias(R, ThenProb, ElseProb,653TrueBiasedRegionsGlobal, FalseBiasedRegionsGlobal,654BranchBiasMap);655}656657// Returns true and insert a select into the right biased set and the map if the658// select is biased.659static bool checkBiasedSelect(660SelectInst *SI, Region *R,661DenseSet<SelectInst *> &TrueBiasedSelectsGlobal,662DenseSet<SelectInst *> &FalseBiasedSelectsGlobal,663DenseMap<SelectInst *, BranchProbability> &SelectBiasMap) {664BranchProbability TrueProb, FalseProb;665if (!extractBranchProbabilities(SI, TrueProb, FalseProb))666return false;667CHR_DEBUG(dbgs() << "SI " << *SI << " ");668CHR_DEBUG(dbgs() << "TrueProb " << TrueProb << " ");669CHR_DEBUG(dbgs() << "FalseProb " << FalseProb << "\n");670return checkBias(SI, TrueProb, FalseProb,671TrueBiasedSelectsGlobal, FalseBiasedSelectsGlobal,672SelectBiasMap);673}674675// Returns the instruction at which to hoist the dependent condition values and676// insert the CHR branch for a region. This is the terminator branch in the677// entry block or the first select in the entry block, if any.678static Instruction* getBranchInsertPoint(RegInfo &RI) {679Region *R = RI.R;680BasicBlock *EntryBB = R->getEntry();681// The hoist point is by default the terminator of the entry block, which is682// the same as the branch instruction if RI.HasBranch is true.683Instruction *HoistPoint = EntryBB->getTerminator();684for (SelectInst *SI : RI.Selects) {685if (SI->getParent() == EntryBB) {686// Pick the first select in Selects in the entry block. Note Selects is687// sorted in the instruction order within a block (asserted below).688HoistPoint = SI;689break;690}691}692assert(HoistPoint && "Null HoistPoint");693#ifndef NDEBUG694// Check that HoistPoint is the first one in Selects in the entry block,695// if any.696DenseSet<Instruction *> EntryBlockSelectSet;697for (SelectInst *SI : RI.Selects) {698if (SI->getParent() == EntryBB) {699EntryBlockSelectSet.insert(SI);700}701}702for (Instruction &I : *EntryBB) {703if (EntryBlockSelectSet.contains(&I)) {704assert(&I == HoistPoint &&705"HoistPoint must be the first one in Selects");706break;707}708}709#endif710return HoistPoint;711}712713// Find a CHR scope in the given region.714CHRScope * CHR::findScope(Region *R) {715CHRScope *Result = nullptr;716BasicBlock *Entry = R->getEntry();717BasicBlock *Exit = R->getExit(); // null if top level.718assert(Entry && "Entry must not be null");719assert((Exit == nullptr) == (R->isTopLevelRegion()) &&720"Only top level region has a null exit");721if (Entry)722CHR_DEBUG(dbgs() << "Entry " << Entry->getName() << "\n");723else724CHR_DEBUG(dbgs() << "Entry null\n");725if (Exit)726CHR_DEBUG(dbgs() << "Exit " << Exit->getName() << "\n");727else728CHR_DEBUG(dbgs() << "Exit null\n");729// Exclude cases where Entry is part of a subregion (hence it doesn't belong730// to this region).731bool EntryInSubregion = RI.getRegionFor(Entry) != R;732if (EntryInSubregion)733return nullptr;734// Exclude loops735for (BasicBlock *Pred : predecessors(Entry))736if (R->contains(Pred))737return nullptr;738// If any of the basic blocks have address taken, we must skip this region739// because we cannot clone basic blocks that have address taken.740for (BasicBlock *BB : R->blocks()) {741if (BB->hasAddressTaken())742return nullptr;743// If we encounter llvm.coro.id, skip this region because if the basic block744// is cloned, we end up inserting a token type PHI node to the block with745// llvm.coro.begin.746// FIXME: This could lead to less optimal codegen, because the region is747// excluded, it can prevent CHR from merging adjacent regions into bigger748// scope and hoisting more branches.749for (Instruction &I : *BB)750if (auto *II = dyn_cast<IntrinsicInst>(&I))751if (II->getIntrinsicID() == Intrinsic::coro_id)752return nullptr;753}754755if (Exit) {756// Try to find an if-then block (check if R is an if-then).757// if (cond) {758// ...759// }760auto *BI = dyn_cast<BranchInst>(Entry->getTerminator());761if (BI)762CHR_DEBUG(dbgs() << "BI.isConditional " << BI->isConditional() << "\n");763else764CHR_DEBUG(dbgs() << "BI null\n");765if (BI && BI->isConditional()) {766BasicBlock *S0 = BI->getSuccessor(0);767BasicBlock *S1 = BI->getSuccessor(1);768CHR_DEBUG(dbgs() << "S0 " << S0->getName() << "\n");769CHR_DEBUG(dbgs() << "S1 " << S1->getName() << "\n");770if (S0 != S1 && (S0 == Exit || S1 == Exit)) {771RegInfo RI(R);772RI.HasBranch = checkBiasedBranch(773BI, R, TrueBiasedRegionsGlobal, FalseBiasedRegionsGlobal,774BranchBiasMap);775Result = new CHRScope(RI);776Scopes.insert(Result);777CHR_DEBUG(dbgs() << "Found a region with a branch\n");778++Stats.NumBranches;779if (!RI.HasBranch) {780ORE.emit([&]() {781return OptimizationRemarkMissed(DEBUG_TYPE, "BranchNotBiased", BI)782<< "Branch not biased";783});784}785}786}787}788{789// Try to look for selects in the direct child blocks (as opposed to in790// subregions) of R.791// ...792// if (..) { // Some subregion793// ...794// }795// if (..) { // Some subregion796// ...797// }798// ...799// a = cond ? b : c;800// ...801SmallVector<SelectInst *, 8> Selects;802for (RegionNode *E : R->elements()) {803if (E->isSubRegion())804continue;805// This returns the basic block of E if E is a direct child of R (not a806// subregion.)807BasicBlock *BB = E->getEntry();808// Need to push in the order to make it easier to find the first Select809// later.810for (Instruction &I : *BB) {811if (auto *SI = dyn_cast<SelectInst>(&I)) {812Selects.push_back(SI);813++Stats.NumBranches;814}815}816}817if (Selects.size() > 0) {818auto AddSelects = [&](RegInfo &RI) {819for (auto *SI : Selects)820if (checkBiasedSelect(SI, RI.R,821TrueBiasedSelectsGlobal,822FalseBiasedSelectsGlobal,823SelectBiasMap))824RI.Selects.push_back(SI);825else826ORE.emit([&]() {827return OptimizationRemarkMissed(DEBUG_TYPE, "SelectNotBiased", SI)828<< "Select not biased";829});830};831if (!Result) {832CHR_DEBUG(dbgs() << "Found a select-only region\n");833RegInfo RI(R);834AddSelects(RI);835Result = new CHRScope(RI);836Scopes.insert(Result);837} else {838CHR_DEBUG(dbgs() << "Found select(s) in a region with a branch\n");839AddSelects(Result->RegInfos[0]);840}841}842}843844if (Result) {845checkScopeHoistable(Result);846}847return Result;848}849850// Check that any of the branch and the selects in the region could be851// hoisted above the the CHR branch insert point (the most dominating of852// them, either the branch (at the end of the first block) or the first853// select in the first block). If the branch can't be hoisted, drop the854// selects in the first blocks.855//856// For example, for the following scope/region with selects, we want to insert857// the merged branch right before the first select in the first/entry block by858// hoisting c1, c2, c3, and c4.859//860// // Branch insert point here.861// a = c1 ? b : c; // Select 1862// d = c2 ? e : f; // Select 2863// if (c3) { // Branch864// ...865// c4 = foo() // A call.866// g = c4 ? h : i; // Select 3867// }868//869// But suppose we can't hoist c4 because it's dependent on the preceding870// call. Then, we drop Select 3. Furthermore, if we can't hoist c2, we also drop871// Select 2. If we can't hoist c3, we drop Selects 1 & 2.872void CHR::checkScopeHoistable(CHRScope *Scope) {873RegInfo &RI = Scope->RegInfos[0];874Region *R = RI.R;875BasicBlock *EntryBB = R->getEntry();876auto *Branch = RI.HasBranch ?877cast<BranchInst>(EntryBB->getTerminator()) : nullptr;878SmallVector<SelectInst *, 8> &Selects = RI.Selects;879if (RI.HasBranch || !Selects.empty()) {880Instruction *InsertPoint = getBranchInsertPoint(RI);881CHR_DEBUG(dbgs() << "InsertPoint " << *InsertPoint << "\n");882// Avoid a data dependence from a select or a branch to a(nother)883// select. Note no instruction can't data-depend on a branch (a branch884// instruction doesn't produce a value).885DenseSet<Instruction *> Unhoistables;886// Initialize Unhoistables with the selects.887for (SelectInst *SI : Selects) {888Unhoistables.insert(SI);889}890// Remove Selects that can't be hoisted.891for (auto it = Selects.begin(); it != Selects.end(); ) {892SelectInst *SI = *it;893if (SI == InsertPoint) {894++it;895continue;896}897DenseMap<Instruction *, bool> Visited;898bool IsHoistable = checkHoistValue(SI->getCondition(), InsertPoint,899DT, Unhoistables, nullptr, Visited);900if (!IsHoistable) {901CHR_DEBUG(dbgs() << "Dropping select " << *SI << "\n");902ORE.emit([&]() {903return OptimizationRemarkMissed(DEBUG_TYPE,904"DropUnhoistableSelect", SI)905<< "Dropped unhoistable select";906});907it = Selects.erase(it);908// Since we are dropping the select here, we also drop it from909// Unhoistables.910Unhoistables.erase(SI);911} else912++it;913}914// Update InsertPoint after potentially removing selects.915InsertPoint = getBranchInsertPoint(RI);916CHR_DEBUG(dbgs() << "InsertPoint " << *InsertPoint << "\n");917if (RI.HasBranch && InsertPoint != Branch) {918DenseMap<Instruction *, bool> Visited;919bool IsHoistable = checkHoistValue(Branch->getCondition(), InsertPoint,920DT, Unhoistables, nullptr, Visited);921if (!IsHoistable) {922// If the branch isn't hoistable, drop the selects in the entry923// block, preferring the branch, which makes the branch the hoist924// point.925assert(InsertPoint != Branch && "Branch must not be the hoist point");926CHR_DEBUG(dbgs() << "Dropping selects in entry block \n");927CHR_DEBUG(928for (SelectInst *SI : Selects) {929dbgs() << "SI " << *SI << "\n";930});931for (SelectInst *SI : Selects) {932ORE.emit([&]() {933return OptimizationRemarkMissed(DEBUG_TYPE,934"DropSelectUnhoistableBranch", SI)935<< "Dropped select due to unhoistable branch";936});937}938llvm::erase_if(Selects, [EntryBB](SelectInst *SI) {939return SI->getParent() == EntryBB;940});941Unhoistables.clear();942InsertPoint = Branch;943}944}945CHR_DEBUG(dbgs() << "InsertPoint " << *InsertPoint << "\n");946#ifndef NDEBUG947if (RI.HasBranch) {948assert(!DT.dominates(Branch, InsertPoint) &&949"Branch can't be already above the hoist point");950DenseMap<Instruction *, bool> Visited;951assert(checkHoistValue(Branch->getCondition(), InsertPoint,952DT, Unhoistables, nullptr, Visited) &&953"checkHoistValue for branch");954}955for (auto *SI : Selects) {956assert(!DT.dominates(SI, InsertPoint) &&957"SI can't be already above the hoist point");958DenseMap<Instruction *, bool> Visited;959assert(checkHoistValue(SI->getCondition(), InsertPoint, DT,960Unhoistables, nullptr, Visited) &&961"checkHoistValue for selects");962}963CHR_DEBUG(dbgs() << "Result\n");964if (RI.HasBranch) {965CHR_DEBUG(dbgs() << "BI " << *Branch << "\n");966}967for (auto *SI : Selects) {968CHR_DEBUG(dbgs() << "SI " << *SI << "\n");969}970#endif971}972}973974// Traverse the region tree, find all nested scopes and merge them if possible.975CHRScope * CHR::findScopes(Region *R, Region *NextRegion, Region *ParentRegion,976SmallVectorImpl<CHRScope *> &Scopes) {977CHR_DEBUG(dbgs() << "findScopes " << R->getNameStr() << "\n");978CHRScope *Result = findScope(R);979// Visit subscopes.980CHRScope *ConsecutiveSubscope = nullptr;981SmallVector<CHRScope *, 8> Subscopes;982for (auto It = R->begin(); It != R->end(); ++It) {983const std::unique_ptr<Region> &SubR = *It;984auto NextIt = std::next(It);985Region *NextSubR = NextIt != R->end() ? NextIt->get() : nullptr;986CHR_DEBUG(dbgs() << "Looking at subregion " << SubR.get()->getNameStr()987<< "\n");988CHRScope *SubCHRScope = findScopes(SubR.get(), NextSubR, R, Scopes);989if (SubCHRScope) {990CHR_DEBUG(dbgs() << "Subregion Scope " << *SubCHRScope << "\n");991} else {992CHR_DEBUG(dbgs() << "Subregion Scope null\n");993}994if (SubCHRScope) {995if (!ConsecutiveSubscope)996ConsecutiveSubscope = SubCHRScope;997else if (!ConsecutiveSubscope->appendable(SubCHRScope)) {998Subscopes.push_back(ConsecutiveSubscope);999ConsecutiveSubscope = SubCHRScope;1000} else1001ConsecutiveSubscope->append(SubCHRScope);1002} else {1003if (ConsecutiveSubscope) {1004Subscopes.push_back(ConsecutiveSubscope);1005}1006ConsecutiveSubscope = nullptr;1007}1008}1009if (ConsecutiveSubscope) {1010Subscopes.push_back(ConsecutiveSubscope);1011}1012for (CHRScope *Sub : Subscopes) {1013if (Result) {1014// Combine it with the parent.1015Result->addSub(Sub);1016} else {1017// Push Subscopes as they won't be combined with the parent.1018Scopes.push_back(Sub);1019}1020}1021return Result;1022}10231024static DenseSet<Value *> getCHRConditionValuesForRegion(RegInfo &RI) {1025DenseSet<Value *> ConditionValues;1026if (RI.HasBranch) {1027auto *BI = cast<BranchInst>(RI.R->getEntry()->getTerminator());1028ConditionValues.insert(BI->getCondition());1029}1030for (SelectInst *SI : RI.Selects) {1031ConditionValues.insert(SI->getCondition());1032}1033return ConditionValues;1034}103510361037// Determine whether to split a scope depending on the sets of the branch1038// condition values of the previous region and the current region. We split1039// (return true) it if 1) the condition values of the inner/lower scope can't be1040// hoisted up to the outer/upper scope, or 2) the two sets of the condition1041// values have an empty intersection (because the combined branch conditions1042// won't probably lead to a simpler combined condition).1043static bool shouldSplit(Instruction *InsertPoint,1044DenseSet<Value *> &PrevConditionValues,1045DenseSet<Value *> &ConditionValues,1046DominatorTree &DT,1047DenseSet<Instruction *> &Unhoistables) {1048assert(InsertPoint && "Null InsertPoint");1049CHR_DEBUG(1050dbgs() << "shouldSplit " << *InsertPoint << " PrevConditionValues ";1051for (Value *V : PrevConditionValues) {1052dbgs() << *V << ", ";1053}1054dbgs() << " ConditionValues ";1055for (Value *V : ConditionValues) {1056dbgs() << *V << ", ";1057}1058dbgs() << "\n");1059// If any of Bases isn't hoistable to the hoist point, split.1060for (Value *V : ConditionValues) {1061DenseMap<Instruction *, bool> Visited;1062if (!checkHoistValue(V, InsertPoint, DT, Unhoistables, nullptr, Visited)) {1063CHR_DEBUG(dbgs() << "Split. checkHoistValue false " << *V << "\n");1064return true; // Not hoistable, split.1065}1066}1067// If PrevConditionValues or ConditionValues is empty, don't split to avoid1068// unnecessary splits at scopes with no branch/selects. If1069// PrevConditionValues and ConditionValues don't intersect at all, split.1070if (!PrevConditionValues.empty() && !ConditionValues.empty()) {1071// Use std::set as DenseSet doesn't work with set_intersection.1072std::set<Value *> PrevBases, Bases;1073DenseMap<Value *, std::set<Value *>> Visited;1074for (Value *V : PrevConditionValues) {1075const std::set<Value *> &BaseValues = getBaseValues(V, DT, Visited);1076PrevBases.insert(BaseValues.begin(), BaseValues.end());1077}1078for (Value *V : ConditionValues) {1079const std::set<Value *> &BaseValues = getBaseValues(V, DT, Visited);1080Bases.insert(BaseValues.begin(), BaseValues.end());1081}1082CHR_DEBUG(1083dbgs() << "PrevBases ";1084for (Value *V : PrevBases) {1085dbgs() << *V << ", ";1086}1087dbgs() << " Bases ";1088for (Value *V : Bases) {1089dbgs() << *V << ", ";1090}1091dbgs() << "\n");1092std::vector<Value *> Intersection;1093std::set_intersection(PrevBases.begin(), PrevBases.end(), Bases.begin(),1094Bases.end(), std::back_inserter(Intersection));1095if (Intersection.empty()) {1096// Empty intersection, split.1097CHR_DEBUG(dbgs() << "Split. Intersection empty\n");1098return true;1099}1100}1101CHR_DEBUG(dbgs() << "No split\n");1102return false; // Don't split.1103}11041105static void getSelectsInScope(CHRScope *Scope,1106DenseSet<Instruction *> &Output) {1107for (RegInfo &RI : Scope->RegInfos)1108for (SelectInst *SI : RI.Selects)1109Output.insert(SI);1110for (CHRScope *Sub : Scope->Subs)1111getSelectsInScope(Sub, Output);1112}11131114void CHR::splitScopes(SmallVectorImpl<CHRScope *> &Input,1115SmallVectorImpl<CHRScope *> &Output) {1116for (CHRScope *Scope : Input) {1117assert(!Scope->BranchInsertPoint &&1118"BranchInsertPoint must not be set");1119DenseSet<Instruction *> Unhoistables;1120getSelectsInScope(Scope, Unhoistables);1121splitScope(Scope, nullptr, nullptr, nullptr, Output, Unhoistables);1122}1123#ifndef NDEBUG1124for (CHRScope *Scope : Output) {1125assert(Scope->BranchInsertPoint && "BranchInsertPoint must be set");1126}1127#endif1128}11291130SmallVector<CHRScope *, 8> CHR::splitScope(1131CHRScope *Scope,1132CHRScope *Outer,1133DenseSet<Value *> *OuterConditionValues,1134Instruction *OuterInsertPoint,1135SmallVectorImpl<CHRScope *> &Output,1136DenseSet<Instruction *> &Unhoistables) {1137if (Outer) {1138assert(OuterConditionValues && "Null OuterConditionValues");1139assert(OuterInsertPoint && "Null OuterInsertPoint");1140}1141bool PrevSplitFromOuter = true;1142DenseSet<Value *> PrevConditionValues;1143Instruction *PrevInsertPoint = nullptr;1144SmallVector<CHRScope *, 8> Splits;1145SmallVector<bool, 8> SplitsSplitFromOuter;1146SmallVector<DenseSet<Value *>, 8> SplitsConditionValues;1147SmallVector<Instruction *, 8> SplitsInsertPoints;1148SmallVector<RegInfo, 8> RegInfos(Scope->RegInfos); // Copy1149for (RegInfo &RI : RegInfos) {1150Instruction *InsertPoint = getBranchInsertPoint(RI);1151DenseSet<Value *> ConditionValues = getCHRConditionValuesForRegion(RI);1152CHR_DEBUG(1153dbgs() << "ConditionValues ";1154for (Value *V : ConditionValues) {1155dbgs() << *V << ", ";1156}1157dbgs() << "\n");1158if (RI.R == RegInfos[0].R) {1159// First iteration. Check to see if we should split from the outer.1160if (Outer) {1161CHR_DEBUG(dbgs() << "Outer " << *Outer << "\n");1162CHR_DEBUG(dbgs() << "Should split from outer at "1163<< RI.R->getNameStr() << "\n");1164if (shouldSplit(OuterInsertPoint, *OuterConditionValues,1165ConditionValues, DT, Unhoistables)) {1166PrevConditionValues = ConditionValues;1167PrevInsertPoint = InsertPoint;1168ORE.emit([&]() {1169return OptimizationRemarkMissed(DEBUG_TYPE,1170"SplitScopeFromOuter",1171RI.R->getEntry()->getTerminator())1172<< "Split scope from outer due to unhoistable branch/select "1173<< "and/or lack of common condition values";1174});1175} else {1176// Not splitting from the outer. Use the outer bases and insert1177// point. Union the bases.1178PrevSplitFromOuter = false;1179PrevConditionValues = *OuterConditionValues;1180PrevConditionValues.insert(ConditionValues.begin(),1181ConditionValues.end());1182PrevInsertPoint = OuterInsertPoint;1183}1184} else {1185CHR_DEBUG(dbgs() << "Outer null\n");1186PrevConditionValues = ConditionValues;1187PrevInsertPoint = InsertPoint;1188}1189} else {1190CHR_DEBUG(dbgs() << "Should split from prev at "1191<< RI.R->getNameStr() << "\n");1192if (shouldSplit(PrevInsertPoint, PrevConditionValues, ConditionValues,1193DT, Unhoistables)) {1194CHRScope *Tail = Scope->split(RI.R);1195Scopes.insert(Tail);1196Splits.push_back(Scope);1197SplitsSplitFromOuter.push_back(PrevSplitFromOuter);1198SplitsConditionValues.push_back(PrevConditionValues);1199SplitsInsertPoints.push_back(PrevInsertPoint);1200Scope = Tail;1201PrevConditionValues = ConditionValues;1202PrevInsertPoint = InsertPoint;1203PrevSplitFromOuter = true;1204ORE.emit([&]() {1205return OptimizationRemarkMissed(DEBUG_TYPE,1206"SplitScopeFromPrev",1207RI.R->getEntry()->getTerminator())1208<< "Split scope from previous due to unhoistable branch/select "1209<< "and/or lack of common condition values";1210});1211} else {1212// Not splitting. Union the bases. Keep the hoist point.1213PrevConditionValues.insert(ConditionValues.begin(), ConditionValues.end());1214}1215}1216}1217Splits.push_back(Scope);1218SplitsSplitFromOuter.push_back(PrevSplitFromOuter);1219SplitsConditionValues.push_back(PrevConditionValues);1220assert(PrevInsertPoint && "Null PrevInsertPoint");1221SplitsInsertPoints.push_back(PrevInsertPoint);1222assert(Splits.size() == SplitsConditionValues.size() &&1223Splits.size() == SplitsSplitFromOuter.size() &&1224Splits.size() == SplitsInsertPoints.size() && "Mismatching sizes");1225for (size_t I = 0; I < Splits.size(); ++I) {1226CHRScope *Split = Splits[I];1227DenseSet<Value *> &SplitConditionValues = SplitsConditionValues[I];1228Instruction *SplitInsertPoint = SplitsInsertPoints[I];1229SmallVector<CHRScope *, 8> NewSubs;1230DenseSet<Instruction *> SplitUnhoistables;1231getSelectsInScope(Split, SplitUnhoistables);1232for (CHRScope *Sub : Split->Subs) {1233SmallVector<CHRScope *, 8> SubSplits = splitScope(1234Sub, Split, &SplitConditionValues, SplitInsertPoint, Output,1235SplitUnhoistables);1236llvm::append_range(NewSubs, SubSplits);1237}1238Split->Subs = NewSubs;1239}1240SmallVector<CHRScope *, 8> Result;1241for (size_t I = 0; I < Splits.size(); ++I) {1242CHRScope *Split = Splits[I];1243if (SplitsSplitFromOuter[I]) {1244// Split from the outer.1245Output.push_back(Split);1246Split->BranchInsertPoint = SplitsInsertPoints[I];1247CHR_DEBUG(dbgs() << "BranchInsertPoint " << *SplitsInsertPoints[I]1248<< "\n");1249} else {1250// Connected to the outer.1251Result.push_back(Split);1252}1253}1254if (!Outer)1255assert(Result.empty() &&1256"If no outer (top-level), must return no nested ones");1257return Result;1258}12591260void CHR::classifyBiasedScopes(SmallVectorImpl<CHRScope *> &Scopes) {1261for (CHRScope *Scope : Scopes) {1262assert(Scope->TrueBiasedRegions.empty() && Scope->FalseBiasedRegions.empty() && "Empty");1263classifyBiasedScopes(Scope, Scope);1264CHR_DEBUG(1265dbgs() << "classifyBiasedScopes " << *Scope << "\n";1266dbgs() << "TrueBiasedRegions ";1267for (Region *R : Scope->TrueBiasedRegions) {1268dbgs() << R->getNameStr() << ", ";1269}1270dbgs() << "\n";1271dbgs() << "FalseBiasedRegions ";1272for (Region *R : Scope->FalseBiasedRegions) {1273dbgs() << R->getNameStr() << ", ";1274}1275dbgs() << "\n";1276dbgs() << "TrueBiasedSelects ";1277for (SelectInst *SI : Scope->TrueBiasedSelects) {1278dbgs() << *SI << ", ";1279}1280dbgs() << "\n";1281dbgs() << "FalseBiasedSelects ";1282for (SelectInst *SI : Scope->FalseBiasedSelects) {1283dbgs() << *SI << ", ";1284}1285dbgs() << "\n";);1286}1287}12881289void CHR::classifyBiasedScopes(CHRScope *Scope, CHRScope *OutermostScope) {1290for (RegInfo &RI : Scope->RegInfos) {1291if (RI.HasBranch) {1292Region *R = RI.R;1293if (TrueBiasedRegionsGlobal.contains(R))1294OutermostScope->TrueBiasedRegions.insert(R);1295else if (FalseBiasedRegionsGlobal.contains(R))1296OutermostScope->FalseBiasedRegions.insert(R);1297else1298llvm_unreachable("Must be biased");1299}1300for (SelectInst *SI : RI.Selects) {1301if (TrueBiasedSelectsGlobal.contains(SI))1302OutermostScope->TrueBiasedSelects.insert(SI);1303else if (FalseBiasedSelectsGlobal.contains(SI))1304OutermostScope->FalseBiasedSelects.insert(SI);1305else1306llvm_unreachable("Must be biased");1307}1308}1309for (CHRScope *Sub : Scope->Subs) {1310classifyBiasedScopes(Sub, OutermostScope);1311}1312}13131314static bool hasAtLeastTwoBiasedBranches(CHRScope *Scope) {1315unsigned NumBiased = Scope->TrueBiasedRegions.size() +1316Scope->FalseBiasedRegions.size() +1317Scope->TrueBiasedSelects.size() +1318Scope->FalseBiasedSelects.size();1319return NumBiased >= CHRMergeThreshold;1320}13211322void CHR::filterScopes(SmallVectorImpl<CHRScope *> &Input,1323SmallVectorImpl<CHRScope *> &Output) {1324for (CHRScope *Scope : Input) {1325// Filter out the ones with only one region and no subs.1326if (!hasAtLeastTwoBiasedBranches(Scope)) {1327CHR_DEBUG(dbgs() << "Filtered out by biased branches truthy-regions "1328<< Scope->TrueBiasedRegions.size()1329<< " falsy-regions " << Scope->FalseBiasedRegions.size()1330<< " true-selects " << Scope->TrueBiasedSelects.size()1331<< " false-selects " << Scope->FalseBiasedSelects.size() << "\n");1332ORE.emit([&]() {1333return OptimizationRemarkMissed(1334DEBUG_TYPE,1335"DropScopeWithOneBranchOrSelect",1336Scope->RegInfos[0].R->getEntry()->getTerminator())1337<< "Drop scope with < "1338<< ore::NV("CHRMergeThreshold", CHRMergeThreshold)1339<< " biased branch(es) or select(s)";1340});1341continue;1342}1343Output.push_back(Scope);1344}1345}13461347void CHR::setCHRRegions(SmallVectorImpl<CHRScope *> &Input,1348SmallVectorImpl<CHRScope *> &Output) {1349for (CHRScope *Scope : Input) {1350assert(Scope->HoistStopMap.empty() && Scope->CHRRegions.empty() &&1351"Empty");1352setCHRRegions(Scope, Scope);1353Output.push_back(Scope);1354CHR_DEBUG(1355dbgs() << "setCHRRegions HoistStopMap " << *Scope << "\n";1356for (auto pair : Scope->HoistStopMap) {1357Region *R = pair.first;1358dbgs() << "Region " << R->getNameStr() << "\n";1359for (Instruction *I : pair.second) {1360dbgs() << "HoistStop " << *I << "\n";1361}1362}1363dbgs() << "CHRRegions" << "\n";1364for (RegInfo &RI : Scope->CHRRegions) {1365dbgs() << RI.R->getNameStr() << "\n";1366});1367}1368}13691370void CHR::setCHRRegions(CHRScope *Scope, CHRScope *OutermostScope) {1371DenseSet<Instruction *> Unhoistables;1372// Put the biased selects in Unhoistables because they should stay where they1373// are and constant-folded after CHR (in case one biased select or a branch1374// can depend on another biased select.)1375for (RegInfo &RI : Scope->RegInfos) {1376for (SelectInst *SI : RI.Selects) {1377Unhoistables.insert(SI);1378}1379}1380Instruction *InsertPoint = OutermostScope->BranchInsertPoint;1381for (RegInfo &RI : Scope->RegInfos) {1382Region *R = RI.R;1383DenseSet<Instruction *> HoistStops;1384bool IsHoisted = false;1385if (RI.HasBranch) {1386assert((OutermostScope->TrueBiasedRegions.contains(R) ||1387OutermostScope->FalseBiasedRegions.contains(R)) &&1388"Must be truthy or falsy");1389auto *BI = cast<BranchInst>(R->getEntry()->getTerminator());1390// Note checkHoistValue fills in HoistStops.1391DenseMap<Instruction *, bool> Visited;1392bool IsHoistable = checkHoistValue(BI->getCondition(), InsertPoint, DT,1393Unhoistables, &HoistStops, Visited);1394assert(IsHoistable && "Must be hoistable");1395(void)(IsHoistable); // Unused in release build1396IsHoisted = true;1397}1398for (SelectInst *SI : RI.Selects) {1399assert((OutermostScope->TrueBiasedSelects.contains(SI) ||1400OutermostScope->FalseBiasedSelects.contains(SI)) &&1401"Must be true or false biased");1402// Note checkHoistValue fills in HoistStops.1403DenseMap<Instruction *, bool> Visited;1404bool IsHoistable = checkHoistValue(SI->getCondition(), InsertPoint, DT,1405Unhoistables, &HoistStops, Visited);1406assert(IsHoistable && "Must be hoistable");1407(void)(IsHoistable); // Unused in release build1408IsHoisted = true;1409}1410if (IsHoisted) {1411OutermostScope->CHRRegions.push_back(RI);1412OutermostScope->HoistStopMap[R] = HoistStops;1413}1414}1415for (CHRScope *Sub : Scope->Subs)1416setCHRRegions(Sub, OutermostScope);1417}14181419static bool CHRScopeSorter(CHRScope *Scope1, CHRScope *Scope2) {1420return Scope1->RegInfos[0].R->getDepth() < Scope2->RegInfos[0].R->getDepth();1421}14221423void CHR::sortScopes(SmallVectorImpl<CHRScope *> &Input,1424SmallVectorImpl<CHRScope *> &Output) {1425Output.resize(Input.size());1426llvm::copy(Input, Output.begin());1427llvm::stable_sort(Output, CHRScopeSorter);1428}14291430// Return true if V is already hoisted or was hoisted (along with its operands)1431// to the insert point.1432static void hoistValue(Value *V, Instruction *HoistPoint, Region *R,1433HoistStopMapTy &HoistStopMap,1434DenseSet<Instruction *> &HoistedSet,1435DenseSet<PHINode *> &TrivialPHIs,1436DominatorTree &DT) {1437auto IT = HoistStopMap.find(R);1438assert(IT != HoistStopMap.end() && "Region must be in hoist stop map");1439DenseSet<Instruction *> &HoistStops = IT->second;1440if (auto *I = dyn_cast<Instruction>(V)) {1441if (I == HoistPoint)1442return;1443if (HoistStops.count(I))1444return;1445if (auto *PN = dyn_cast<PHINode>(I))1446if (TrivialPHIs.count(PN))1447// The trivial phi inserted by the previous CHR scope could replace a1448// non-phi in HoistStops. Note that since this phi is at the exit of a1449// previous CHR scope, which dominates this scope, it's safe to stop1450// hoisting there.1451return;1452if (HoistedSet.count(I))1453// Already hoisted, return.1454return;1455assert(isHoistableInstructionType(I) && "Unhoistable instruction type");1456assert(DT.getNode(I->getParent()) && "DT must contain I's block");1457assert(DT.getNode(HoistPoint->getParent()) &&1458"DT must contain HoistPoint block");1459if (DT.dominates(I, HoistPoint))1460// We are already above the hoist point. Stop here. This may be necessary1461// when multiple scopes would independently hoist the same1462// instruction. Since an outer (dominating) scope would hoist it to its1463// entry before an inner (dominated) scope would to its entry, the inner1464// scope may see the instruction already hoisted, in which case it1465// potentially wrong for the inner scope to hoist it and could cause bad1466// IR (non-dominating def), but safe to skip hoisting it instead because1467// it's already in a block that dominates the inner scope.1468return;1469for (Value *Op : I->operands()) {1470hoistValue(Op, HoistPoint, R, HoistStopMap, HoistedSet, TrivialPHIs, DT);1471}1472I->moveBefore(HoistPoint);1473HoistedSet.insert(I);1474CHR_DEBUG(dbgs() << "hoistValue " << *I << "\n");1475}1476}14771478// Hoist the dependent condition values of the branches and the selects in the1479// scope to the insert point.1480static void hoistScopeConditions(CHRScope *Scope, Instruction *HoistPoint,1481DenseSet<PHINode *> &TrivialPHIs,1482DominatorTree &DT) {1483DenseSet<Instruction *> HoistedSet;1484for (const RegInfo &RI : Scope->CHRRegions) {1485Region *R = RI.R;1486bool IsTrueBiased = Scope->TrueBiasedRegions.count(R);1487bool IsFalseBiased = Scope->FalseBiasedRegions.count(R);1488if (RI.HasBranch && (IsTrueBiased || IsFalseBiased)) {1489auto *BI = cast<BranchInst>(R->getEntry()->getTerminator());1490hoistValue(BI->getCondition(), HoistPoint, R, Scope->HoistStopMap,1491HoistedSet, TrivialPHIs, DT);1492}1493for (SelectInst *SI : RI.Selects) {1494bool IsTrueBiased = Scope->TrueBiasedSelects.count(SI);1495bool IsFalseBiased = Scope->FalseBiasedSelects.count(SI);1496if (!(IsTrueBiased || IsFalseBiased))1497continue;1498hoistValue(SI->getCondition(), HoistPoint, R, Scope->HoistStopMap,1499HoistedSet, TrivialPHIs, DT);1500}1501}1502}15031504// Negate the predicate if an ICmp if it's used only by branches or selects by1505// swapping the operands of the branches or the selects. Returns true if success.1506static bool negateICmpIfUsedByBranchOrSelectOnly(ICmpInst *ICmp,1507Instruction *ExcludedUser,1508CHRScope *Scope) {1509for (User *U : ICmp->users()) {1510if (U == ExcludedUser)1511continue;1512if (isa<BranchInst>(U) && cast<BranchInst>(U)->isConditional())1513continue;1514if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == ICmp)1515continue;1516return false;1517}1518for (User *U : ICmp->users()) {1519if (U == ExcludedUser)1520continue;1521if (auto *BI = dyn_cast<BranchInst>(U)) {1522assert(BI->isConditional() && "Must be conditional");1523BI->swapSuccessors();1524// Don't need to swap this in terms of1525// TrueBiasedRegions/FalseBiasedRegions because true-based/false-based1526// mean whehter the branch is likely go into the if-then rather than1527// successor0/successor1 and because we can tell which edge is the then or1528// the else one by comparing the destination to the region exit block.1529continue;1530}1531if (auto *SI = dyn_cast<SelectInst>(U)) {1532// Swap operands1533SI->swapValues();1534SI->swapProfMetadata();1535if (Scope->TrueBiasedSelects.count(SI)) {1536assert(!Scope->FalseBiasedSelects.contains(SI) &&1537"Must not be already in");1538Scope->FalseBiasedSelects.insert(SI);1539} else if (Scope->FalseBiasedSelects.count(SI)) {1540assert(!Scope->TrueBiasedSelects.contains(SI) &&1541"Must not be already in");1542Scope->TrueBiasedSelects.insert(SI);1543}1544continue;1545}1546llvm_unreachable("Must be a branch or a select");1547}1548ICmp->setPredicate(CmpInst::getInversePredicate(ICmp->getPredicate()));1549return true;1550}15511552// A helper for transformScopes. Insert a trivial phi at the scope exit block1553// for a value that's defined in the scope but used outside it (meaning it's1554// alive at the exit block).1555static void insertTrivialPHIs(CHRScope *Scope,1556BasicBlock *EntryBlock, BasicBlock *ExitBlock,1557DenseSet<PHINode *> &TrivialPHIs) {1558SmallSetVector<BasicBlock *, 8> BlocksInScope;1559for (RegInfo &RI : Scope->RegInfos) {1560for (BasicBlock *BB : RI.R->blocks()) { // This includes the blocks in the1561// sub-Scopes.1562BlocksInScope.insert(BB);1563}1564}1565CHR_DEBUG({1566dbgs() << "Inserting redundant phis\n";1567for (BasicBlock *BB : BlocksInScope)1568dbgs() << "BlockInScope " << BB->getName() << "\n";1569});1570for (BasicBlock *BB : BlocksInScope) {1571for (Instruction &I : *BB) {1572SmallVector<Instruction *, 8> Users;1573for (User *U : I.users()) {1574if (auto *UI = dyn_cast<Instruction>(U)) {1575if (!BlocksInScope.contains(UI->getParent()) &&1576// Unless there's already a phi for I at the exit block.1577!(isa<PHINode>(UI) && UI->getParent() == ExitBlock)) {1578CHR_DEBUG(dbgs() << "V " << I << "\n");1579CHR_DEBUG(dbgs() << "Used outside scope by user " << *UI << "\n");1580Users.push_back(UI);1581} else if (UI->getParent() == EntryBlock && isa<PHINode>(UI)) {1582// There's a loop backedge from a block that's dominated by this1583// scope to the entry block.1584CHR_DEBUG(dbgs() << "V " << I << "\n");1585CHR_DEBUG(dbgs()1586<< "Used at entry block (for a back edge) by a phi user "1587<< *UI << "\n");1588Users.push_back(UI);1589}1590}1591}1592if (Users.size() > 0) {1593// Insert a trivial phi for I (phi [&I, P0], [&I, P1], ...) at1594// ExitBlock. Replace I with the new phi in UI unless UI is another1595// phi at ExitBlock.1596PHINode *PN = PHINode::Create(I.getType(), pred_size(ExitBlock), "");1597PN->insertBefore(ExitBlock->begin());1598for (BasicBlock *Pred : predecessors(ExitBlock)) {1599PN->addIncoming(&I, Pred);1600}1601TrivialPHIs.insert(PN);1602CHR_DEBUG(dbgs() << "Insert phi " << *PN << "\n");1603for (Instruction *UI : Users) {1604for (unsigned J = 0, NumOps = UI->getNumOperands(); J < NumOps; ++J) {1605if (UI->getOperand(J) == &I) {1606UI->setOperand(J, PN);1607}1608}1609CHR_DEBUG(dbgs() << "Updated user " << *UI << "\n");1610}1611}1612}1613}1614}16151616// Assert that all the CHR regions of the scope have a biased branch or select.1617static void LLVM_ATTRIBUTE_UNUSED1618assertCHRRegionsHaveBiasedBranchOrSelect(CHRScope *Scope) {1619#ifndef NDEBUG1620auto HasBiasedBranchOrSelect = [](RegInfo &RI, CHRScope *Scope) {1621if (Scope->TrueBiasedRegions.count(RI.R) ||1622Scope->FalseBiasedRegions.count(RI.R))1623return true;1624for (SelectInst *SI : RI.Selects)1625if (Scope->TrueBiasedSelects.count(SI) ||1626Scope->FalseBiasedSelects.count(SI))1627return true;1628return false;1629};1630for (RegInfo &RI : Scope->CHRRegions) {1631assert(HasBiasedBranchOrSelect(RI, Scope) &&1632"Must have biased branch or select");1633}1634#endif1635}16361637// Assert that all the condition values of the biased branches and selects have1638// been hoisted to the pre-entry block or outside of the scope.1639static void LLVM_ATTRIBUTE_UNUSED assertBranchOrSelectConditionHoisted(1640CHRScope *Scope, BasicBlock *PreEntryBlock) {1641CHR_DEBUG(dbgs() << "Biased regions condition values \n");1642for (RegInfo &RI : Scope->CHRRegions) {1643Region *R = RI.R;1644bool IsTrueBiased = Scope->TrueBiasedRegions.count(R);1645bool IsFalseBiased = Scope->FalseBiasedRegions.count(R);1646if (RI.HasBranch && (IsTrueBiased || IsFalseBiased)) {1647auto *BI = cast<BranchInst>(R->getEntry()->getTerminator());1648Value *V = BI->getCondition();1649CHR_DEBUG(dbgs() << *V << "\n");1650if (auto *I = dyn_cast<Instruction>(V)) {1651(void)(I); // Unused in release build.1652assert((I->getParent() == PreEntryBlock ||1653!Scope->contains(I)) &&1654"Must have been hoisted to PreEntryBlock or outside the scope");1655}1656}1657for (SelectInst *SI : RI.Selects) {1658bool IsTrueBiased = Scope->TrueBiasedSelects.count(SI);1659bool IsFalseBiased = Scope->FalseBiasedSelects.count(SI);1660if (!(IsTrueBiased || IsFalseBiased))1661continue;1662Value *V = SI->getCondition();1663CHR_DEBUG(dbgs() << *V << "\n");1664if (auto *I = dyn_cast<Instruction>(V)) {1665(void)(I); // Unused in release build.1666assert((I->getParent() == PreEntryBlock ||1667!Scope->contains(I)) &&1668"Must have been hoisted to PreEntryBlock or outside the scope");1669}1670}1671}1672}16731674void CHR::transformScopes(CHRScope *Scope, DenseSet<PHINode *> &TrivialPHIs) {1675CHR_DEBUG(dbgs() << "transformScopes " << *Scope << "\n");16761677assert(Scope->RegInfos.size() >= 1 && "Should have at least one Region");16781679for (RegInfo &RI : Scope->RegInfos) {1680const Region *R = RI.R;1681unsigned Duplication = getRegionDuplicationCount(R);1682CHR_DEBUG(dbgs() << "Dup count for R=" << R << " is " << Duplication1683<< "\n");1684if (Duplication >= CHRDupThreshsold) {1685CHR_DEBUG(dbgs() << "Reached the dup threshold of " << Duplication1686<< " for this region");1687ORE.emit([&]() {1688return OptimizationRemarkMissed(DEBUG_TYPE, "DupThresholdReached",1689R->getEntry()->getTerminator())1690<< "Reached the duplication threshold for the region";1691});1692return;1693}1694}1695for (RegInfo &RI : Scope->RegInfos) {1696DuplicationCount[RI.R]++;1697}16981699Region *FirstRegion = Scope->RegInfos[0].R;1700BasicBlock *EntryBlock = FirstRegion->getEntry();1701Region *LastRegion = Scope->RegInfos[Scope->RegInfos.size() - 1].R;1702BasicBlock *ExitBlock = LastRegion->getExit();1703std::optional<uint64_t> ProfileCount = BFI.getBlockProfileCount(EntryBlock);17041705if (ExitBlock) {1706// Insert a trivial phi at the exit block (where the CHR hot path and the1707// cold path merges) for a value that's defined in the scope but used1708// outside it (meaning it's alive at the exit block). We will add the1709// incoming values for the CHR cold paths to it below. Without this, we'd1710// miss updating phi's for such values unless there happens to already be a1711// phi for that value there.1712insertTrivialPHIs(Scope, EntryBlock, ExitBlock, TrivialPHIs);1713}17141715// Split the entry block of the first region. The new block becomes the new1716// entry block of the first region. The old entry block becomes the block to1717// insert the CHR branch into. Note DT gets updated. Since DT gets updated1718// through the split, we update the entry of the first region after the split,1719// and Region only points to the entry and the exit blocks, rather than1720// keeping everything in a list or set, the blocks membership and the1721// entry/exit blocks of the region are still valid after the split.1722CHR_DEBUG(dbgs() << "Splitting entry block " << EntryBlock->getName()1723<< " at " << *Scope->BranchInsertPoint << "\n");1724BasicBlock *NewEntryBlock =1725SplitBlock(EntryBlock, Scope->BranchInsertPoint, &DT);1726assert(NewEntryBlock->getSinglePredecessor() == EntryBlock &&1727"NewEntryBlock's only pred must be EntryBlock");1728FirstRegion->replaceEntryRecursive(NewEntryBlock);1729BasicBlock *PreEntryBlock = EntryBlock;17301731ValueToValueMapTy VMap;1732// Clone the blocks in the scope (excluding the PreEntryBlock) to split into a1733// hot path (originals) and a cold path (clones) and update the PHIs at the1734// exit block.1735cloneScopeBlocks(Scope, PreEntryBlock, ExitBlock, LastRegion, VMap);17361737// Replace the old (placeholder) branch with the new (merged) conditional1738// branch.1739BranchInst *MergedBr = createMergedBranch(PreEntryBlock, EntryBlock,1740NewEntryBlock, VMap);17411742#ifndef NDEBUG1743assertCHRRegionsHaveBiasedBranchOrSelect(Scope);1744#endif17451746// Hoist the conditional values of the branches/selects.1747hoistScopeConditions(Scope, PreEntryBlock->getTerminator(), TrivialPHIs, DT);17481749#ifndef NDEBUG1750assertBranchOrSelectConditionHoisted(Scope, PreEntryBlock);1751#endif17521753// Create the combined branch condition and constant-fold the branches/selects1754// in the hot path.1755fixupBranchesAndSelects(Scope, PreEntryBlock, MergedBr,1756ProfileCount.value_or(0));1757}17581759// A helper for transformScopes. Clone the blocks in the scope (excluding the1760// PreEntryBlock) to split into a hot path and a cold path and update the PHIs1761// at the exit block.1762void CHR::cloneScopeBlocks(CHRScope *Scope,1763BasicBlock *PreEntryBlock,1764BasicBlock *ExitBlock,1765Region *LastRegion,1766ValueToValueMapTy &VMap) {1767// Clone all the blocks. The original blocks will be the hot-path1768// CHR-optimized code and the cloned blocks will be the original unoptimized1769// code. This is so that the block pointers from the1770// CHRScope/Region/RegionInfo can stay valid in pointing to the hot-path code1771// which CHR should apply to.1772SmallVector<BasicBlock*, 8> NewBlocks;1773for (RegInfo &RI : Scope->RegInfos)1774for (BasicBlock *BB : RI.R->blocks()) { // This includes the blocks in the1775// sub-Scopes.1776assert(BB != PreEntryBlock && "Don't copy the preetntry block");1777BasicBlock *NewBB = CloneBasicBlock(BB, VMap, ".nonchr", &F);1778NewBlocks.push_back(NewBB);1779VMap[BB] = NewBB;17801781// Unreachable predecessors will not be cloned and will not have an edge1782// to the cloned block. As such, also remove them from any phi nodes.1783for (PHINode &PN : make_early_inc_range(NewBB->phis()))1784PN.removeIncomingValueIf([&](unsigned Idx) {1785return !DT.isReachableFromEntry(PN.getIncomingBlock(Idx));1786});1787}17881789// Place the cloned blocks right after the original blocks (right before the1790// exit block of.)1791if (ExitBlock)1792F.splice(ExitBlock->getIterator(), &F, NewBlocks[0]->getIterator(),1793F.end());17941795// Update the cloned blocks/instructions to refer to themselves.1796for (BasicBlock *NewBB : NewBlocks)1797for (Instruction &I : *NewBB)1798RemapInstruction(&I, VMap,1799RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);18001801// Add the cloned blocks to the PHIs of the exit blocks. ExitBlock is null for1802// the top-level region but we don't need to add PHIs. The trivial PHIs1803// inserted above will be updated here.1804if (ExitBlock)1805for (PHINode &PN : ExitBlock->phis())1806for (unsigned I = 0, NumOps = PN.getNumIncomingValues(); I < NumOps;1807++I) {1808BasicBlock *Pred = PN.getIncomingBlock(I);1809if (LastRegion->contains(Pred)) {1810Value *V = PN.getIncomingValue(I);1811auto It = VMap.find(V);1812if (It != VMap.end()) V = It->second;1813assert(VMap.find(Pred) != VMap.end() && "Pred must have been cloned");1814PN.addIncoming(V, cast<BasicBlock>(VMap[Pred]));1815}1816}1817}18181819// A helper for transformScope. Replace the old (placeholder) branch with the1820// new (merged) conditional branch.1821BranchInst *CHR::createMergedBranch(BasicBlock *PreEntryBlock,1822BasicBlock *EntryBlock,1823BasicBlock *NewEntryBlock,1824ValueToValueMapTy &VMap) {1825BranchInst *OldBR = cast<BranchInst>(PreEntryBlock->getTerminator());1826assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == NewEntryBlock &&1827"SplitBlock did not work correctly!");1828assert(NewEntryBlock->getSinglePredecessor() == EntryBlock &&1829"NewEntryBlock's only pred must be EntryBlock");1830assert(VMap.find(NewEntryBlock) != VMap.end() &&1831"NewEntryBlock must have been copied");1832OldBR->dropAllReferences();1833OldBR->eraseFromParent();1834// The true predicate is a placeholder. It will be replaced later in1835// fixupBranchesAndSelects().1836BranchInst *NewBR = BranchInst::Create(NewEntryBlock,1837cast<BasicBlock>(VMap[NewEntryBlock]),1838ConstantInt::getTrue(F.getContext()));1839NewBR->insertInto(PreEntryBlock, PreEntryBlock->end());1840assert(NewEntryBlock->getSinglePredecessor() == EntryBlock &&1841"NewEntryBlock's only pred must be EntryBlock");1842return NewBR;1843}18441845// A helper for transformScopes. Create the combined branch condition and1846// constant-fold the branches/selects in the hot path.1847void CHR::fixupBranchesAndSelects(CHRScope *Scope,1848BasicBlock *PreEntryBlock,1849BranchInst *MergedBR,1850uint64_t ProfileCount) {1851Value *MergedCondition = ConstantInt::getTrue(F.getContext());1852BranchProbability CHRBranchBias(1, 1);1853uint64_t NumCHRedBranches = 0;1854IRBuilder<> IRB(PreEntryBlock->getTerminator());1855for (RegInfo &RI : Scope->CHRRegions) {1856Region *R = RI.R;1857if (RI.HasBranch) {1858fixupBranch(R, Scope, IRB, MergedCondition, CHRBranchBias);1859++NumCHRedBranches;1860}1861for (SelectInst *SI : RI.Selects) {1862fixupSelect(SI, Scope, IRB, MergedCondition, CHRBranchBias);1863++NumCHRedBranches;1864}1865}1866Stats.NumBranchesDelta += NumCHRedBranches - 1;1867Stats.WeightedNumBranchesDelta += (NumCHRedBranches - 1) * ProfileCount;1868ORE.emit([&]() {1869return OptimizationRemark(DEBUG_TYPE,1870"CHR",1871// Refer to the hot (original) path1872MergedBR->getSuccessor(0)->getTerminator())1873<< "Merged " << ore::NV("NumCHRedBranches", NumCHRedBranches)1874<< " branches or selects";1875});1876MergedBR->setCondition(MergedCondition);1877uint32_t Weights[] = {1878static_cast<uint32_t>(CHRBranchBias.scale(1000)),1879static_cast<uint32_t>(CHRBranchBias.getCompl().scale(1000)),1880};1881setBranchWeights(*MergedBR, Weights, /*IsExpected=*/false);1882CHR_DEBUG(dbgs() << "CHR branch bias " << Weights[0] << ":" << Weights[1]1883<< "\n");1884}18851886// A helper for fixupBranchesAndSelects. Add to the combined branch condition1887// and constant-fold a branch in the hot path.1888void CHR::fixupBranch(Region *R, CHRScope *Scope,1889IRBuilder<> &IRB,1890Value *&MergedCondition,1891BranchProbability &CHRBranchBias) {1892bool IsTrueBiased = Scope->TrueBiasedRegions.count(R);1893assert((IsTrueBiased || Scope->FalseBiasedRegions.count(R)) &&1894"Must be truthy or falsy");1895auto *BI = cast<BranchInst>(R->getEntry()->getTerminator());1896assert(BranchBiasMap.contains(R) && "Must be in the bias map");1897BranchProbability Bias = BranchBiasMap[R];1898assert(Bias >= getCHRBiasThreshold() && "Must be highly biased");1899// Take the min.1900if (CHRBranchBias > Bias)1901CHRBranchBias = Bias;1902BasicBlock *IfThen = BI->getSuccessor(1);1903BasicBlock *IfElse = BI->getSuccessor(0);1904BasicBlock *RegionExitBlock = R->getExit();1905assert(RegionExitBlock && "Null ExitBlock");1906assert((IfThen == RegionExitBlock || IfElse == RegionExitBlock) &&1907IfThen != IfElse && "Invariant from findScopes");1908if (IfThen == RegionExitBlock) {1909// Swap them so that IfThen means going into it and IfElse means skipping1910// it.1911std::swap(IfThen, IfElse);1912}1913CHR_DEBUG(dbgs() << "IfThen " << IfThen->getName()1914<< " IfElse " << IfElse->getName() << "\n");1915Value *Cond = BI->getCondition();1916BasicBlock *HotTarget = IsTrueBiased ? IfThen : IfElse;1917bool ConditionTrue = HotTarget == BI->getSuccessor(0);1918addToMergedCondition(ConditionTrue, Cond, BI, Scope, IRB,1919MergedCondition);1920// Constant-fold the branch at ClonedEntryBlock.1921assert(ConditionTrue == (HotTarget == BI->getSuccessor(0)) &&1922"The successor shouldn't change");1923Value *NewCondition = ConditionTrue ?1924ConstantInt::getTrue(F.getContext()) :1925ConstantInt::getFalse(F.getContext());1926BI->setCondition(NewCondition);1927}19281929// A helper for fixupBranchesAndSelects. Add to the combined branch condition1930// and constant-fold a select in the hot path.1931void CHR::fixupSelect(SelectInst *SI, CHRScope *Scope,1932IRBuilder<> &IRB,1933Value *&MergedCondition,1934BranchProbability &CHRBranchBias) {1935bool IsTrueBiased = Scope->TrueBiasedSelects.count(SI);1936assert((IsTrueBiased ||1937Scope->FalseBiasedSelects.count(SI)) && "Must be biased");1938assert(SelectBiasMap.contains(SI) && "Must be in the bias map");1939BranchProbability Bias = SelectBiasMap[SI];1940assert(Bias >= getCHRBiasThreshold() && "Must be highly biased");1941// Take the min.1942if (CHRBranchBias > Bias)1943CHRBranchBias = Bias;1944Value *Cond = SI->getCondition();1945addToMergedCondition(IsTrueBiased, Cond, SI, Scope, IRB,1946MergedCondition);1947Value *NewCondition = IsTrueBiased ?1948ConstantInt::getTrue(F.getContext()) :1949ConstantInt::getFalse(F.getContext());1950SI->setCondition(NewCondition);1951}19521953// A helper for fixupBranch/fixupSelect. Add a branch condition to the merged1954// condition.1955void CHR::addToMergedCondition(bool IsTrueBiased, Value *Cond,1956Instruction *BranchOrSelect, CHRScope *Scope,1957IRBuilder<> &IRB, Value *&MergedCondition) {1958if (!IsTrueBiased) {1959// If Cond is an icmp and all users of V except for BranchOrSelect is a1960// branch, negate the icmp predicate and swap the branch targets and avoid1961// inserting an Xor to negate Cond.1962auto *ICmp = dyn_cast<ICmpInst>(Cond);1963if (!ICmp ||1964!negateICmpIfUsedByBranchOrSelectOnly(ICmp, BranchOrSelect, Scope))1965Cond = IRB.CreateXor(ConstantInt::getTrue(F.getContext()), Cond);1966}19671968// Freeze potentially poisonous conditions.1969if (!isGuaranteedNotToBeUndefOrPoison(Cond))1970Cond = IRB.CreateFreeze(Cond);19711972// Use logical and to avoid propagating poison from later conditions.1973MergedCondition = IRB.CreateLogicalAnd(MergedCondition, Cond);1974}19751976void CHR::transformScopes(SmallVectorImpl<CHRScope *> &CHRScopes) {1977unsigned I = 0;1978DenseSet<PHINode *> TrivialPHIs;1979for (CHRScope *Scope : CHRScopes) {1980transformScopes(Scope, TrivialPHIs);1981CHR_DEBUG(1982std::ostringstream oss;1983oss << " after transformScopes " << I++;1984dumpIR(F, oss.str().c_str(), nullptr));1985(void)I;1986}1987}19881989static void LLVM_ATTRIBUTE_UNUSED1990dumpScopes(SmallVectorImpl<CHRScope *> &Scopes, const char *Label) {1991dbgs() << Label << " " << Scopes.size() << "\n";1992for (CHRScope *Scope : Scopes) {1993dbgs() << *Scope << "\n";1994}1995}19961997bool CHR::run() {1998if (!shouldApply(F, PSI))1999return false;20002001CHR_DEBUG(dumpIR(F, "before", nullptr));20022003bool Changed = false;2004{2005CHR_DEBUG(2006dbgs() << "RegionInfo:\n";2007RI.print(dbgs()));20082009// Recursively traverse the region tree and find regions that have biased2010// branches and/or selects and create scopes.2011SmallVector<CHRScope *, 8> AllScopes;2012findScopes(AllScopes);2013CHR_DEBUG(dumpScopes(AllScopes, "All scopes"));20142015// Split the scopes if 1) the conditional values of the biased2016// branches/selects of the inner/lower scope can't be hoisted up to the2017// outermost/uppermost scope entry, or 2) the condition values of the biased2018// branches/selects in a scope (including subscopes) don't share at least2019// one common value.2020SmallVector<CHRScope *, 8> SplitScopes;2021splitScopes(AllScopes, SplitScopes);2022CHR_DEBUG(dumpScopes(SplitScopes, "Split scopes"));20232024// After splitting, set the biased regions and selects of a scope (a tree2025// root) that include those of the subscopes.2026classifyBiasedScopes(SplitScopes);2027CHR_DEBUG(dbgs() << "Set per-scope bias " << SplitScopes.size() << "\n");20282029// Filter out the scopes that has only one biased region or select (CHR2030// isn't useful in such a case).2031SmallVector<CHRScope *, 8> FilteredScopes;2032filterScopes(SplitScopes, FilteredScopes);2033CHR_DEBUG(dumpScopes(FilteredScopes, "Filtered scopes"));20342035// Set the regions to be CHR'ed and their hoist stops for each scope.2036SmallVector<CHRScope *, 8> SetScopes;2037setCHRRegions(FilteredScopes, SetScopes);2038CHR_DEBUG(dumpScopes(SetScopes, "Set CHR regions"));20392040// Sort CHRScopes by the depth so that outer CHRScopes comes before inner2041// ones. We need to apply CHR from outer to inner so that we apply CHR only2042// to the hot path, rather than both hot and cold paths.2043SmallVector<CHRScope *, 8> SortedScopes;2044sortScopes(SetScopes, SortedScopes);2045CHR_DEBUG(dumpScopes(SortedScopes, "Sorted scopes"));20462047CHR_DEBUG(2048dbgs() << "RegionInfo:\n";2049RI.print(dbgs()));20502051// Apply the CHR transformation.2052if (!SortedScopes.empty()) {2053transformScopes(SortedScopes);2054Changed = true;2055}2056}20572058if (Changed) {2059CHR_DEBUG(dumpIR(F, "after", &Stats));2060ORE.emit([&]() {2061return OptimizationRemark(DEBUG_TYPE, "Stats", &F)2062<< ore::NV("Function", &F) << " "2063<< "Reduced the number of branches in hot paths by "2064<< ore::NV("NumBranchesDelta", Stats.NumBranchesDelta)2065<< " (static) and "2066<< ore::NV("WeightedNumBranchesDelta", Stats.WeightedNumBranchesDelta)2067<< " (weighted by PGO count)";2068});2069}20702071return Changed;2072}20732074namespace llvm {20752076ControlHeightReductionPass::ControlHeightReductionPass() {2077parseCHRFilterFiles();2078}20792080PreservedAnalyses ControlHeightReductionPass::run(2081Function &F,2082FunctionAnalysisManager &FAM) {2083auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);2084auto PPSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());2085// If there is no profile summary, we should not do CHR.2086if (!PPSI || !PPSI->hasProfileSummary())2087return PreservedAnalyses::all();2088auto &PSI = *PPSI;2089auto &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);2090auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);2091auto &RI = FAM.getResult<RegionInfoAnalysis>(F);2092auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);2093bool Changed = CHR(F, BFI, DT, PSI, RI, ORE).run();2094if (!Changed)2095return PreservedAnalyses::all();2096return PreservedAnalyses::none();2097}20982099} // namespace llvm210021012102