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