LLVM 20.0.0git
DFAJumpThreading.cpp
Go to the documentation of this file.
1//===- DFAJumpThreading.cpp - Threads a switch statement inside a loop ----===//
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// Transform each threading path to effectively jump thread the DFA. For
10// example, the CFG below could be transformed as follows, where the cloned
11// blocks unconditionally branch to the next correct case based on what is
12// identified in the analysis.
13//
14// sw.bb sw.bb
15// / | \ / | \
16// case1 case2 case3 case1 case2 case3
17// \ | / | | |
18// determinator det.2 det.3 det.1
19// br sw.bb / | \
20// sw.bb.2 sw.bb.3 sw.bb.1
21// br case2 br case3 br case1ยง
22//
23// Definitions and Terminology:
24//
25// * Threading path:
26// a list of basic blocks, the exit state, and the block that determines
27// the next state, for which the following notation will be used:
28// < path of BBs that form a cycle > [ state, determinator ]
29//
30// * Predictable switch:
31// The switch variable is always a known constant so that all conditional
32// jumps based on switch variable can be converted to unconditional jump.
33//
34// * Determinator:
35// The basic block that determines the next state of the DFA.
36//
37// Representing the optimization in C-like pseudocode: the code pattern on the
38// left could functionally be transformed to the right pattern if the switch
39// condition is predictable.
40//
41// X = A goto A
42// for (...) A:
43// switch (X) ...
44// case A goto B
45// X = B B:
46// case B ...
47// X = C goto C
48//
49// The pass first checks that switch variable X is decided by the control flow
50// path taken in the loop; for example, in case B, the next value of X is
51// decided to be C. It then enumerates through all paths in the loop and labels
52// the basic blocks where the next state is decided.
53//
54// Using this information it creates new paths that unconditionally branch to
55// the next case. This involves cloning code, so it only gets triggered if the
56// amount of code duplicated is below a threshold.
57//
58//===----------------------------------------------------------------------===//
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/DenseMap.h"
63#include "llvm/ADT/SmallSet.h"
64#include "llvm/ADT/Statistic.h"
71#include "llvm/IR/CFG.h"
72#include "llvm/IR/Constants.h"
75#include "llvm/Support/Debug.h"
79#include <algorithm>
80#include <deque>
81
82#ifdef EXPENSIVE_CHECKS
83#include "llvm/IR/Verifier.h"
84#endif
85
86using namespace llvm;
87
88#define DEBUG_TYPE "dfa-jump-threading"
89
90STATISTIC(NumTransforms, "Number of transformations done");
91STATISTIC(NumCloned, "Number of blocks cloned");
92STATISTIC(NumPaths, "Number of individual paths threaded");
93
94static cl::opt<bool>
95 ClViewCfgBefore("dfa-jump-view-cfg-before",
96 cl::desc("View the CFG before DFA Jump Threading"),
97 cl::Hidden, cl::init(false));
98
100 "dfa-early-exit-heuristic",
101 cl::desc("Exit early if an unpredictable value come from the same loop"),
102 cl::Hidden, cl::init(true));
103
105 "dfa-max-path-length",
106 cl::desc("Max number of blocks searched to find a threading path"),
107 cl::Hidden, cl::init(20));
108
110 "dfa-max-num-visited-paths",
111 cl::desc(
112 "Max number of blocks visited while enumerating paths around a switch"),
113 cl::Hidden, cl::init(2000));
114
116 MaxNumPaths("dfa-max-num-paths",
117 cl::desc("Max number of paths enumerated around a switch"),
118 cl::Hidden, cl::init(200));
119
121 CostThreshold("dfa-cost-threshold",
122 cl::desc("Maximum cost accepted for the transformation"),
123 cl::Hidden, cl::init(50));
124
125namespace {
126
127class SelectInstToUnfold {
128 SelectInst *SI;
129 PHINode *SIUse;
130
131public:
132 SelectInstToUnfold(SelectInst *SI, PHINode *SIUse) : SI(SI), SIUse(SIUse) {}
133
134 SelectInst *getInst() { return SI; }
135 PHINode *getUse() { return SIUse; }
136
137 explicit operator bool() const { return SI && SIUse; }
138};
139
140void unfold(DomTreeUpdater *DTU, LoopInfo *LI, SelectInstToUnfold SIToUnfold,
141 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
142 std::vector<BasicBlock *> *NewBBs);
143
144class DFAJumpThreading {
145public:
146 DFAJumpThreading(AssumptionCache *AC, DominatorTree *DT, LoopInfo *LI,
148 : AC(AC), DT(DT), LI(LI), TTI(TTI), ORE(ORE) {}
149
150 bool run(Function &F);
151 bool LoopInfoBroken;
152
153private:
154 void
155 unfoldSelectInstrs(DominatorTree *DT,
156 const SmallVector<SelectInstToUnfold, 4> &SelectInsts) {
157 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
159
160 while (!Stack.empty()) {
161 SelectInstToUnfold SIToUnfold = Stack.pop_back_val();
162
163 std::vector<SelectInstToUnfold> NewSIsToUnfold;
164 std::vector<BasicBlock *> NewBBs;
165 unfold(&DTU, LI, SIToUnfold, &NewSIsToUnfold, &NewBBs);
166
167 // Put newly discovered select instructions into the work list.
168 for (const SelectInstToUnfold &NewSIToUnfold : NewSIsToUnfold)
169 Stack.push_back(NewSIToUnfold);
170 }
171 }
172
173 AssumptionCache *AC;
174 DominatorTree *DT;
175 LoopInfo *LI;
178};
179
180} // end anonymous namespace
181
182namespace {
183
184/// Unfold the select instruction held in \p SIToUnfold by replacing it with
185/// control flow.
186///
187/// Put newly discovered select instructions into \p NewSIsToUnfold. Put newly
188/// created basic blocks into \p NewBBs.
189///
190/// TODO: merge it with CodeGenPrepare::optimizeSelectInst() if possible.
191void unfold(DomTreeUpdater *DTU, LoopInfo *LI, SelectInstToUnfold SIToUnfold,
192 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
193 std::vector<BasicBlock *> *NewBBs) {
194 SelectInst *SI = SIToUnfold.getInst();
195 PHINode *SIUse = SIToUnfold.getUse();
196 BasicBlock *StartBlock = SI->getParent();
197 BasicBlock *EndBlock = SIUse->getParent();
198 BranchInst *StartBlockTerm =
199 dyn_cast<BranchInst>(StartBlock->getTerminator());
200
201 assert(StartBlockTerm);
202 assert(SI->hasOneUse());
203
204 if (StartBlockTerm->isUnconditional()) {
205 // Arbitrarily choose the 'false' side for a new input value to the PHI.
206 BasicBlock *NewBlock = BasicBlock::Create(
207 SI->getContext(), Twine(SI->getName(), ".si.unfold.false"),
208 EndBlock->getParent(), EndBlock);
209 NewBBs->push_back(NewBlock);
210 BranchInst::Create(EndBlock, NewBlock);
211 DTU->applyUpdates({{DominatorTree::Insert, NewBlock, EndBlock}});
212
213 // StartBlock
214 // | \
215 // | NewBlock
216 // | /
217 // EndBlock
218 Value *SIOp1 = SI->getTrueValue();
219 Value *SIOp2 = SI->getFalseValue();
220
221 PHINode *NewPhi = PHINode::Create(SIUse->getType(), 1,
222 Twine(SIOp2->getName(), ".si.unfold.phi"),
223 NewBlock->getFirstInsertionPt());
224 NewPhi->addIncoming(SIOp2, StartBlock);
225
226 if (auto *OpSi = dyn_cast<SelectInst>(SIOp1))
227 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, SIUse));
228 if (auto *OpSi = dyn_cast<SelectInst>(SIOp2))
229 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, NewPhi));
230
231 // Update the phi node of SI.
232 for (unsigned Idx = 0; Idx < SIUse->getNumIncomingValues(); ++Idx) {
233 if (SIUse->getIncomingBlock(Idx) == StartBlock)
234 SIUse->setIncomingValue(Idx, SIOp1);
235 }
236 SIUse->addIncoming(NewPhi, NewBlock);
237
238 // Update any other PHI nodes in EndBlock.
239 for (auto II = EndBlock->begin(); PHINode *Phi = dyn_cast<PHINode>(II);
240 ++II) {
241 if (Phi != SIUse)
242 Phi->addIncoming(Phi->getIncomingValueForBlock(StartBlock), NewBlock);
243 }
244
245 StartBlockTerm->eraseFromParent();
246
247 // Insert the real conditional branch based on the original condition.
248 BranchInst::Create(EndBlock, NewBlock, SI->getCondition(), StartBlock);
249 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, EndBlock},
250 {DominatorTree::Insert, StartBlock, NewBlock}});
251 } else {
252 BasicBlock *NewBlockT = BasicBlock::Create(
253 SI->getContext(), Twine(SI->getName(), ".si.unfold.true"),
254 EndBlock->getParent(), EndBlock);
255 BasicBlock *NewBlockF = BasicBlock::Create(
256 SI->getContext(), Twine(SI->getName(), ".si.unfold.false"),
257 EndBlock->getParent(), EndBlock);
258
259 NewBBs->push_back(NewBlockT);
260 NewBBs->push_back(NewBlockF);
261
262 // Def only has one use in EndBlock.
263 // Before transformation:
264 // StartBlock(Def)
265 // | \
266 // EndBlock OtherBlock
267 // (Use)
268 //
269 // After transformation:
270 // StartBlock(Def)
271 // | \
272 // | OtherBlock
273 // NewBlockT
274 // | \
275 // | NewBlockF
276 // | /
277 // | /
278 // EndBlock
279 // (Use)
280 BranchInst::Create(EndBlock, NewBlockF);
281 // Insert the real conditional branch based on the original condition.
282 BranchInst::Create(EndBlock, NewBlockF, SI->getCondition(), NewBlockT);
283 DTU->applyUpdates({{DominatorTree::Insert, NewBlockT, NewBlockF},
284 {DominatorTree::Insert, NewBlockT, EndBlock},
285 {DominatorTree::Insert, NewBlockF, EndBlock}});
286
287 Value *TrueVal = SI->getTrueValue();
288 Value *FalseVal = SI->getFalseValue();
289
290 PHINode *NewPhiT = PHINode::Create(
291 SIUse->getType(), 1, Twine(TrueVal->getName(), ".si.unfold.phi"),
292 NewBlockT->getFirstInsertionPt());
293 PHINode *NewPhiF = PHINode::Create(
294 SIUse->getType(), 1, Twine(FalseVal->getName(), ".si.unfold.phi"),
295 NewBlockF->getFirstInsertionPt());
296 NewPhiT->addIncoming(TrueVal, StartBlock);
297 NewPhiF->addIncoming(FalseVal, NewBlockT);
298
299 if (auto *TrueSI = dyn_cast<SelectInst>(TrueVal))
300 NewSIsToUnfold->push_back(SelectInstToUnfold(TrueSI, NewPhiT));
301 if (auto *FalseSi = dyn_cast<SelectInst>(FalseVal))
302 NewSIsToUnfold->push_back(SelectInstToUnfold(FalseSi, NewPhiF));
303
304 SIUse->addIncoming(NewPhiT, NewBlockT);
305 SIUse->addIncoming(NewPhiF, NewBlockF);
306 SIUse->removeIncomingValue(StartBlock);
307
308 // Update any other PHI nodes in EndBlock.
309 for (PHINode &Phi : EndBlock->phis()) {
310 if (SIUse == &Phi)
311 continue;
312 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), NewBlockT);
313 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), NewBlockF);
314 Phi.removeIncomingValue(StartBlock);
315 }
316
317 // Update the appropriate successor of the start block to point to the new
318 // unfolded block.
319 unsigned SuccNum = StartBlockTerm->getSuccessor(1) == EndBlock ? 1 : 0;
320 StartBlockTerm->setSuccessor(SuccNum, NewBlockT);
321 DTU->applyUpdates({{DominatorTree::Delete, StartBlock, EndBlock},
322 {DominatorTree::Insert, StartBlock, NewBlockT}});
323 }
324
325 // Preserve loop info
326 if (Loop *L = LI->getLoopFor(SI->getParent())) {
327 for (BasicBlock *NewBB : *NewBBs)
328 L->addBasicBlockToLoop(NewBB, *LI);
329 }
330
331 // The select is now dead.
332 assert(SI->use_empty() && "Select must be dead now");
333 SI->eraseFromParent();
334}
335
336struct ClonedBlock {
337 BasicBlock *BB;
338 APInt State; ///< \p State corresponds to the next value of a switch stmnt.
339};
340
341typedef std::deque<BasicBlock *> PathType;
342typedef std::vector<PathType> PathsType;
343typedef SmallPtrSet<const BasicBlock *, 8> VisitedBlocks;
344typedef std::vector<ClonedBlock> CloneList;
345
346// This data structure keeps track of all blocks that have been cloned. If two
347// different ThreadingPaths clone the same block for a certain state it should
348// be reused, and it can be looked up in this map.
349typedef DenseMap<BasicBlock *, CloneList> DuplicateBlockMap;
350
351// This map keeps track of all the new definitions for an instruction. This
352// information is needed when restoring SSA form after cloning blocks.
354
355inline raw_ostream &operator<<(raw_ostream &OS, const PathType &Path) {
356 OS << "< ";
357 for (const BasicBlock *BB : Path) {
358 std::string BBName;
359 if (BB->hasName())
360 raw_string_ostream(BBName) << BB->getName();
361 else
362 raw_string_ostream(BBName) << BB;
363 OS << BBName << " ";
364 }
365 OS << ">";
366 return OS;
367}
368
369/// ThreadingPath is a path in the control flow of a loop that can be threaded
370/// by cloning necessary basic blocks and replacing conditional branches with
371/// unconditional ones. A threading path includes a list of basic blocks, the
372/// exit state, and the block that determines the next state.
373struct ThreadingPath {
374 /// Exit value is DFA's exit state for the given path.
375 APInt getExitValue() const { return ExitVal; }
376 void setExitValue(const ConstantInt *V) {
377 ExitVal = V->getValue();
378 IsExitValSet = true;
379 }
380 bool isExitValueSet() const { return IsExitValSet; }
381
382 /// Determinator is the basic block that determines the next state of the DFA.
383 const BasicBlock *getDeterminatorBB() const { return DBB; }
384 void setDeterminator(const BasicBlock *BB) { DBB = BB; }
385
386 /// Path is a list of basic blocks.
387 const PathType &getPath() const { return Path; }
388 void setPath(const PathType &NewPath) { Path = NewPath; }
389 void push_back(BasicBlock *BB) { Path.push_back(BB); }
390 void push_front(BasicBlock *BB) { Path.push_front(BB); }
391 void appendExcludingFirst(const PathType &OtherPath) {
392 Path.insert(Path.end(), OtherPath.begin() + 1, OtherPath.end());
393 }
394
395 void print(raw_ostream &OS) const {
396 OS << Path << " [ " << ExitVal << ", " << DBB->getName() << " ]";
397 }
398
399private:
400 PathType Path;
401 APInt ExitVal;
402 const BasicBlock *DBB = nullptr;
403 bool IsExitValSet = false;
404};
405
406#ifndef NDEBUG
407inline raw_ostream &operator<<(raw_ostream &OS, const ThreadingPath &TPath) {
408 TPath.print(OS);
409 return OS;
410}
411#endif
412
413struct MainSwitch {
414 MainSwitch(SwitchInst *SI, LoopInfo *LI, OptimizationRemarkEmitter *ORE)
415 : LI(LI) {
416 if (isCandidate(SI)) {
417 Instr = SI;
418 } else {
419 ORE->emit([&]() {
420 return OptimizationRemarkMissed(DEBUG_TYPE, "SwitchNotPredictable", SI)
421 << "Switch instruction is not predictable.";
422 });
423 }
424 }
425
426 virtual ~MainSwitch() = default;
427
428 SwitchInst *getInstr() const { return Instr; }
429 const SmallVector<SelectInstToUnfold, 4> getSelectInsts() {
430 return SelectInsts;
431 }
432
433private:
434 /// Do a use-def chain traversal starting from the switch condition to see if
435 /// \p SI is a potential condidate.
436 ///
437 /// Also, collect select instructions to unfold.
438 bool isCandidate(const SwitchInst *SI) {
439 std::deque<std::pair<Value *, BasicBlock *>> Q;
440 SmallSet<Value *, 16> SeenValues;
441 SelectInsts.clear();
442
443 Value *SICond = SI->getCondition();
444 LLVM_DEBUG(dbgs() << "\tSICond: " << *SICond << "\n");
445 if (!isa<PHINode>(SICond))
446 return false;
447
448 // The switch must be in a loop.
449 const Loop *L = LI->getLoopFor(SI->getParent());
450 if (!L)
451 return false;
452
453 addToQueue(SICond, nullptr, Q, SeenValues);
454
455 while (!Q.empty()) {
456 Value *Current = Q.front().first;
457 BasicBlock *CurrentIncomingBB = Q.front().second;
458 Q.pop_front();
459
460 if (auto *Phi = dyn_cast<PHINode>(Current)) {
461 for (BasicBlock *IncomingBB : Phi->blocks()) {
462 Value *Incoming = Phi->getIncomingValueForBlock(IncomingBB);
463 addToQueue(Incoming, IncomingBB, Q, SeenValues);
464 }
465 LLVM_DEBUG(dbgs() << "\tphi: " << *Phi << "\n");
466 } else if (SelectInst *SelI = dyn_cast<SelectInst>(Current)) {
467 if (!isValidSelectInst(SelI))
468 return false;
469 addToQueue(SelI->getTrueValue(), CurrentIncomingBB, Q, SeenValues);
470 addToQueue(SelI->getFalseValue(), CurrentIncomingBB, Q, SeenValues);
471 LLVM_DEBUG(dbgs() << "\tselect: " << *SelI << "\n");
472 if (auto *SelIUse = dyn_cast<PHINode>(SelI->user_back()))
473 SelectInsts.push_back(SelectInstToUnfold(SelI, SelIUse));
474 } else if (isa<Constant>(Current)) {
475 LLVM_DEBUG(dbgs() << "\tconst: " << *Current << "\n");
476 continue;
477 } else {
478 LLVM_DEBUG(dbgs() << "\tother: " << *Current << "\n");
479 // Allow unpredictable values. The hope is that those will be the
480 // initial switch values that can be ignored (they will hit the
481 // unthreaded switch) but this assumption will get checked later after
482 // paths have been enumerated (in function getStateDefMap).
483
484 // If the unpredictable value comes from the same inner loop it is
485 // likely that it will also be on the enumerated paths, causing us to
486 // exit after we have enumerated all the paths. This heuristic save
487 // compile time because a search for all the paths can become expensive.
488 if (EarlyExitHeuristic &&
489 L->contains(LI->getLoopFor(CurrentIncomingBB))) {
491 << "\tExiting early due to unpredictability heuristic.\n");
492 return false;
493 }
494
495 continue;
496 }
497 }
498
499 return true;
500 }
501
502 void addToQueue(Value *Val, BasicBlock *BB,
503 std::deque<std::pair<Value *, BasicBlock *>> &Q,
504 SmallSet<Value *, 16> &SeenValues) {
505 if (SeenValues.contains(Val))
506 return;
507 Q.push_back({Val, BB});
508 SeenValues.insert(Val);
509 }
510
511 bool isValidSelectInst(SelectInst *SI) {
512 if (!SI->hasOneUse())
513 return false;
514
515 Instruction *SIUse = dyn_cast<Instruction>(SI->user_back());
516 // The use of the select inst should be either a phi or another select.
517 if (!SIUse && !(isa<PHINode>(SIUse) || isa<SelectInst>(SIUse)))
518 return false;
519
520 BasicBlock *SIBB = SI->getParent();
521
522 // Currently, we can only expand select instructions in basic blocks with
523 // one successor.
524 BranchInst *SITerm = dyn_cast<BranchInst>(SIBB->getTerminator());
525 if (!SITerm || !SITerm->isUnconditional())
526 return false;
527
528 // Only fold the select coming from directly where it is defined.
529 PHINode *PHIUser = dyn_cast<PHINode>(SIUse);
530 if (PHIUser && PHIUser->getIncomingBlock(*SI->use_begin()) != SIBB)
531 return false;
532
533 // If select will not be sunk during unfolding, and it is in the same basic
534 // block as another state defining select, then cannot unfold both.
535 for (SelectInstToUnfold SIToUnfold : SelectInsts) {
536 SelectInst *PrevSI = SIToUnfold.getInst();
537 if (PrevSI->getTrueValue() != SI && PrevSI->getFalseValue() != SI &&
538 PrevSI->getParent() == SI->getParent())
539 return false;
540 }
541
542 return true;
543 }
544
545 LoopInfo *LI;
546 SwitchInst *Instr = nullptr;
548};
549
550struct AllSwitchPaths {
551 AllSwitchPaths(const MainSwitch *MSwitch, OptimizationRemarkEmitter *ORE,
552 LoopInfo *LI, Loop *L)
553 : Switch(MSwitch->getInstr()), SwitchBlock(Switch->getParent()), ORE(ORE),
554 LI(LI), SwitchOuterLoop(L) {}
555
556 std::vector<ThreadingPath> &getThreadingPaths() { return TPaths; }
557 unsigned getNumThreadingPaths() { return TPaths.size(); }
558 SwitchInst *getSwitchInst() { return Switch; }
559 BasicBlock *getSwitchBlock() { return SwitchBlock; }
560
561 void run() {
562 StateDefMap StateDef = getStateDefMap();
563 if (StateDef.empty()) {
564 ORE->emit([&]() {
565 return OptimizationRemarkMissed(DEBUG_TYPE, "SwitchNotPredictable",
566 Switch)
567 << "Switch instruction is not predictable.";
568 });
569 return;
570 }
571
572 auto *SwitchPhi = cast<PHINode>(Switch->getOperand(0));
573 auto *SwitchPhiDefBB = SwitchPhi->getParent();
574 VisitedBlocks VB;
575 // Get paths from the determinator BBs to SwitchPhiDefBB
576 std::vector<ThreadingPath> PathsToPhiDef =
577 getPathsFromStateDefMap(StateDef, SwitchPhi, VB);
578 if (SwitchPhiDefBB == SwitchBlock) {
579 TPaths = std::move(PathsToPhiDef);
580 return;
581 }
582
583 // Find and append paths from SwitchPhiDefBB to SwitchBlock.
584 PathsType PathsToSwitchBB =
585 paths(SwitchPhiDefBB, SwitchBlock, VB, /* PathDepth = */ 1);
586 if (PathsToSwitchBB.empty())
587 return;
588
589 std::vector<ThreadingPath> TempList;
590 for (const ThreadingPath &Path : PathsToPhiDef) {
591 for (const PathType &PathToSw : PathsToSwitchBB) {
592 ThreadingPath PathCopy(Path);
593 PathCopy.appendExcludingFirst(PathToSw);
594 TempList.push_back(PathCopy);
595 }
596 }
597 TPaths = std::move(TempList);
598 }
599
600private:
601 // Value: an instruction that defines a switch state;
602 // Key: the parent basic block of that instruction.
604 std::vector<ThreadingPath> getPathsFromStateDefMap(StateDefMap &StateDef,
605 PHINode *Phi,
606 VisitedBlocks &VB) {
607 std::vector<ThreadingPath> Res;
608 auto *PhiBB = Phi->getParent();
609 VB.insert(PhiBB);
610
611 VisitedBlocks UniqueBlocks;
612 for (auto *IncomingBB : Phi->blocks()) {
613 if (!UniqueBlocks.insert(IncomingBB).second)
614 continue;
615 if (!SwitchOuterLoop->contains(IncomingBB))
616 continue;
617
618 Value *IncomingValue = Phi->getIncomingValueForBlock(IncomingBB);
619 // We found the determinator. This is the start of our path.
620 if (auto *C = dyn_cast<ConstantInt>(IncomingValue)) {
621 // SwitchBlock is the determinator, unsupported unless its also the def.
622 if (PhiBB == SwitchBlock &&
623 SwitchBlock != cast<PHINode>(Switch->getOperand(0))->getParent())
624 continue;
625 ThreadingPath NewPath;
626 NewPath.setDeterminator(PhiBB);
627 NewPath.setExitValue(C);
628 // Don't add SwitchBlock at the start, this is handled later.
629 if (IncomingBB != SwitchBlock)
630 NewPath.push_back(IncomingBB);
631 NewPath.push_back(PhiBB);
632 Res.push_back(NewPath);
633 continue;
634 }
635 // Don't get into a cycle.
636 if (VB.contains(IncomingBB) || IncomingBB == SwitchBlock)
637 continue;
638 // Recurse up the PHI chain.
639 auto *IncomingPhi = dyn_cast<PHINode>(IncomingValue);
640 if (!IncomingPhi)
641 continue;
642 auto *IncomingPhiDefBB = IncomingPhi->getParent();
643 if (!StateDef.contains(IncomingPhiDefBB))
644 continue;
645
646 // Direct predecessor, just add to the path.
647 if (IncomingPhiDefBB == IncomingBB) {
648 std::vector<ThreadingPath> PredPaths =
649 getPathsFromStateDefMap(StateDef, IncomingPhi, VB);
650 for (ThreadingPath &Path : PredPaths) {
651 Path.push_back(PhiBB);
652 Res.push_back(std::move(Path));
653 }
654 continue;
655 }
656 // Not a direct predecessor, find intermediate paths to append to the
657 // existing path.
658 if (VB.contains(IncomingPhiDefBB))
659 continue;
660
661 PathsType IntermediatePaths;
662 IntermediatePaths =
663 paths(IncomingPhiDefBB, IncomingBB, VB, /* PathDepth = */ 1);
664 if (IntermediatePaths.empty())
665 continue;
666
667 std::vector<ThreadingPath> PredPaths =
668 getPathsFromStateDefMap(StateDef, IncomingPhi, VB);
669 for (const ThreadingPath &Path : PredPaths) {
670 for (const PathType &IPath : IntermediatePaths) {
671 ThreadingPath NewPath(Path);
672 NewPath.appendExcludingFirst(IPath);
673 NewPath.push_back(PhiBB);
674 Res.push_back(NewPath);
675 }
676 }
677 }
678 VB.erase(PhiBB);
679 return Res;
680 }
681
682 PathsType paths(BasicBlock *BB, BasicBlock *ToBB, VisitedBlocks &Visited,
683 unsigned PathDepth) {
684 PathsType Res;
685
686 // Stop exploring paths after visiting MaxPathLength blocks
687 if (PathDepth > MaxPathLength) {
688 ORE->emit([&]() {
689 return OptimizationRemarkAnalysis(DEBUG_TYPE, "MaxPathLengthReached",
690 Switch)
691 << "Exploration stopped after visiting MaxPathLength="
692 << ore::NV("MaxPathLength", MaxPathLength) << " blocks.";
693 });
694 return Res;
695 }
696
697 Visited.insert(BB);
698 if (++NumVisited > MaxNumVisitiedPaths)
699 return Res;
700
701 // Stop if we have reached the BB out of loop, since its successors have no
702 // impact on the DFA.
703 if (!SwitchOuterLoop->contains(BB))
704 return Res;
705
706 // Some blocks have multiple edges to the same successor, and this set
707 // is used to prevent a duplicate path from being generated
708 SmallSet<BasicBlock *, 4> Successors;
709 for (BasicBlock *Succ : successors(BB)) {
710 if (!Successors.insert(Succ).second)
711 continue;
712
713 // Found a cycle through the final block.
714 if (Succ == ToBB) {
715 Res.push_back({BB, ToBB});
716 continue;
717 }
718
719 // We have encountered a cycle, do not get caught in it
720 if (Visited.contains(Succ))
721 continue;
722
723 auto *CurrLoop = LI->getLoopFor(BB);
724 // Unlikely to be beneficial.
725 if (Succ == CurrLoop->getHeader())
726 continue;
727 // Skip for now, revisit this condition later to see the impact on
728 // coverage and compile time.
729 if (LI->getLoopFor(Succ) != CurrLoop)
730 continue;
731
732 PathsType SuccPaths = paths(Succ, ToBB, Visited, PathDepth + 1);
733 for (PathType &Path : SuccPaths) {
734 Path.push_front(BB);
735 Res.push_back(Path);
736 if (Res.size() >= MaxNumPaths) {
737 return Res;
738 }
739 }
740 }
741 // This block could now be visited again from a different predecessor. Note
742 // that this will result in exponential runtime. Subpaths could possibly be
743 // cached but it takes a lot of memory to store them.
744 Visited.erase(BB);
745 return Res;
746 }
747
748 /// Walk the use-def chain and collect all the state-defining instructions.
749 ///
750 /// Return an empty map if unpredictable values encountered inside the basic
751 /// blocks of \p LoopPaths.
752 StateDefMap getStateDefMap() const {
753 StateDefMap Res;
754 Value *FirstDef = Switch->getOperand(0);
755 assert(isa<PHINode>(FirstDef) && "The first definition must be a phi.");
756
758 Stack.push_back(dyn_cast<PHINode>(FirstDef));
759 SmallSet<Value *, 16> SeenValues;
760
761 while (!Stack.empty()) {
762 PHINode *CurPhi = Stack.pop_back_val();
763
764 Res[CurPhi->getParent()] = CurPhi;
765 SeenValues.insert(CurPhi);
766
767 for (BasicBlock *IncomingBB : CurPhi->blocks()) {
768 Value *Incoming = CurPhi->getIncomingValueForBlock(IncomingBB);
769 bool IsOutsideLoops = !SwitchOuterLoop->contains(IncomingBB);
770 if (Incoming == FirstDef || isa<ConstantInt>(Incoming) ||
771 SeenValues.contains(Incoming) || IsOutsideLoops) {
772 continue;
773 }
774
775 // Any unpredictable value inside the loops means we must bail out.
776 if (!isa<PHINode>(Incoming))
777 return StateDefMap();
778
779 Stack.push_back(cast<PHINode>(Incoming));
780 }
781 }
782
783 return Res;
784 }
785
786 unsigned NumVisited = 0;
788 BasicBlock *SwitchBlock;
790 std::vector<ThreadingPath> TPaths;
791 LoopInfo *LI;
792 Loop *SwitchOuterLoop;
793};
794
795struct TransformDFA {
796 TransformDFA(AllSwitchPaths *SwitchPaths, DominatorTree *DT,
800 : SwitchPaths(SwitchPaths), DT(DT), AC(AC), TTI(TTI), ORE(ORE),
801 EphValues(EphValues) {}
802
803 void run() {
804 if (isLegalAndProfitableToTransform()) {
805 createAllExitPaths();
806 NumTransforms++;
807 }
808 }
809
810private:
811 /// This function performs both a legality check and profitability check at
812 /// the same time since it is convenient to do so. It iterates through all
813 /// blocks that will be cloned, and keeps track of the duplication cost. It
814 /// also returns false if it is illegal to clone some required block.
815 bool isLegalAndProfitableToTransform() {
817 SwitchInst *Switch = SwitchPaths->getSwitchInst();
818
819 // Don't thread switch without multiple successors.
820 if (Switch->getNumSuccessors() <= 1)
821 return false;
822
823 // Note that DuplicateBlockMap is not being used as intended here. It is
824 // just being used to ensure (BB, State) pairs are only counted once.
825 DuplicateBlockMap DuplicateMap;
826
827 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
828 PathType PathBBs = TPath.getPath();
829 APInt NextState = TPath.getExitValue();
830 const BasicBlock *Determinator = TPath.getDeterminatorBB();
831
832 // Update Metrics for the Switch block, this is always cloned
833 BasicBlock *BB = SwitchPaths->getSwitchBlock();
834 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
835 if (!VisitedBB) {
836 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
837 DuplicateMap[BB].push_back({BB, NextState});
838 }
839
840 // If the Switch block is the Determinator, then we can continue since
841 // this is the only block that is cloned and we already counted for it.
842 if (PathBBs.front() == Determinator)
843 continue;
844
845 // Otherwise update Metrics for all blocks that will be cloned. If any
846 // block is already cloned and would be reused, don't double count it.
847 auto DetIt = llvm::find(PathBBs, Determinator);
848 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
849 BB = *BBIt;
850 VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
851 if (VisitedBB)
852 continue;
853 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
854 DuplicateMap[BB].push_back({BB, NextState});
855 }
856
857 if (Metrics.notDuplicatable) {
858 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
859 << "non-duplicatable instructions.\n");
860 ORE->emit([&]() {
861 return OptimizationRemarkMissed(DEBUG_TYPE, "NonDuplicatableInst",
862 Switch)
863 << "Contains non-duplicatable instructions.";
864 });
865 return false;
866 }
867
868 // FIXME: Allow jump threading with controlled convergence.
869 if (Metrics.Convergence != ConvergenceKind::None) {
870 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
871 << "convergent instructions.\n");
872 ORE->emit([&]() {
873 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch)
874 << "Contains convergent instructions.";
875 });
876 return false;
877 }
878
879 if (!Metrics.NumInsts.isValid()) {
880 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
881 << "instructions with invalid cost.\n");
882 ORE->emit([&]() {
883 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch)
884 << "Contains instructions with invalid cost.";
885 });
886 return false;
887 }
888 }
889
890 InstructionCost DuplicationCost = 0;
891
892 unsigned JumpTableSize = 0;
893 TTI->getEstimatedNumberOfCaseClusters(*Switch, JumpTableSize, nullptr,
894 nullptr);
895 if (JumpTableSize == 0) {
896 // Factor in the number of conditional branches reduced from jump
897 // threading. Assume that lowering the switch block is implemented by
898 // using binary search, hence the LogBase2().
899 unsigned CondBranches =
900 APInt(32, Switch->getNumSuccessors()).ceilLogBase2();
901 assert(CondBranches > 0 &&
902 "The threaded switch must have multiple branches");
903 DuplicationCost = Metrics.NumInsts / CondBranches;
904 } else {
905 // Compared with jump tables, the DFA optimizer removes an indirect branch
906 // on each loop iteration, thus making branch prediction more precise. The
907 // more branch targets there are, the more likely it is for the branch
908 // predictor to make a mistake, and the more benefit there is in the DFA
909 // optimizer. Thus, the more branch targets there are, the lower is the
910 // cost of the DFA opt.
911 DuplicationCost = Metrics.NumInsts / JumpTableSize;
912 }
913
914 LLVM_DEBUG(dbgs() << "\nDFA Jump Threading: Cost to jump thread block "
915 << SwitchPaths->getSwitchBlock()->getName()
916 << " is: " << DuplicationCost << "\n\n");
917
918 if (DuplicationCost > CostThreshold) {
919 LLVM_DEBUG(dbgs() << "Not jump threading, duplication cost exceeds the "
920 << "cost threshold.\n");
921 ORE->emit([&]() {
922 return OptimizationRemarkMissed(DEBUG_TYPE, "NotProfitable", Switch)
923 << "Duplication cost exceeds the cost threshold (cost="
924 << ore::NV("Cost", DuplicationCost)
925 << ", threshold=" << ore::NV("Threshold", CostThreshold) << ").";
926 });
927 return false;
928 }
929
930 ORE->emit([&]() {
931 return OptimizationRemark(DEBUG_TYPE, "JumpThreaded", Switch)
932 << "Switch statement jump-threaded.";
933 });
934
935 return true;
936 }
937
938 /// Transform each threading path to effectively jump thread the DFA.
939 void createAllExitPaths() {
940 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager);
941
942 // Move the switch block to the end of the path, since it will be duplicated
943 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock();
944 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
945 LLVM_DEBUG(dbgs() << TPath << "\n");
946 // TODO: Fix exit path creation logic so that we dont need this
947 // placeholder.
948 TPath.push_front(SwitchBlock);
949 }
950
951 // Transform the ThreadingPaths and keep track of the cloned values
952 DuplicateBlockMap DuplicateMap;
953 DefMap NewDefs;
954
955 SmallSet<BasicBlock *, 16> BlocksToClean;
956 for (BasicBlock *BB : successors(SwitchBlock))
957 BlocksToClean.insert(BB);
958
959 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
960 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, &DTU);
961 NumPaths++;
962 }
963
964 // After all paths are cloned, now update the last successor of the cloned
965 // path so it skips over the switch statement
966 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths())
967 updateLastSuccessor(TPath, DuplicateMap, &DTU);
968
969 // For each instruction that was cloned and used outside, update its uses
970 updateSSA(NewDefs);
971
972 // Clean PHI Nodes for the newly created blocks
973 for (BasicBlock *BB : BlocksToClean)
974 cleanPhiNodes(BB);
975 }
976
977 /// For a specific ThreadingPath \p Path, create an exit path starting from
978 /// the determinator block.
979 ///
980 /// To remember the correct destination, we have to duplicate blocks
981 /// corresponding to each state. Also update the terminating instruction of
982 /// the predecessors, and phis in the successor blocks.
983 void createExitPath(DefMap &NewDefs, ThreadingPath &Path,
984 DuplicateBlockMap &DuplicateMap,
985 SmallSet<BasicBlock *, 16> &BlocksToClean,
986 DomTreeUpdater *DTU) {
987 APInt NextState = Path.getExitValue();
988 const BasicBlock *Determinator = Path.getDeterminatorBB();
989 PathType PathBBs = Path.getPath();
990
991 // Don't select the placeholder block in front
992 if (PathBBs.front() == Determinator)
993 PathBBs.pop_front();
994
995 auto DetIt = llvm::find(PathBBs, Determinator);
996 // When there is only one BB in PathBBs, the determinator takes itself as a
997 // direct predecessor.
998 BasicBlock *PrevBB = PathBBs.size() == 1 ? *DetIt : *std::prev(DetIt);
999 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
1000 BasicBlock *BB = *BBIt;
1001 BlocksToClean.insert(BB);
1002
1003 // We already cloned BB for this NextState, now just update the branch
1004 // and continue.
1005 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap);
1006 if (NextBB) {
1007 updatePredecessor(PrevBB, BB, NextBB, DTU);
1008 PrevBB = NextBB;
1009 continue;
1010 }
1011
1012 // Clone the BB and update the successor of Prev to jump to the new block
1013 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor(
1014 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU);
1015 DuplicateMap[BB].push_back({NewBB, NextState});
1016 BlocksToClean.insert(NewBB);
1017 PrevBB = NewBB;
1018 }
1019 }
1020
1021 /// Restore SSA form after cloning blocks.
1022 ///
1023 /// Each cloned block creates new defs for a variable, and the uses need to be
1024 /// updated to reflect this. The uses may be replaced with a cloned value, or
1025 /// some derived phi instruction. Note that all uses of a value defined in the
1026 /// same block were already remapped when cloning the block.
1027 void updateSSA(DefMap &NewDefs) {
1028 SSAUpdaterBulk SSAUpdate;
1029 SmallVector<Use *, 16> UsesToRename;
1030
1031 for (const auto &KV : NewDefs) {
1032 Instruction *I = KV.first;
1033 BasicBlock *BB = I->getParent();
1034 std::vector<Instruction *> Cloned = KV.second;
1035
1036 // Scan all uses of this instruction to see if it is used outside of its
1037 // block, and if so, record them in UsesToRename.
1038 for (Use &U : I->uses()) {
1039 Instruction *User = cast<Instruction>(U.getUser());
1040 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1041 if (UserPN->getIncomingBlock(U) == BB)
1042 continue;
1043 } else if (User->getParent() == BB) {
1044 continue;
1045 }
1046
1047 UsesToRename.push_back(&U);
1048 }
1049
1050 // If there are no uses outside the block, we're done with this
1051 // instruction.
1052 if (UsesToRename.empty())
1053 continue;
1054 LLVM_DEBUG(dbgs() << "DFA-JT: Renaming non-local uses of: " << *I
1055 << "\n");
1056
1057 // We found a use of I outside of BB. Rename all uses of I that are
1058 // outside its block to be uses of the appropriate PHI node etc. See
1059 // ValuesInBlocks with the values we know.
1060 unsigned VarNum = SSAUpdate.AddVariable(I->getName(), I->getType());
1061 SSAUpdate.AddAvailableValue(VarNum, BB, I);
1062 for (Instruction *New : Cloned)
1063 SSAUpdate.AddAvailableValue(VarNum, New->getParent(), New);
1064
1065 while (!UsesToRename.empty())
1066 SSAUpdate.AddUse(VarNum, UsesToRename.pop_back_val());
1067
1068 LLVM_DEBUG(dbgs() << "\n");
1069 }
1070 // SSAUpdater handles phi placement and renaming uses with the appropriate
1071 // value.
1072 SSAUpdate.RewriteAllUses(DT);
1073 }
1074
1075 /// Clones a basic block, and adds it to the CFG.
1076 ///
1077 /// This function also includes updating phi nodes in the successors of the
1078 /// BB, and remapping uses that were defined locally in the cloned BB.
1079 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB,
1080 const APInt &NextState,
1081 DuplicateBlockMap &DuplicateMap,
1082 DefMap &NewDefs,
1083 DomTreeUpdater *DTU) {
1084 ValueToValueMapTy VMap;
1085 BasicBlock *NewBB = CloneBasicBlock(
1086 BB, VMap, ".jt" + std::to_string(NextState.getLimitedValue()),
1087 BB->getParent());
1088 NewBB->moveAfter(BB);
1089 NumCloned++;
1090
1091 for (Instruction &I : *NewBB) {
1092 // Do not remap operands of PHINode in case a definition in BB is an
1093 // incoming value to a phi in the same block. This incoming value will
1094 // be renamed later while restoring SSA.
1095 if (isa<PHINode>(&I))
1096 continue;
1097 RemapInstruction(&I, VMap,
1099 if (AssumeInst *II = dyn_cast<AssumeInst>(&I))
1100 AC->registerAssumption(II);
1101 }
1102
1103 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap);
1104 updatePredecessor(PrevBB, BB, NewBB, DTU);
1105 updateDefMap(NewDefs, VMap);
1106
1107 // Add all successors to the DominatorTree
1109 for (auto *SuccBB : successors(NewBB)) {
1110 if (SuccSet.insert(SuccBB).second)
1111 DTU->applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}});
1112 }
1113 SuccSet.clear();
1114 return NewBB;
1115 }
1116
1117 /// Update the phi nodes in BB's successors.
1118 ///
1119 /// This means creating a new incoming value from NewBB with the new
1120 /// instruction wherever there is an incoming value from BB.
1121 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB,
1122 const APInt &NextState, ValueToValueMapTy &VMap,
1123 DuplicateBlockMap &DuplicateMap) {
1124 std::vector<BasicBlock *> BlocksToUpdate;
1125
1126 // If BB is the last block in the path, we can simply update the one case
1127 // successor that will be reached.
1128 if (BB == SwitchPaths->getSwitchBlock()) {
1129 SwitchInst *Switch = SwitchPaths->getSwitchInst();
1130 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1131 BlocksToUpdate.push_back(NextCase);
1132 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap);
1133 if (ClonedSucc)
1134 BlocksToUpdate.push_back(ClonedSucc);
1135 }
1136 // Otherwise update phis in all successors.
1137 else {
1138 for (BasicBlock *Succ : successors(BB)) {
1139 BlocksToUpdate.push_back(Succ);
1140
1141 // Check if a successor has already been cloned for the particular exit
1142 // value. In this case if a successor was already cloned, the phi nodes
1143 // in the cloned block should be updated directly.
1144 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap);
1145 if (ClonedSucc)
1146 BlocksToUpdate.push_back(ClonedSucc);
1147 }
1148 }
1149
1150 // If there is a phi with an incoming value from BB, create a new incoming
1151 // value for the new predecessor ClonedBB. The value will either be the same
1152 // value from BB or a cloned value.
1153 for (BasicBlock *Succ : BlocksToUpdate) {
1154 for (auto II = Succ->begin(); PHINode *Phi = dyn_cast<PHINode>(II);
1155 ++II) {
1156 Value *Incoming = Phi->getIncomingValueForBlock(BB);
1157 if (Incoming) {
1158 if (isa<Constant>(Incoming)) {
1159 Phi->addIncoming(Incoming, ClonedBB);
1160 continue;
1161 }
1162 Value *ClonedVal = VMap[Incoming];
1163 if (ClonedVal)
1164 Phi->addIncoming(ClonedVal, ClonedBB);
1165 else
1166 Phi->addIncoming(Incoming, ClonedBB);
1167 }
1168 }
1169 }
1170 }
1171
1172 /// Sets the successor of PrevBB to be NewBB instead of OldBB. Note that all
1173 /// other successors are kept as well.
1174 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB,
1175 BasicBlock *NewBB, DomTreeUpdater *DTU) {
1176 // When a path is reused, there is a chance that predecessors were already
1177 // updated before. Check if the predecessor needs to be updated first.
1178 if (!isPredecessor(OldBB, PrevBB))
1179 return;
1180
1181 Instruction *PrevTerm = PrevBB->getTerminator();
1182 for (unsigned Idx = 0; Idx < PrevTerm->getNumSuccessors(); Idx++) {
1183 if (PrevTerm->getSuccessor(Idx) == OldBB) {
1184 OldBB->removePredecessor(PrevBB, /* KeepOneInputPHIs = */ true);
1185 PrevTerm->setSuccessor(Idx, NewBB);
1186 }
1187 }
1188 DTU->applyUpdates({{DominatorTree::Delete, PrevBB, OldBB},
1189 {DominatorTree::Insert, PrevBB, NewBB}});
1190 }
1191
1192 /// Add new value mappings to the DefMap to keep track of all new definitions
1193 /// for a particular instruction. These will be used while updating SSA form.
1194 void updateDefMap(DefMap &NewDefs, ValueToValueMapTy &VMap) {
1196 NewDefsVector.reserve(VMap.size());
1197
1198 for (auto Entry : VMap) {
1199 Instruction *Inst =
1200 dyn_cast<Instruction>(const_cast<Value *>(Entry.first));
1201 if (!Inst || !Entry.second || isa<BranchInst>(Inst) ||
1202 isa<SwitchInst>(Inst)) {
1203 continue;
1204 }
1205
1206 Instruction *Cloned = dyn_cast<Instruction>(Entry.second);
1207 if (!Cloned)
1208 continue;
1209
1210 NewDefsVector.push_back({Inst, Cloned});
1211 }
1212
1213 // Sort the defs to get deterministic insertion order into NewDefs.
1214 sort(NewDefsVector, [](const auto &LHS, const auto &RHS) {
1215 if (LHS.first == RHS.first)
1216 return LHS.second->comesBefore(RHS.second);
1217 return LHS.first->comesBefore(RHS.first);
1218 });
1219
1220 for (const auto &KV : NewDefsVector)
1221 NewDefs[KV.first].push_back(KV.second);
1222 }
1223
1224 /// Update the last branch of a particular cloned path to point to the correct
1225 /// case successor.
1226 ///
1227 /// Note that this is an optional step and would have been done in later
1228 /// optimizations, but it makes the CFG significantly easier to work with.
1229 void updateLastSuccessor(ThreadingPath &TPath,
1230 DuplicateBlockMap &DuplicateMap,
1231 DomTreeUpdater *DTU) {
1232 APInt NextState = TPath.getExitValue();
1233 BasicBlock *BB = TPath.getPath().back();
1234 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap);
1235
1236 // Note multiple paths can end at the same block so check that it is not
1237 // updated yet
1238 if (!isa<SwitchInst>(LastBlock->getTerminator()))
1239 return;
1240 SwitchInst *Switch = cast<SwitchInst>(LastBlock->getTerminator());
1241 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1242
1243 std::vector<DominatorTree::UpdateType> DTUpdates;
1245 for (BasicBlock *Succ : successors(LastBlock)) {
1246 if (Succ != NextCase && SuccSet.insert(Succ).second)
1247 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ});
1248 }
1249
1250 Switch->eraseFromParent();
1251 BranchInst::Create(NextCase, LastBlock);
1252
1253 DTU->applyUpdates(DTUpdates);
1254 }
1255
1256 /// After cloning blocks, some of the phi nodes have extra incoming values
1257 /// that are no longer used. This function removes them.
1258 void cleanPhiNodes(BasicBlock *BB) {
1259 // If BB is no longer reachable, remove any remaining phi nodes
1260 if (pred_empty(BB)) {
1261 std::vector<PHINode *> PhiToRemove;
1262 for (auto II = BB->begin(); PHINode *Phi = dyn_cast<PHINode>(II); ++II) {
1263 PhiToRemove.push_back(Phi);
1264 }
1265 for (PHINode *PN : PhiToRemove) {
1266 PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
1267 PN->eraseFromParent();
1268 }
1269 return;
1270 }
1271
1272 // Remove any incoming values that come from an invalid predecessor
1273 for (auto II = BB->begin(); PHINode *Phi = dyn_cast<PHINode>(II); ++II) {
1274 std::vector<BasicBlock *> BlocksToRemove;
1275 for (BasicBlock *IncomingBB : Phi->blocks()) {
1276 if (!isPredecessor(BB, IncomingBB))
1277 BlocksToRemove.push_back(IncomingBB);
1278 }
1279 for (BasicBlock *BB : BlocksToRemove)
1280 Phi->removeIncomingValue(BB);
1281 }
1282 }
1283
1284 /// Checks if BB was already cloned for a particular next state value. If it
1285 /// was then it returns this cloned block, and otherwise null.
1286 BasicBlock *getClonedBB(BasicBlock *BB, const APInt &NextState,
1287 DuplicateBlockMap &DuplicateMap) {
1288 CloneList ClonedBBs = DuplicateMap[BB];
1289
1290 // Find an entry in the CloneList with this NextState. If it exists then
1291 // return the corresponding BB
1292 auto It = llvm::find_if(ClonedBBs, [NextState](const ClonedBlock &C) {
1293 return C.State == NextState;
1294 });
1295 return It != ClonedBBs.end() ? (*It).BB : nullptr;
1296 }
1297
1298 /// Helper to get the successor corresponding to a particular case value for
1299 /// a switch statement.
1300 BasicBlock *getNextCaseSuccessor(SwitchInst *Switch, const APInt &NextState) {
1301 BasicBlock *NextCase = nullptr;
1302 for (auto Case : Switch->cases()) {
1303 if (Case.getCaseValue()->getValue() == NextState) {
1304 NextCase = Case.getCaseSuccessor();
1305 break;
1306 }
1307 }
1308 if (!NextCase)
1309 NextCase = Switch->getDefaultDest();
1310 return NextCase;
1311 }
1312
1313 /// Returns true if IncomingBB is a predecessor of BB.
1314 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) {
1315 return llvm::is_contained(predecessors(BB), IncomingBB);
1316 }
1317
1318 AllSwitchPaths *SwitchPaths;
1319 DominatorTree *DT;
1320 AssumptionCache *AC;
1324 std::vector<ThreadingPath> TPaths;
1325};
1326
1327bool DFAJumpThreading::run(Function &F) {
1328 LLVM_DEBUG(dbgs() << "\nDFA Jump threading: " << F.getName() << "\n");
1329
1330 if (F.hasOptSize()) {
1331 LLVM_DEBUG(dbgs() << "Skipping due to the 'minsize' attribute\n");
1332 return false;
1333 }
1334
1335 if (ClViewCfgBefore)
1336 F.viewCFG();
1337
1338 SmallVector<AllSwitchPaths, 2> ThreadableLoops;
1339 bool MadeChanges = false;
1340 LoopInfoBroken = false;
1341
1342 for (BasicBlock &BB : F) {
1343 auto *SI = dyn_cast<SwitchInst>(BB.getTerminator());
1344 if (!SI)
1345 continue;
1346
1347 LLVM_DEBUG(dbgs() << "\nCheck if SwitchInst in BB " << BB.getName()
1348 << " is a candidate\n");
1349 MainSwitch Switch(SI, LI, ORE);
1350
1351 if (!Switch.getInstr()) {
1352 LLVM_DEBUG(dbgs() << "\nSwitchInst in BB " << BB.getName() << " is not a "
1353 << "candidate for jump threading\n");
1354 continue;
1355 }
1356
1357 LLVM_DEBUG(dbgs() << "\nSwitchInst in BB " << BB.getName() << " is a "
1358 << "candidate for jump threading\n");
1359 LLVM_DEBUG(SI->dump());
1360
1361 unfoldSelectInstrs(DT, Switch.getSelectInsts());
1362 if (!Switch.getSelectInsts().empty())
1363 MadeChanges = true;
1364
1365 AllSwitchPaths SwitchPaths(&Switch, ORE, LI,
1366 LI->getLoopFor(&BB)->getOutermostLoop());
1367 SwitchPaths.run();
1368
1369 if (SwitchPaths.getNumThreadingPaths() > 0) {
1370 ThreadableLoops.push_back(SwitchPaths);
1371
1372 // For the time being limit this optimization to occurring once in a
1373 // function since it can change the CFG significantly. This is not a
1374 // strict requirement but it can cause buggy behavior if there is an
1375 // overlap of blocks in different opportunities. There is a lot of room to
1376 // experiment with catching more opportunities here.
1377 // NOTE: To release this contraint, we must handle LoopInfo invalidation
1378 break;
1379 }
1380 }
1381
1382#ifdef NDEBUG
1383 LI->verify(*DT);
1384#endif
1385
1387 if (ThreadableLoops.size() > 0)
1388 CodeMetrics::collectEphemeralValues(&F, AC, EphValues);
1389
1390 for (AllSwitchPaths SwitchPaths : ThreadableLoops) {
1391 TransformDFA Transform(&SwitchPaths, DT, AC, TTI, ORE, EphValues);
1392 Transform.run();
1393 MadeChanges = true;
1394 LoopInfoBroken = true;
1395 }
1396
1397#ifdef EXPENSIVE_CHECKS
1398 assert(DT->verify(DominatorTree::VerificationLevel::Full));
1399 verifyFunction(F, &dbgs());
1400#endif
1401
1402 return MadeChanges;
1403}
1404
1405} // end anonymous namespace
1406
1407/// Integrate with the new Pass Manager
1412 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
1415 DFAJumpThreading ThreadImpl(&AC, &DT, &LI, &TTI, &ORE);
1416 if (!ThreadImpl.run(F))
1417 return PreservedAnalyses::all();
1418
1421 if (!ThreadImpl.LoopInfoBroken)
1422 PA.preserve<LoopAnalysis>();
1423 return PA;
1424}
This file implements a class to represent arbitrary precision integral constant values and operations...
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static const Function * getParent(const Value *V)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< unsigned > MaxPathLength("dfa-max-path-length", cl::desc("Max number of blocks searched to find a threading path"), cl::Hidden, cl::init(20))
static cl::opt< unsigned > MaxNumVisitiedPaths("dfa-max-num-visited-paths", cl::desc("Max number of blocks visited while enumerating paths around a switch"), cl::Hidden, cl::init(2000))
static cl::opt< bool > ClViewCfgBefore("dfa-jump-view-cfg-before", cl::desc("View the CFG before DFA Jump Threading"), cl::Hidden, cl::init(false))
static cl::opt< unsigned > CostThreshold("dfa-cost-threshold", cl::desc("Maximum cost accepted for the transformation"), cl::Hidden, cl::init(50))
static cl::opt< bool > EarlyExitHeuristic("dfa-early-exit-heuristic", cl::desc("Exit early if an unpredictable value come from the same loop"), cl::Hidden, cl::init(true))
static cl::opt< unsigned > MaxNumPaths("dfa-max-num-paths", cl::desc("Max number of paths enumerated around a switch"), cl::Hidden, cl::init(200))
#define DEBUG_TYPE
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
Machine Trace Metrics
uint64_t IntrinsicInst * II
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
unsigned ceilLogBase2() const
Definition: APInt.h:1720
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:453
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
This represents the llvm.assume intrinsic.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:448
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:517
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:416
const Instruction & front() const
Definition: BasicBlock.h:471
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:212
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
Definition: BasicBlock.cpp:287
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:219
size_t size() const
Definition: BasicBlock.h:469
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:239
const Instruction & back() const
Definition: BasicBlock.h:473
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Definition: BasicBlock.cpp:516
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
This is the shared class of boolean and integer constants.
Definition: Constants.h:81
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
void applyUpdates(ArrayRef< typename DomTreeT::UpdateType > Updates)
Submit updates to all available trees.
unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:92
BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:566
const LoopT * getOutermostLoop() const
Get the outermost loop in which this loop is contained.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:39
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1852
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:131
Helper class for SSA formation on a set of values defined in multiple blocks.
unsigned AddVariable(StringRef Name, Type *Ty)
Add a new variable to the SSA rewriter.
void AddAvailableValue(unsigned Var, BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
void RewriteAllUses(DominatorTree *DT, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Perform all the necessary updates, including new PHI-nodes insertion and the requested uses update.
void AddUse(unsigned Var, Use *U)
Record a use of the symbolic value.
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getTrueValue() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:367
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:502
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition: SmallSet.h:236
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:179
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
void reserve(size_type N)
Definition: SmallVector.h:676
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
Multiway switch.
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
size_type size() const
Definition: ValueMap.h:140
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
const ParentTy * getParent() const
Definition: ilist_node.h:32
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
@ Entry
Definition: COFF.h:826
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< InstrNode * > Instr
Definition: RDFGraph.h:389
NodeAddr< PhiNode * > Phi
Definition: RDFGraph.h:390
@ FalseVal
Definition: TGLexer.h:59
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1742
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
Definition: Verifier.cpp:7137
auto successors(const MachineBasicBlock *BB)
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition: ValueMapper.h:94
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition: ValueMapper.h:76
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
Definition: ValueMapper.h:263
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:292
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1749
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1886
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:118
Utility to calculate the size and a few similar metrics for a set of basic blocks.
Definition: CodeMetrics.h:33
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
Definition: CodeMetrics.cpp:71
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Integrate with the new Pass Manager.
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...