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