LLVM 23.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/DenseSet.h"
64#include "llvm/ADT/Statistic.h"
72#include "llvm/IR/CFG.h"
73#include "llvm/IR/Constants.h"
76#include "llvm/Support/Debug.h"
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
94namespace llvm {
95static cl::opt<bool>
96 ClViewCfgBefore("dfa-jump-view-cfg-before",
97 cl::desc("View the CFG before DFA Jump Threading"),
98 cl::Hidden, cl::init(false));
99
101 "dfa-early-exit-heuristic",
102 cl::desc("Exit early if an unpredictable value come from the same loop"),
103 cl::Hidden, cl::init(true));
104
106 "dfa-max-path-length",
107 cl::desc("Max number of blocks searched to find a threading path"),
108 cl::Hidden, cl::init(20));
109
111 "dfa-max-num-visited-paths",
112 cl::desc(
113 "Max number of blocks visited while enumerating paths around a switch"),
114 cl::Hidden, cl::init(2500));
115
117 MaxNumPaths("dfa-max-num-paths",
118 cl::desc("Max number of paths enumerated around a switch"),
119 cl::Hidden, cl::init(200));
120
122 CostThreshold("dfa-cost-threshold",
123 cl::desc("Maximum cost accepted for the transformation"),
124 cl::Hidden, cl::init(50));
125
127 "dfa-max-cloned-rate",
128 cl::desc(
129 "Maximum cloned instructions rate accepted for the transformation"),
130 cl::Hidden, cl::init(7.5));
131
133 MaxOuterUseBlocks("dfa-max-out-use-blocks",
134 cl::desc("Maximum unduplicated blocks with outer uses "
135 "accepted for the transformation"),
136 cl::Hidden, cl::init(40));
137
139
140} // namespace llvm
141
142namespace {
143class SelectInstToUnfold {
144 SelectInst *SI;
145 PHINode *SIUse;
146
147public:
148 SelectInstToUnfold(SelectInst *SI, PHINode *SIUse) : SI(SI), SIUse(SIUse) {}
149
150 SelectInst *getInst() { return SI; }
151 PHINode *getUse() { return SIUse; }
152
153 explicit operator bool() const { return SI && SIUse; }
154};
155
156class DFAJumpThreading {
157public:
158 DFAJumpThreading(AssumptionCache *AC, DomTreeUpdater *DTU, LoopInfo *LI,
159 TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE)
160 : AC(AC), DTU(DTU), LI(LI), TTI(TTI), ORE(ORE) {}
161
162 bool run(Function &F);
163 bool LoopInfoBroken;
164
165private:
166 void
167 unfoldSelectInstrs(const SmallVector<SelectInstToUnfold, 4> &SelectInsts) {
169
170 while (!Stack.empty()) {
171 SelectInstToUnfold SIToUnfold = Stack.pop_back_val();
172
173 std::vector<SelectInstToUnfold> NewSIsToUnfold;
174 std::vector<BasicBlock *> NewBBs;
175 unfold(DTU, LI, SIToUnfold, &NewSIsToUnfold, &NewBBs);
176
177 // Put newly discovered select instructions into the work list.
178 llvm::append_range(Stack, NewSIsToUnfold);
179 }
180 }
181
182 static void unfold(DomTreeUpdater *DTU, LoopInfo *LI,
183 SelectInstToUnfold SIToUnfold,
184 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
185 std::vector<BasicBlock *> *NewBBs);
186
187 AssumptionCache *AC;
188 DomTreeUpdater *DTU;
189 LoopInfo *LI;
190 TargetTransformInfo *TTI;
191 OptimizationRemarkEmitter *ORE;
192};
193} // namespace
194
195/// Unfold the select instruction held in \p SIToUnfold by replacing it with
196/// control flow.
197///
198/// Put newly discovered select instructions into \p NewSIsToUnfold. Put newly
199/// created basic blocks into \p NewBBs.
200///
201/// TODO: merge it with CodeGenPrepare::optimizeSelectInst() if possible.
202void DFAJumpThreading::unfold(DomTreeUpdater *DTU, LoopInfo *LI,
203 SelectInstToUnfold SIToUnfold,
204 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
205 std::vector<BasicBlock *> *NewBBs) {
206 SelectInst *SI = SIToUnfold.getInst();
207 PHINode *SIUse = SIToUnfold.getUse();
208 assert(SI->hasOneUse());
209 // The select may come indirectly, instead of from where it is defined.
210 BasicBlock *StartBlock = SIUse->getIncomingBlock(*SI->use_begin());
211
212 if (UncondBrInst *StartBlockTerm =
213 dyn_cast<UncondBrInst>(StartBlock->getTerminator())) {
214 BasicBlock *EndBlock = StartBlock->getUniqueSuccessor();
215 // Arbitrarily choose the 'false' side for a new input value to the PHI.
216 BasicBlock *NewBlock = BasicBlock::Create(
217 SI->getContext(), Twine(SI->getName(), ".si.unfold.false"),
218 EndBlock->getParent(), EndBlock);
219 NewBBs->push_back(NewBlock);
220 UncondBrInst::Create(EndBlock, NewBlock);
221 DTU->applyUpdates({{DominatorTree::Insert, NewBlock, EndBlock}});
222
223 // StartBlock
224 // | \
225 // | NewBlock
226 // | /
227 // EndBlock
228 Value *SIOp1 = SI->getTrueValue();
229 Value *SIOp2 = SI->getFalseValue();
230
231 PHINode *NewPhi = PHINode::Create(SIUse->getType(), 1,
232 Twine(SIOp2->getName(), ".si.unfold.phi"),
233 NewBlock->getFirstInsertionPt());
234 NewPhi->addIncoming(SIOp2, StartBlock);
235
236 // Update any other PHI nodes in EndBlock.
237 for (PHINode &Phi : EndBlock->phis()) {
238 if (SIUse == &Phi)
239 continue;
240 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), NewBlock);
241 }
242
243 // Update the phi node of SI, which is its only use.
244 if (EndBlock == SIUse->getParent()) {
245 SIUse->addIncoming(NewPhi, NewBlock);
246 SIUse->replaceUsesOfWith(SI, SIOp1);
247 } else {
248 PHINode *EndPhi = PHINode::Create(SIUse->getType(), pred_size(EndBlock),
249 Twine(SI->getName(), ".si.unfold.phi"),
250 EndBlock->getFirstInsertionPt());
251 for (BasicBlock *Pred : predecessors(EndBlock)) {
252 if (Pred != StartBlock && Pred != NewBlock)
253 EndPhi->addIncoming(EndPhi, Pred);
254 }
255
256 EndPhi->addIncoming(SIOp1, StartBlock);
257 EndPhi->addIncoming(NewPhi, NewBlock);
258 SIUse->replaceUsesOfWith(SI, EndPhi);
259 SIUse = EndPhi;
260 }
261
262 if (auto *OpSi = dyn_cast<SelectInst>(SIOp1))
263 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, SIUse));
264 if (auto *OpSi = dyn_cast<SelectInst>(SIOp2))
265 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, NewPhi));
266
267 // Insert the real conditional branch based on the original condition.
268 StartBlockTerm->eraseFromParent();
269 auto *BI =
270 CondBrInst::Create(SI->getCondition(), EndBlock, NewBlock, StartBlock);
272 BI->setMetadata(LLVMContext::MD_prof,
273 SI->getMetadata(LLVMContext::MD_prof));
274 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, NewBlock}});
275 } else {
276 BasicBlock *EndBlock = SIUse->getParent();
277 BasicBlock *NewBlockT = BasicBlock::Create(
278 SI->getContext(), Twine(SI->getName(), ".si.unfold.true"),
279 EndBlock->getParent(), EndBlock);
280 BasicBlock *NewBlockF = BasicBlock::Create(
281 SI->getContext(), Twine(SI->getName(), ".si.unfold.false"),
282 EndBlock->getParent(), EndBlock);
283
284 NewBBs->push_back(NewBlockT);
285 NewBBs->push_back(NewBlockF);
286
287 // Def only has one use in EndBlock.
288 // Before transformation:
289 // StartBlock(Def)
290 // | \
291 // EndBlock OtherBlock
292 // (Use)
293 //
294 // After transformation:
295 // StartBlock(Def)
296 // | \
297 // | OtherBlock
298 // NewBlockT
299 // | \
300 // | NewBlockF
301 // | /
302 // | /
303 // EndBlock
304 // (Use)
305 UncondBrInst::Create(EndBlock, NewBlockF);
306 // Insert the real conditional branch based on the original condition.
307 auto *BI =
308 CondBrInst::Create(SI->getCondition(), EndBlock, NewBlockF, NewBlockT);
310 BI->setMetadata(LLVMContext::MD_prof,
311 SI->getMetadata(LLVMContext::MD_prof));
312 DTU->applyUpdates({{DominatorTree::Insert, NewBlockT, NewBlockF},
313 {DominatorTree::Insert, NewBlockT, EndBlock},
314 {DominatorTree::Insert, NewBlockF, EndBlock}});
315
316 Value *TrueVal = SI->getTrueValue();
317 Value *FalseVal = SI->getFalseValue();
318
319 PHINode *NewPhiT = PHINode::Create(
320 SIUse->getType(), 1, Twine(TrueVal->getName(), ".si.unfold.phi"),
321 NewBlockT->getFirstInsertionPt());
322 PHINode *NewPhiF = PHINode::Create(
323 SIUse->getType(), 1, Twine(FalseVal->getName(), ".si.unfold.phi"),
324 NewBlockF->getFirstInsertionPt());
325 NewPhiT->addIncoming(TrueVal, StartBlock);
326 NewPhiF->addIncoming(FalseVal, NewBlockT);
327
328 if (auto *TrueSI = dyn_cast<SelectInst>(TrueVal))
329 NewSIsToUnfold->push_back(SelectInstToUnfold(TrueSI, NewPhiT));
330 if (auto *FalseSi = dyn_cast<SelectInst>(FalseVal))
331 NewSIsToUnfold->push_back(SelectInstToUnfold(FalseSi, NewPhiF));
332
333 SIUse->addIncoming(NewPhiT, NewBlockT);
334 SIUse->addIncoming(NewPhiF, NewBlockF);
335 SIUse->removeIncomingValue(StartBlock);
336
337 // Update any other PHI nodes in EndBlock.
338 for (PHINode &Phi : EndBlock->phis()) {
339 if (SIUse == &Phi)
340 continue;
341 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), NewBlockT);
342 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), NewBlockF);
343 Phi.removeIncomingValue(StartBlock);
344 }
345
346 // Update the appropriate successor of the start block to point to the new
347 // unfolded block.
348 CondBrInst *CondBr = cast<CondBrInst>(StartBlock->getTerminator());
349 unsigned SuccNum = CondBr->getSuccessor(1) == EndBlock ? 1 : 0;
350 CondBr->setSuccessor(SuccNum, NewBlockT);
351 DTU->applyUpdates({{DominatorTree::Delete, StartBlock, EndBlock},
352 {DominatorTree::Insert, StartBlock, NewBlockT}});
353 }
354
355 // Preserve loop info
356 if (Loop *L = LI->getLoopFor(StartBlock)) {
357 for (BasicBlock *NewBB : *NewBBs)
358 L->addBasicBlockToLoop(NewBB, *LI);
359 }
360
361 // The select is now dead.
362 assert(SI->use_empty() && "Select must be dead now");
363 SI->eraseFromParent();
364}
365
366namespace {
367struct ClonedBlock {
368 BasicBlock *BB;
369 APInt State; ///< \p State corresponds to the next value of a switch stmnt.
370};
371} // namespace
372
373typedef std::deque<BasicBlock *> PathType;
374typedef std::vector<PathType> PathsType;
376typedef std::vector<ClonedBlock> CloneList;
377
378// This data structure keeps track of all blocks that have been cloned. If two
379// different ThreadingPaths clone the same block for a certain state it should
380// be reused, and it can be looked up in this map.
382
383// This map keeps track of all the new definitions for an instruction. This
384// information is needed when restoring SSA form after cloning blocks.
386
387inline raw_ostream &operator<<(raw_ostream &OS, const PathType &Path) {
388 auto BBNames = llvm::map_range(
389 Path, [](const BasicBlock *BB) { return BB->getNameOrAsOperand(); });
390 OS << "< " << llvm::join(BBNames, ", ") << " >";
391 return OS;
392}
393
394namespace {
395/// ThreadingPath is a path in the control flow of a loop that can be threaded
396/// by cloning necessary basic blocks and replacing conditional branches with
397/// unconditional ones. A threading path includes a list of basic blocks, the
398/// exit state, and the block that determines the next state.
399struct ThreadingPath {
400 /// Exit value is DFA's exit state for the given path.
401 APInt getExitValue() const { return ExitVal; }
402 void setExitValue(const ConstantInt *V) {
403 ExitVal = V->getValue();
404 IsExitValSet = true;
405 }
406 void setExitValue(const APInt &V) {
407 ExitVal = V;
408 IsExitValSet = true;
409 }
410 bool isExitValueSet() const { return IsExitValSet; }
411
412 /// Determinator is the basic block that determines the next state of the DFA.
413 const BasicBlock *getDeterminatorBB() const { return DBB; }
414 void setDeterminator(const BasicBlock *BB) { DBB = BB; }
415
416 /// Path is a list of basic blocks.
417 const PathType &getPath() const { return Path; }
418 void setPath(const PathType &NewPath) { Path = NewPath; }
419 void push_back(BasicBlock *BB) { Path.push_back(BB); }
420 void push_front(BasicBlock *BB) { Path.push_front(BB); }
421 void appendExcludingFirst(const PathType &OtherPath) {
422 llvm::append_range(Path, llvm::drop_begin(OtherPath));
423 }
424
425 void print(raw_ostream &OS) const {
426 OS << Path << " [ " << ExitVal << ", " << DBB->getNameOrAsOperand() << " ]";
427 }
428
429private:
430 PathType Path;
431 APInt ExitVal;
432 const BasicBlock *DBB = nullptr;
433 bool IsExitValSet = false;
434};
435
436#ifndef NDEBUG
437inline raw_ostream &operator<<(raw_ostream &OS, const ThreadingPath &TPath) {
438 TPath.print(OS);
439 return OS;
440}
441#endif
442
443struct MainSwitch {
444 MainSwitch(SwitchInst *SI, LoopInfo *LI, OptimizationRemarkEmitter *ORE)
445 : LI(LI) {
446 if (isCandidate(SI)) {
447 Instr = SI;
448 } else {
449 ORE->emit([&]() {
450 return OptimizationRemarkMissed(DEBUG_TYPE, "SwitchNotPredictable", SI)
451 << "Switch instruction is not predictable.";
452 });
453 }
454 }
455
456 virtual ~MainSwitch() = default;
457
458 SwitchInst *getInstr() const { return Instr; }
459 const SmallVector<SelectInstToUnfold, 4> getSelectInsts() {
460 return SelectInsts;
461 }
462
463private:
464 /// Do a use-def chain traversal starting from the switch condition to see if
465 /// \p SI is a potential condidate.
466 ///
467 /// Also, collect select instructions to unfold.
468 bool isCandidate(const SwitchInst *SI) {
469 std::deque<std::pair<Value *, BasicBlock *>> Q;
470 SmallPtrSet<Value *, 16> SeenValues;
471 SelectInsts.clear();
472
473 Value *SICond = SI->getCondition();
474 LLVM_DEBUG(dbgs() << "\tSICond: " << *SICond << "\n");
475 if (!isa<PHINode>(SICond))
476 return false;
477
478 // The switch must be in a loop.
479 const Loop *L = LI->getLoopFor(SI->getParent());
480 if (!L)
481 return false;
482
483 addToQueue(SICond, nullptr, Q, SeenValues);
484
485 while (!Q.empty()) {
486 Value *Current = Q.front().first;
487 BasicBlock *CurrentIncomingBB = Q.front().second;
488 Q.pop_front();
489
490 if (auto *Phi = dyn_cast<PHINode>(Current)) {
491 for (BasicBlock *IncomingBB : Phi->blocks()) {
492 Value *Incoming = Phi->getIncomingValueForBlock(IncomingBB);
493 addToQueue(Incoming, IncomingBB, Q, SeenValues);
494 }
495 LLVM_DEBUG(dbgs() << "\tphi: " << *Phi << "\n");
496 } else if (SelectInst *SelI = dyn_cast<SelectInst>(Current)) {
497 if (!isValidSelectInst(SelI))
498 return false;
499 addToQueue(SelI->getTrueValue(), CurrentIncomingBB, Q, SeenValues);
500 addToQueue(SelI->getFalseValue(), CurrentIncomingBB, Q, SeenValues);
501 LLVM_DEBUG(dbgs() << "\tselect: " << *SelI << "\n");
502 if (auto *SelIUse = dyn_cast<PHINode>(SelI->user_back()))
503 SelectInsts.push_back(SelectInstToUnfold(SelI, SelIUse));
504 } else if (isa<Constant>(Current)) {
505 LLVM_DEBUG(dbgs() << "\tconst: " << *Current << "\n");
506 continue;
507 } else {
508 LLVM_DEBUG(dbgs() << "\tother: " << *Current << "\n");
509 // Allow unpredictable values. The hope is that those will be the
510 // initial switch values that can be ignored (they will hit the
511 // unthreaded switch) but this assumption will get checked later after
512 // paths have been enumerated (in function getStateDefMap).
513
514 // If the unpredictable value comes from the same inner loop it is
515 // likely that it will also be on the enumerated paths, causing us to
516 // exit after we have enumerated all the paths. This heuristic save
517 // compile time because a search for all the paths can become expensive.
518 if (EarlyExitHeuristic &&
519 L->contains(LI->getLoopFor(CurrentIncomingBB))) {
521 << "\tExiting early due to unpredictability heuristic.\n");
522 return false;
523 }
524
525 continue;
526 }
527 }
528
529 return true;
530 }
531
532 void addToQueue(Value *Val, BasicBlock *BB,
533 std::deque<std::pair<Value *, BasicBlock *>> &Q,
534 SmallPtrSet<Value *, 16> &SeenValues) {
535 if (SeenValues.insert(Val).second)
536 Q.push_back({Val, BB});
537 }
538
539 bool isValidSelectInst(SelectInst *SI) {
540 if (!SI->hasOneUse())
541 return false;
542
543 Instruction *SIUse = SI->user_back();
544 // The use of the select inst should be either a phi or another select.
545 if (!isa<PHINode, SelectInst>(SIUse))
546 return false;
547
548 BasicBlock *SIBB = SI->getParent();
549
550 // Currently, we can only expand select instructions in basic blocks with
551 // one successor.
552 UncondBrInst *SITerm = dyn_cast<UncondBrInst>(SIBB->getTerminator());
553 if (!SITerm)
554 return false;
555
556 // Only fold the select coming from directly where it is defined.
557 // TODO: We have dealt with the select coming indirectly now. This
558 // constraint can be relaxed.
559 PHINode *PHIUser = dyn_cast<PHINode>(SIUse);
560 if (PHIUser && PHIUser->getIncomingBlock(*SI->use_begin()) != SIBB)
561 return false;
562
563 // If select will not be sunk during unfolding, and it is in the same basic
564 // block as another state defining select, then cannot unfold both.
565 for (SelectInstToUnfold SIToUnfold : SelectInsts) {
566 SelectInst *PrevSI = SIToUnfold.getInst();
567 if (PrevSI->getTrueValue() != SI && PrevSI->getFalseValue() != SI &&
568 PrevSI->getParent() == SI->getParent())
569 return false;
570 }
571
572 return true;
573 }
574
575 LoopInfo *LI;
576 SwitchInst *Instr = nullptr;
578};
579
580struct AllSwitchPaths {
581 AllSwitchPaths(const MainSwitch *MSwitch, OptimizationRemarkEmitter *ORE,
582 LoopInfo *LI, Loop *L)
583 : Switch(MSwitch->getInstr()), SwitchBlock(Switch->getParent()), ORE(ORE),
584 LI(LI), SwitchOuterLoop(L) {}
585
586 std::vector<ThreadingPath> &getThreadingPaths() { return TPaths; }
587 unsigned getNumThreadingPaths() { return TPaths.size(); }
588 SwitchInst *getSwitchInst() { return Switch; }
589 BasicBlock *getSwitchBlock() { return SwitchBlock; }
590
591 void run() {
592 findTPaths();
593 unifyTPaths();
594 }
595
596private:
597 // Value: an instruction that defines a switch state;
598 // Key: the parent basic block of that instruction.
599 typedef DenseMap<const BasicBlock *, const PHINode *> StateDefMap;
600 std::vector<ThreadingPath> getPathsFromStateDefMap(StateDefMap &StateDef,
601 PHINode *Phi,
602 VisitedBlocks &VB,
603 unsigned PathsLimit) {
604 std::vector<ThreadingPath> Res;
605 auto *PhiBB = Phi->getParent();
606 VB.insert(PhiBB);
607
608 VisitedBlocks UniqueBlocks;
609 for (auto *IncomingBB : Phi->blocks()) {
610 if (Res.size() >= PathsLimit)
611 break;
612 if (!UniqueBlocks.insert(IncomingBB).second)
613 continue;
614 if (!SwitchOuterLoop->contains(IncomingBB))
615 continue;
616
617 Value *IncomingValue = Phi->getIncomingValueForBlock(IncomingBB);
618 // We found the determinator. This is the start of our path.
619 if (auto *C = dyn_cast<ConstantInt>(IncomingValue)) {
620 // SwitchBlock is the determinator, unsupported unless its also the def.
621 if (PhiBB == SwitchBlock &&
622 SwitchBlock != cast<PHINode>(Switch->getOperand(0))->getParent())
623 continue;
624 ThreadingPath NewPath;
625 NewPath.setDeterminator(PhiBB);
626 NewPath.setExitValue(C);
627 // Don't add SwitchBlock at the start, this is handled later.
628 if (IncomingBB != SwitchBlock) {
629 // Don't add a cycle to the path.
630 if (VB.contains(IncomingBB))
631 continue;
632 NewPath.push_back(IncomingBB);
633 }
634 NewPath.push_back(PhiBB);
635 Res.push_back(NewPath);
636 continue;
637 }
638 // Don't get into a cycle.
639 if (VB.contains(IncomingBB) || IncomingBB == SwitchBlock)
640 continue;
641 // Recurse up the PHI chain.
642 auto *IncomingPhi = dyn_cast<PHINode>(IncomingValue);
643 if (!IncomingPhi)
644 continue;
645 auto *IncomingPhiDefBB = IncomingPhi->getParent();
646 if (!StateDef.contains(IncomingPhiDefBB))
647 continue;
648
649 // Direct predecessor, just add to the path.
650 if (IncomingPhiDefBB == IncomingBB) {
651 assert(PathsLimit > Res.size());
652 std::vector<ThreadingPath> PredPaths = getPathsFromStateDefMap(
653 StateDef, IncomingPhi, VB, PathsLimit - Res.size());
654 for (ThreadingPath &Path : PredPaths) {
655 Path.push_back(PhiBB);
656 Res.push_back(std::move(Path));
657 }
658 continue;
659 }
660 // Not a direct predecessor, find intermediate paths to append to the
661 // existing path.
662 if (VB.contains(IncomingPhiDefBB))
663 continue;
664
665 PathsType IntermediatePaths;
666 assert(PathsLimit > Res.size());
667 auto InterPathLimit = PathsLimit - Res.size();
668 IntermediatePaths = paths(IncomingPhiDefBB, IncomingBB, VB,
669 /* PathDepth = */ 1, InterPathLimit);
670 if (IntermediatePaths.empty())
671 continue;
672
673 assert(InterPathLimit >= IntermediatePaths.size());
674 auto PredPathLimit = InterPathLimit / IntermediatePaths.size();
675 std::vector<ThreadingPath> PredPaths =
676 getPathsFromStateDefMap(StateDef, IncomingPhi, VB, PredPathLimit);
677 for (const ThreadingPath &Path : PredPaths) {
678 for (const PathType &IPath : IntermediatePaths) {
679 ThreadingPath NewPath(Path);
680 NewPath.appendExcludingFirst(IPath);
681 NewPath.push_back(PhiBB);
682 Res.push_back(NewPath);
683 }
684 }
685 }
686 VB.erase(PhiBB);
687 return Res;
688 }
689
690 PathsType paths(BasicBlock *BB, BasicBlock *ToBB, VisitedBlocks &Visited,
691 unsigned PathDepth, unsigned PathsLimit) {
692 PathsType Res;
693
694 // Stop exploring paths after visiting MaxPathLength blocks
695 if (PathDepth > MaxPathLength) {
696 ORE->emit([&]() {
697 return OptimizationRemarkAnalysis(DEBUG_TYPE, "MaxPathLengthReached",
698 Switch)
699 << "Exploration stopped after visiting MaxPathLength="
700 << ore::NV("MaxPathLength", MaxPathLength) << " blocks.";
701 });
702 return Res;
703 }
704
705 Visited.insert(BB);
706 if (++NumVisited > MaxNumVisitiedPaths)
707 return Res;
708
709 // Stop if we have reached the BB out of loop, since its successors have no
710 // impact on the DFA.
711 if (!SwitchOuterLoop->contains(BB))
712 return Res;
713
714 // Some blocks have multiple edges to the same successor, and this set
715 // is used to prevent a duplicate path from being generated
716 SmallPtrSet<BasicBlock *, 4> Successors;
717 for (BasicBlock *Succ : successors(BB)) {
718 if (Res.size() >= PathsLimit)
719 break;
720 if (!Successors.insert(Succ).second)
721 continue;
722
723 // Found a cycle through the final block.
724 if (Succ == ToBB) {
725 Res.push_back({BB, ToBB});
726 continue;
727 }
728
729 // We have encountered a cycle, do not get caught in it
730 if (Visited.contains(Succ))
731 continue;
732
733 auto *CurrLoop = LI->getLoopFor(BB);
734 // Unlikely to be beneficial.
735 if (Succ == CurrLoop->getHeader())
736 continue;
737 // Skip for now, revisit this condition later to see the impact on
738 // coverage and compile time.
739 if (LI->getLoopFor(Succ) != CurrLoop)
740 continue;
741 assert(PathsLimit > Res.size());
742 PathsType SuccPaths =
743 paths(Succ, ToBB, Visited, PathDepth + 1, PathsLimit - Res.size());
744 for (PathType &Path : SuccPaths) {
745 Path.push_front(BB);
746 Res.push_back(Path);
747 }
748 }
749 // This block could now be visited again from a different predecessor. Note
750 // that this will result in exponential runtime. Subpaths could possibly be
751 // cached but it takes a lot of memory to store them.
752 Visited.erase(BB);
753 return Res;
754 }
755
756 /// Walk the use-def chain and collect all the state-defining blocks and the
757 /// PHI nodes in those blocks that define the state.
758 StateDefMap getStateDefMap() const {
759 StateDefMap Res;
760 DenseSet<const BasicBlock *> MultipleDefBBs;
761 PHINode *FirstDef = dyn_cast<PHINode>(Switch->getOperand(0));
762 assert(FirstDef && "The first definition must be a phi.");
763
765 Stack.push_back(FirstDef);
766 SmallPtrSet<Value *, 16> SeenValues;
767
768 while (!Stack.empty()) {
769 PHINode *CurPhi = Stack.pop_back_val();
770 BasicBlock *CurDefBlock = CurPhi->getParent();
771
772 auto [_, Inserted] = Res.try_emplace(CurDefBlock, CurPhi);
773 if (!Inserted)
774 MultipleDefBBs.insert(CurDefBlock);
775
776 SeenValues.insert(CurPhi);
777
778 for (BasicBlock *IncomingBB : CurPhi->blocks()) {
779 PHINode *IncomingPhi =
780 dyn_cast<PHINode>(CurPhi->getIncomingValueForBlock(IncomingBB));
781 if (!IncomingPhi)
782 continue;
783 bool IsOutsideLoops = !SwitchOuterLoop->contains(IncomingBB);
784 if (SeenValues.contains(IncomingPhi) || IsOutsideLoops)
785 continue;
786
787 Stack.push_back(IncomingPhi);
788 }
789 }
790
791 // NOTE: If multiple phi definitions exist in a block, we cannot
792 // thread the paths with such block by simple cloning. For example:
793 // < then, det, lbl_entry, switch_bb > [ 0, det ]
794 // < then, det, switch_bb > [ 1, det ]
795 // In this case, it is impossible to diverge then->det into then->det.0 and
796 // then->det.1 by simple path cloning.
797 for (auto *BB : MultipleDefBBs) {
798 LLVM_DEBUG(dbgs() << "Not a state-defining block: Multiple defs in "
799 << BB->getNameOrAsOperand() << "\n");
800 Res.erase(BB);
801 }
802 return Res;
803 }
804
805 // Find all threadable paths.
806 void findTPaths() {
807 StateDefMap StateDef = getStateDefMap();
808 if (StateDef.empty()) {
809 ORE->emit([&]() {
810 return OptimizationRemarkMissed(DEBUG_TYPE, "SwitchNotPredictable",
811 Switch)
812 << "Switch instruction is not predictable.";
813 });
814 return;
815 }
816
817 auto *SwitchPhi = cast<PHINode>(Switch->getOperand(0));
818 auto *SwitchPhiDefBB = SwitchPhi->getParent();
819 VisitedBlocks VB;
820 // Get paths from the determinator BBs to SwitchPhiDefBB
821 std::vector<ThreadingPath> PathsToPhiDef =
822 getPathsFromStateDefMap(StateDef, SwitchPhi, VB, MaxNumPaths);
823 if (SwitchPhiDefBB == SwitchBlock || PathsToPhiDef.empty()) {
824 TPaths = std::move(PathsToPhiDef);
825 return;
826 }
827
828 assert(MaxNumPaths >= PathsToPhiDef.size() && !PathsToPhiDef.empty());
829 auto PathsLimit = MaxNumPaths / PathsToPhiDef.size();
830 // Find and append paths from SwitchPhiDefBB to SwitchBlock.
831 PathsType PathsToSwitchBB =
832 paths(SwitchPhiDefBB, SwitchBlock, VB, /* PathDepth = */ 1, PathsLimit);
833 if (PathsToSwitchBB.empty())
834 return;
835
836 std::vector<ThreadingPath> TempList;
837 for (const ThreadingPath &Path : PathsToPhiDef) {
838 SmallPtrSet<BasicBlock *, 32> PathSet(Path.getPath().begin(),
839 Path.getPath().end());
840 for (const PathType &PathToSw : PathsToSwitchBB) {
841 if (any_of(llvm::drop_begin(PathToSw),
842 [&](const BasicBlock *BB) { return PathSet.contains(BB); }))
843 continue;
844 ThreadingPath PathCopy(Path);
845 PathCopy.appendExcludingFirst(PathToSw);
846 TempList.push_back(PathCopy);
847 }
848 }
849 TPaths = std::move(TempList);
850 }
851
852 /// Fast helper to get the successor corresponding to a particular case value
853 /// for a switch statement.
854 BasicBlock *getNextCaseSuccessor(const APInt &NextState) {
855 // Precompute the value => successor mapping
856 if (CaseValToDest.empty()) {
857 for (auto Case : Switch->cases()) {
858 APInt CaseVal = Case.getCaseValue()->getValue();
859 CaseValToDest[CaseVal] = Case.getCaseSuccessor();
860 }
861 }
862
863 auto SuccIt = CaseValToDest.find(NextState);
864 return SuccIt == CaseValToDest.end() ? Switch->getDefaultDest()
865 : SuccIt->second;
866 }
867
868 // Two states are equivalent if they have the same switch destination.
869 // Unify the states in different threading path if the states are equivalent.
870 void unifyTPaths() {
871 SmallDenseMap<BasicBlock *, APInt> DestToState;
872 for (ThreadingPath &Path : TPaths) {
873 APInt NextState = Path.getExitValue();
874 BasicBlock *Dest = getNextCaseSuccessor(NextState);
875 auto [StateIt, Inserted] = DestToState.try_emplace(Dest, NextState);
876 if (Inserted)
877 continue;
878 if (NextState != StateIt->second) {
879 LLVM_DEBUG(dbgs() << "Next state in " << Path << " is equivalent to "
880 << StateIt->second << "\n");
881 Path.setExitValue(StateIt->second);
882 }
883 }
884 }
885
886 unsigned NumVisited = 0;
887 SwitchInst *Switch;
888 BasicBlock *SwitchBlock;
889 OptimizationRemarkEmitter *ORE;
890 std::vector<ThreadingPath> TPaths;
891 DenseMap<APInt, BasicBlock *> CaseValToDest;
892 LoopInfo *LI;
893 Loop *SwitchOuterLoop;
894};
895
896struct TransformDFA {
897 TransformDFA(AllSwitchPaths *SwitchPaths, DomTreeUpdater *DTU,
898 AssumptionCache *AC, TargetTransformInfo *TTI,
899 OptimizationRemarkEmitter *ORE,
900 SmallPtrSet<const Value *, 32> EphValues)
901 : SwitchPaths(SwitchPaths), DTU(DTU), AC(AC), TTI(TTI), ORE(ORE),
902 EphValues(EphValues) {}
903
904 bool run() {
905 if (isLegalAndProfitableToTransform()) {
906 createAllExitPaths();
907 NumTransforms++;
908 return true;
909 }
910 return false;
911 }
912
913private:
914 /// This function performs both a legality check and profitability check at
915 /// the same time since it is convenient to do so. It iterates through all
916 /// blocks that will be cloned, and keeps track of the duplication cost. It
917 /// also returns false if it is illegal to clone some required block.
918 bool isLegalAndProfitableToTransform() {
919 CodeMetrics Metrics;
920 uint64_t NumClonedInst = 0;
921 SwitchInst *Switch = SwitchPaths->getSwitchInst();
922
923 // Don't thread switch without multiple successors.
924 if (Switch->getNumSuccessors() <= 1)
925 return false;
926
927 // Note that DuplicateBlockMap is not being used as intended here. It is
928 // just being used to ensure (BB, State) pairs are only counted once.
929 DuplicateBlockMap DuplicateMap;
930 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
931 PathType PathBBs = TPath.getPath();
932 APInt NextState = TPath.getExitValue();
933 const BasicBlock *Determinator = TPath.getDeterminatorBB();
934
935 // Update Metrics for the Switch block, this is always cloned
936 BasicBlock *BB = SwitchPaths->getSwitchBlock();
937 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
938 if (!VisitedBB) {
939 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
940 NumClonedInst += BB->size();
941 DuplicateMap[BB].push_back({BB, NextState});
942 }
943
944 // If the Switch block is the Determinator, then we can continue since
945 // this is the only block that is cloned and we already counted for it.
946 if (PathBBs.front() == Determinator)
947 continue;
948
949 // Otherwise update Metrics for all blocks that will be cloned. If any
950 // block is already cloned and would be reused, don't double count it.
951 auto DetIt = llvm::find(PathBBs, Determinator);
952 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
953 BB = *BBIt;
954 VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
955 if (VisitedBB)
956 continue;
957 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
958 NumClonedInst += BB->size();
959 DuplicateMap[BB].push_back({BB, NextState});
960 }
961
962 if (Metrics.notDuplicatable) {
963 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
964 << "non-duplicatable instructions.\n");
965 ORE->emit([&]() {
966 return OptimizationRemarkMissed(DEBUG_TYPE, "NonDuplicatableInst",
967 Switch)
968 << "Contains non-duplicatable instructions.";
969 });
970 return false;
971 }
972
973 // FIXME: Allow jump threading with controlled convergence.
974 if (Metrics.Convergence != ConvergenceKind::None) {
975 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
976 << "convergent instructions.\n");
977 ORE->emit([&]() {
978 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch)
979 << "Contains convergent instructions.";
980 });
981 return false;
982 }
983
984 if (!Metrics.NumInsts.isValid()) {
985 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
986 << "instructions with invalid cost.\n");
987 ORE->emit([&]() {
988 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch)
989 << "Contains instructions with invalid cost.";
990 });
991 return false;
992 }
993 }
994
995 // Too much cloned instructions slow down later optimizations, especially
996 // SLPVectorizer.
997 // TODO: Thread the switch partially before reaching the threshold.
998 uint64_t NumOrigInst = 0;
999 uint64_t NumOuterUseBlock = 0;
1000 for (auto *BB : DuplicateMap.keys()) {
1001 NumOrigInst += BB->size();
1002 // Only unduplicated blocks with single predecessor require new phi
1003 // nodes.
1004 for (auto *Succ : successors(BB))
1005 if (!DuplicateMap.count(Succ) && Succ->getSinglePredecessor())
1006 NumOuterUseBlock++;
1007 }
1008
1009 if (double(NumClonedInst) / double(NumOrigInst) > MaxClonedRate) {
1010 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, too much "
1011 "instructions wll be cloned\n");
1012 ORE->emit([&]() {
1013 return OptimizationRemarkMissed(DEBUG_TYPE, "NotProfitable", Switch)
1014 << "Too much instructions will be cloned.";
1015 });
1016 return false;
1017 }
1018
1019 // Too much unduplicated blocks with outer uses may cause too much
1020 // insertions of phi nodes for duplicated definitions. TODO: Drop this
1021 // threshold if we come up with another way to reduce the number of inserted
1022 // phi nodes.
1023 if (NumOuterUseBlock > MaxOuterUseBlocks) {
1024 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, too much "
1025 "blocks with outer uses\n");
1026 ORE->emit([&]() {
1027 return OptimizationRemarkMissed(DEBUG_TYPE, "NotProfitable", Switch)
1028 << "Too much blocks with outer uses.";
1029 });
1030 return false;
1031 }
1032
1033 InstructionCost DuplicationCost = 0;
1034
1035 unsigned JumpTableSize = 0;
1036 TTI->getEstimatedNumberOfCaseClusters(*Switch, JumpTableSize, nullptr,
1037 nullptr);
1038 if (JumpTableSize == 0) {
1039 // Factor in the number of conditional branches reduced from jump
1040 // threading. Assume that lowering the switch block is implemented by
1041 // using binary search, hence the LogBase2().
1042 unsigned CondBranches =
1043 APInt(32, Switch->getNumSuccessors()).ceilLogBase2();
1044 assert(CondBranches > 0 &&
1045 "The threaded switch must have multiple branches");
1046 DuplicationCost = Metrics.NumInsts / CondBranches;
1047 } else {
1048 // Compared with jump tables, the DFA optimizer removes an indirect branch
1049 // on each loop iteration, thus making branch prediction more precise. The
1050 // more branch targets there are, the more likely it is for the branch
1051 // predictor to make a mistake, and the more benefit there is in the DFA
1052 // optimizer. Thus, the more branch targets there are, the lower is the
1053 // cost of the DFA opt.
1054 DuplicationCost = Metrics.NumInsts / JumpTableSize;
1055 }
1056
1057 LLVM_DEBUG(dbgs() << "\nDFA Jump Threading: Cost to jump thread block "
1058 << SwitchPaths->getSwitchBlock()->getName()
1059 << " is: " << DuplicationCost << "\n\n");
1060
1061 if (DuplicationCost > CostThreshold) {
1062 LLVM_DEBUG(dbgs() << "Not jump threading, duplication cost exceeds the "
1063 << "cost threshold.\n");
1064 ORE->emit([&]() {
1065 return OptimizationRemarkMissed(DEBUG_TYPE, "NotProfitable", Switch)
1066 << "Duplication cost exceeds the cost threshold (cost="
1067 << ore::NV("Cost", DuplicationCost)
1068 << ", threshold=" << ore::NV("Threshold", CostThreshold) << ").";
1069 });
1070 return false;
1071 }
1072
1073 ORE->emit([&]() {
1074 return OptimizationRemark(DEBUG_TYPE, "JumpThreaded", Switch)
1075 << "Switch statement jump-threaded.";
1076 });
1077
1078 return true;
1079 }
1080
1081 /// Transform each threading path to effectively jump thread the DFA.
1082 void createAllExitPaths() {
1083 // Move the switch block to the end of the path, since it will be duplicated
1084 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock();
1085 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
1086 LLVM_DEBUG(dbgs() << TPath << "\n");
1087 // TODO: Fix exit path creation logic so that we dont need this
1088 // placeholder.
1089 TPath.push_front(SwitchBlock);
1090 }
1091
1092 // Transform the ThreadingPaths and keep track of the cloned values
1093 DuplicateBlockMap DuplicateMap;
1094 DefMap NewDefs;
1095
1096 SmallPtrSet<BasicBlock *, 16> BlocksToClean;
1097 BlocksToClean.insert_range(successors(SwitchBlock));
1098
1099 for (const ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
1100 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, DTU);
1101 NumPaths++;
1102 }
1103
1104 // After all paths are cloned, now update the last successor of the cloned
1105 // path so it skips over the switch statement
1106 for (const ThreadingPath &TPath : SwitchPaths->getThreadingPaths())
1107 updateLastSuccessor(TPath, DuplicateMap, DTU);
1108
1109 // For each instruction that was cloned and used outside, update its uses
1110 updateSSA(NewDefs);
1111
1112 // Clean PHI Nodes for the newly created blocks
1113 for (BasicBlock *BB : BlocksToClean)
1114 cleanPhiNodes(BB);
1115 }
1116
1117 /// For a specific ThreadingPath \p Path, create an exit path starting from
1118 /// the determinator block.
1119 ///
1120 /// To remember the correct destination, we have to duplicate blocks
1121 /// corresponding to each state. Also update the terminating instruction of
1122 /// the predecessors, and phis in the successor blocks.
1123 void createExitPath(DefMap &NewDefs, const ThreadingPath &Path,
1124 DuplicateBlockMap &DuplicateMap,
1125 SmallPtrSet<BasicBlock *, 16> &BlocksToClean,
1126 DomTreeUpdater *DTU) {
1127 APInt NextState = Path.getExitValue();
1128 const BasicBlock *Determinator = Path.getDeterminatorBB();
1129 PathType PathBBs = Path.getPath();
1130
1131 // Don't select the placeholder block in front
1132 if (PathBBs.front() == Determinator)
1133 PathBBs.pop_front();
1134
1135 auto DetIt = llvm::find(PathBBs, Determinator);
1136 // When there is only one BB in PathBBs, the determinator takes itself as a
1137 // direct predecessor.
1138 BasicBlock *PrevBB = PathBBs.size() == 1 ? *DetIt : *std::prev(DetIt);
1139 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
1140 BasicBlock *BB = *BBIt;
1141 BlocksToClean.insert(BB);
1142
1143 // We already cloned BB for this NextState, now just update the branch
1144 // and continue.
1145 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap);
1146 if (NextBB) {
1147 updatePredecessor(PrevBB, BB, NextBB, DTU);
1148 PrevBB = NextBB;
1149 continue;
1150 }
1151
1152 // Clone the BB and update the successor of Prev to jump to the new block
1153 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor(
1154 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU);
1155 DuplicateMap[BB].push_back({NewBB, NextState});
1156 BlocksToClean.insert(NewBB);
1157 PrevBB = NewBB;
1158 }
1159 }
1160
1161 /// Restore SSA form after cloning blocks.
1162 ///
1163 /// Each cloned block creates new defs for a variable, and the uses need to be
1164 /// updated to reflect this. The uses may be replaced with a cloned value, or
1165 /// some derived phi instruction. Note that all uses of a value defined in the
1166 /// same block were already remapped when cloning the block.
1167 void updateSSA(DefMap &NewDefs) {
1168 SSAUpdaterBulk SSAUpdate;
1169 SmallVector<Use *, 16> UsesToRename;
1170
1171 for (const auto &KV : NewDefs) {
1172 Instruction *I = KV.first;
1173 BasicBlock *BB = I->getParent();
1174 std::vector<Instruction *> Cloned = KV.second;
1175
1176 // Scan all uses of this instruction to see if it is used outside of its
1177 // block, and if so, record them in UsesToRename.
1178 for (Use &U : I->uses()) {
1179 Instruction *User = cast<Instruction>(U.getUser());
1180 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1181 if (UserPN->getIncomingBlock(U) == BB)
1182 continue;
1183 } else if (User->getParent() == BB) {
1184 continue;
1185 }
1186
1187 UsesToRename.push_back(&U);
1188 }
1189
1190 // If there are no uses outside the block, we're done with this
1191 // instruction.
1192 if (UsesToRename.empty())
1193 continue;
1194 LLVM_DEBUG(dbgs() << "DFA-JT: Renaming non-local uses of: " << *I
1195 << "\n");
1196
1197 // We found a use of I outside of BB. Rename all uses of I that are
1198 // outside its block to be uses of the appropriate PHI node etc. See
1199 // ValuesInBlocks with the values we know.
1200 unsigned VarNum = SSAUpdate.AddVariable(I->getName(), I->getType());
1201 SSAUpdate.AddAvailableValue(VarNum, BB, I);
1202 for (Instruction *New : Cloned)
1203 SSAUpdate.AddAvailableValue(VarNum, New->getParent(), New);
1204
1205 while (!UsesToRename.empty())
1206 SSAUpdate.AddUse(VarNum, UsesToRename.pop_back_val());
1207
1208 LLVM_DEBUG(dbgs() << "\n");
1209 }
1210 // SSAUpdater handles phi placement and renaming uses with the appropriate
1211 // value.
1212 SSAUpdate.RewriteAllUses(&DTU->getDomTree());
1213 }
1214
1215 /// Helper to get the successor corresponding to a particular case value for
1216 /// a switch statement.
1217 /// TODO: Unify it with SwitchPaths->getNextCaseSuccessor(SwitchInst *Switch)
1218 /// by updating cached value => successor mapping during threading.
1219 static BasicBlock *getNextCaseSuccessor(SwitchInst *Switch,
1220 const APInt &NextState) {
1221 BasicBlock *NextCase = nullptr;
1222 for (auto Case : Switch->cases()) {
1223 if (Case.getCaseValue()->getValue() == NextState) {
1224 NextCase = Case.getCaseSuccessor();
1225 break;
1226 }
1227 }
1228 if (!NextCase)
1229 NextCase = Switch->getDefaultDest();
1230 return NextCase;
1231 }
1232
1233 /// Clones a basic block, and adds it to the CFG.
1234 ///
1235 /// This function also includes updating phi nodes in the successors of the
1236 /// BB, and remapping uses that were defined locally in the cloned BB.
1237 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB,
1238 const APInt &NextState,
1239 DuplicateBlockMap &DuplicateMap,
1240 DefMap &NewDefs,
1241 DomTreeUpdater *DTU) {
1242 ValueToValueMapTy VMap;
1243 BasicBlock *NewBB = CloneBasicBlock(
1244 BB, VMap, ".jt" + std::to_string(NextState.getLimitedValue()),
1245 BB->getParent());
1246 NewBB->moveAfter(BB);
1247 NumCloned++;
1248
1249 // Give the clone fresh noalias scopes; otherwise it shares BB's scopes and
1250 // AA can treat aliasing accesses on different threaded paths as noalias.
1251 SmallVector<MDNode *> NoAliasScopes;
1252 identifyNoAliasScopesToClone({NewBB}, NoAliasScopes);
1253 cloneAndAdaptNoAliasScopes(NoAliasScopes, {NewBB}, BB->getContext(), "dfa");
1254
1255 for (Instruction &I : *NewBB) {
1256 // Do not remap operands of PHINode in case a definition in BB is an
1257 // incoming value to a phi in the same block. This incoming value will
1258 // be renamed later while restoring SSA.
1259 if (isa<PHINode>(&I))
1260 continue;
1261 RemapInstruction(&I, VMap,
1263 if (AssumeInst *II = dyn_cast<AssumeInst>(&I))
1265 }
1266
1267 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap);
1268 updatePredecessor(PrevBB, BB, NewBB, DTU);
1269 updateDefMap(NewDefs, VMap);
1270
1271 // Add all successors to the DominatorTree
1272 SmallPtrSet<BasicBlock *, 4> SuccSet;
1273 for (auto *SuccBB : successors(NewBB)) {
1274 if (SuccSet.insert(SuccBB).second)
1275 DTU->applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}});
1276 }
1277 SuccSet.clear();
1278 return NewBB;
1279 }
1280
1281 /// Update the phi nodes in BB's successors.
1282 ///
1283 /// This means creating a new incoming value from NewBB with the new
1284 /// instruction wherever there is an incoming value from BB.
1285 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB,
1286 const APInt &NextState, ValueToValueMapTy &VMap,
1287 DuplicateBlockMap &DuplicateMap) {
1288 std::vector<BasicBlock *> BlocksToUpdate;
1289
1290 // If BB is the last block in the path, we can simply update the one case
1291 // successor that will be reached.
1292 if (BB == SwitchPaths->getSwitchBlock()) {
1293 SwitchInst *Switch = SwitchPaths->getSwitchInst();
1294 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1295 BlocksToUpdate.push_back(NextCase);
1296 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap);
1297 if (ClonedSucc)
1298 BlocksToUpdate.push_back(ClonedSucc);
1299 }
1300 // Otherwise update phis in all successors.
1301 else {
1302 for (BasicBlock *Succ : successors(BB)) {
1303 BlocksToUpdate.push_back(Succ);
1304
1305 // Check if a successor has already been cloned for the particular exit
1306 // value. In this case if a successor was already cloned, the phi nodes
1307 // in the cloned block should be updated directly.
1308 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap);
1309 if (ClonedSucc)
1310 BlocksToUpdate.push_back(ClonedSucc);
1311 }
1312 }
1313
1314 // If there is a phi with an incoming value from BB, create a new incoming
1315 // value for the new predecessor ClonedBB. The value will either be the same
1316 // value from BB or a cloned value.
1317 for (BasicBlock *Succ : BlocksToUpdate) {
1318 for (PHINode &Phi : Succ->phis()) {
1319 Value *Incoming = Phi.getIncomingValueForBlock(BB);
1320 if (Incoming) {
1321 if (isa<Constant>(Incoming)) {
1322 Phi.addIncoming(Incoming, ClonedBB);
1323 continue;
1324 }
1325 Value *ClonedVal = VMap[Incoming];
1326 if (ClonedVal)
1327 Phi.addIncoming(ClonedVal, ClonedBB);
1328 else
1329 Phi.addIncoming(Incoming, ClonedBB);
1330 }
1331 }
1332 }
1333 }
1334
1335 /// Sets the successor of PrevBB to be NewBB instead of OldBB. Note that all
1336 /// other successors are kept as well.
1337 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB,
1338 BasicBlock *NewBB, DomTreeUpdater *DTU) {
1339 // When a path is reused, there is a chance that predecessors were already
1340 // updated before. Check if the predecessor needs to be updated first.
1341 if (!isPredecessor(OldBB, PrevBB))
1342 return;
1343
1344 Instruction *PrevTerm = PrevBB->getTerminator();
1345 for (unsigned Idx = 0; Idx < PrevTerm->getNumSuccessors(); Idx++) {
1346 if (PrevTerm->getSuccessor(Idx) == OldBB) {
1347 OldBB->removePredecessor(PrevBB, /* KeepOneInputPHIs = */ true);
1348 PrevTerm->setSuccessor(Idx, NewBB);
1349 }
1350 }
1351 DTU->applyUpdates({{DominatorTree::Delete, PrevBB, OldBB},
1352 {DominatorTree::Insert, PrevBB, NewBB}});
1353 }
1354
1355 /// Add new value mappings to the DefMap to keep track of all new definitions
1356 /// for a particular instruction. These will be used while updating SSA form.
1357 void updateDefMap(DefMap &NewDefs, ValueToValueMapTy &VMap) {
1359 NewDefsVector.reserve(VMap.size());
1360
1361 for (auto Entry : VMap) {
1362 Instruction *Inst =
1363 dyn_cast<Instruction>(const_cast<Value *>(Entry.first));
1364 if (!Inst || !Entry.second ||
1366 continue;
1367
1368 Instruction *Cloned = dyn_cast<Instruction>(Entry.second);
1369 if (!Cloned)
1370 continue;
1371
1372 NewDefsVector.push_back({Inst, Cloned});
1373 }
1374
1375 // Sort the defs to get deterministic insertion order into NewDefs.
1376 sort(NewDefsVector, [](const auto &LHS, const auto &RHS) {
1377 if (LHS.first == RHS.first)
1378 return LHS.second->comesBefore(RHS.second);
1379 return LHS.first->comesBefore(RHS.first);
1380 });
1381
1382 for (const auto &KV : NewDefsVector)
1383 NewDefs[KV.first].push_back(KV.second);
1384 }
1385
1386 /// Update the last branch of a particular cloned path to point to the correct
1387 /// case successor.
1388 ///
1389 /// Note that this is an optional step and would have been done in later
1390 /// optimizations, but it makes the CFG significantly easier to work with.
1391 void updateLastSuccessor(const ThreadingPath &TPath,
1392 DuplicateBlockMap &DuplicateMap,
1393 DomTreeUpdater *DTU) {
1394 APInt NextState = TPath.getExitValue();
1395 BasicBlock *BB = TPath.getPath().back();
1396 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap);
1397
1398 // Note multiple paths can end at the same block so check that it is not
1399 // updated yet
1400 if (!isa<SwitchInst>(LastBlock->getTerminator()))
1401 return;
1402 SwitchInst *Switch = cast<SwitchInst>(LastBlock->getTerminator());
1403 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1404
1405 std::vector<DominatorTree::UpdateType> DTUpdates;
1406 SmallPtrSet<BasicBlock *, 4> SuccSet;
1407 for (BasicBlock *Succ : successors(LastBlock)) {
1408 if (Succ != NextCase && SuccSet.insert(Succ).second)
1409 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ});
1410 }
1411
1412 Switch->eraseFromParent();
1413 UncondBrInst::Create(NextCase, LastBlock);
1414
1415 DTU->applyUpdates(DTUpdates);
1416 }
1417
1418 /// After cloning blocks, some of the phi nodes have extra incoming values
1419 /// that are no longer used. This function removes them.
1420 void cleanPhiNodes(BasicBlock *BB) {
1421 // If BB is no longer reachable, remove any remaining phi nodes
1422 if (pred_empty(BB)) {
1423 for (PHINode &PN : make_early_inc_range(BB->phis())) {
1424 PN.replaceAllUsesWith(PoisonValue::get(PN.getType()));
1425 PN.eraseFromParent();
1426 }
1427 return;
1428 }
1429
1430 // Remove any incoming values that come from an invalid predecessor
1431 for (PHINode &Phi : BB->phis())
1432 Phi.removeIncomingValueIf([&](unsigned Index) {
1433 BasicBlock *IncomingBB = Phi.getIncomingBlock(Index);
1434 return !isPredecessor(BB, IncomingBB);
1435 });
1436 }
1437
1438 /// Checks if BB was already cloned for a particular next state value. If it
1439 /// was then it returns this cloned block, and otherwise null.
1440 BasicBlock *getClonedBB(BasicBlock *BB, const APInt &NextState,
1441 DuplicateBlockMap &DuplicateMap) {
1442 CloneList ClonedBBs = DuplicateMap[BB];
1443
1444 // Find an entry in the CloneList with this NextState. If it exists then
1445 // return the corresponding BB
1446 auto It = llvm::find_if(ClonedBBs, [NextState](const ClonedBlock &C) {
1447 return C.State == NextState;
1448 });
1449 return It != ClonedBBs.end() ? (*It).BB : nullptr;
1450 }
1451
1452 /// Returns true if IncomingBB is a predecessor of BB.
1453 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) {
1454 return llvm::is_contained(predecessors(BB), IncomingBB);
1455 }
1456
1457 AllSwitchPaths *SwitchPaths;
1458 DomTreeUpdater *DTU;
1459 AssumptionCache *AC;
1460 TargetTransformInfo *TTI;
1461 OptimizationRemarkEmitter *ORE;
1462 SmallPtrSet<const Value *, 32> EphValues;
1463 std::vector<ThreadingPath> TPaths;
1464};
1465} // namespace
1466
1467bool DFAJumpThreading::run(Function &F) {
1468 LLVM_DEBUG(dbgs() << "\nDFA Jump threading: " << F.getName() << "\n");
1469
1470 if (F.hasOptSize()) {
1471 LLVM_DEBUG(dbgs() << "Skipping due to the 'minsize' attribute\n");
1472 return false;
1473 }
1474
1475 if (ClViewCfgBefore)
1476 F.viewCFG();
1477
1478 SmallVector<AllSwitchPaths, 2> ThreadableLoops;
1479 bool MadeChanges = false;
1480 LoopInfoBroken = false;
1481
1482 for (BasicBlock &BB : F) {
1484 if (!SI)
1485 continue;
1486
1487 LLVM_DEBUG(dbgs() << "\nCheck if SwitchInst in BB " << BB.getName()
1488 << " is a candidate\n");
1489 MainSwitch Switch(SI, LI, ORE);
1490
1491 if (!Switch.getInstr()) {
1492 LLVM_DEBUG(dbgs() << "\nSwitchInst in BB " << BB.getName() << " is not a "
1493 << "candidate for jump threading\n");
1494 continue;
1495 }
1496
1497 LLVM_DEBUG(dbgs() << "\nSwitchInst in BB " << BB.getName() << " is a "
1498 << "candidate for jump threading\n");
1499 LLVM_DEBUG(SI->dump());
1500
1501 unfoldSelectInstrs(Switch.getSelectInsts());
1502 if (!Switch.getSelectInsts().empty())
1503 MadeChanges = true;
1504
1505 AllSwitchPaths SwitchPaths(&Switch, ORE, LI,
1506 LI->getLoopFor(&BB)->getOutermostLoop());
1507 SwitchPaths.run();
1508
1509 if (SwitchPaths.getNumThreadingPaths() > 0) {
1510 ThreadableLoops.push_back(SwitchPaths);
1511
1512 // For the time being limit this optimization to occurring once in a
1513 // function since it can change the CFG significantly. This is not a
1514 // strict requirement but it can cause buggy behavior if there is an
1515 // overlap of blocks in different opportunities. There is a lot of room to
1516 // experiment with catching more opportunities here.
1517 // NOTE: To release this contraint, we must handle LoopInfo invalidation
1518 break;
1519 }
1520 }
1521
1522#ifdef NDEBUG
1523 LI->verify(DTU->getDomTree());
1524#endif
1525
1526 SmallPtrSet<const Value *, 32> EphValues;
1527 if (ThreadableLoops.size() > 0)
1528 CodeMetrics::collectEphemeralValues(&F, AC, EphValues);
1529
1530 for (AllSwitchPaths SwitchPaths : ThreadableLoops) {
1531 TransformDFA Transform(&SwitchPaths, DTU, AC, TTI, ORE, EphValues);
1532 if (Transform.run())
1533 MadeChanges = LoopInfoBroken = true;
1534 }
1535
1536 DTU->flush();
1537
1538#ifdef EXPENSIVE_CHECKS
1539 verifyFunction(F, &dbgs());
1540#endif
1541
1542 if (MadeChanges && VerifyDomInfo)
1543 assert(DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full) &&
1544 "Failed to maintain validity of domtree!");
1545
1546 return MadeChanges;
1547}
1548
1549/// Integrate with the new Pass Manager
1554 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
1557
1558 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1559 DFAJumpThreading ThreadImpl(&AC, &DTU, &LI, &TTI, &ORE);
1560 if (!ThreadImpl.run(F))
1561 return PreservedAnalyses::all();
1562
1565 if (!ThreadImpl.LoopInfoBroken)
1566 PA.preserve<LoopAnalysis>();
1567 return PA;
1568}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
std::deque< BasicBlock * > PathType
std::vector< PathType > PathsType
MapVector< Instruction *, std::vector< Instruction * > > DefMap
std::vector< ClonedBlock > CloneList
DenseMap< BasicBlock *, CloneList > DuplicateBlockMap
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
#define DEBUG_TYPE
#define _
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static void updateSSA(DominatorTree &DT, CallBrInst *CBR, CallInst *Intrinsic, SSAUpdater &SSAUpdate)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
Machine Trace Metrics
uint64_t IntrinsicInst * II
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:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
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:476
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:530
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
size_t size() const
Definition BasicBlock.h:482
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
BasicBlock * getSuccessor(unsigned i) const
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:301
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:221
Analysis pass which computes a DominatorTree.
Definition Dominators.h:270
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:151
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI 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:587
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
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.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
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 LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
LLVM_ABI unsigned AddVariable(StringRef Name, Type *Ty)
Add a new variable to the SSA rewriter.
LLVM_ABI void AddAvailableValue(unsigned Var, BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
LLVM_ABI void RewriteAllUses(DominatorTree *DT, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Perform all the necessary updates, including new PHI-nodes insertion and the requested uses update.
LLVM_ABI 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
bool erase(PtrType Ptr)
Remove pointer from the set.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
void push_back(const T &Elt)
BasicBlock * getDefaultDest() const
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) const
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
size_type size() const
Definition ValueMap.h:144
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI std::string getNameOrAsOperand() const
Definition Value.cpp:461
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
@ Entry
Definition COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
initializer< Ty > init(const Ty &Val)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:31
DXILDebugInfoMap run(Module &M)
@ User
could "use" a pointer
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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:1764
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
static cl::opt< unsigned > MaxNumPaths("dfa-max-num-paths", cl::desc("Max number of paths enumerated around a switch"), cl::Hidden, cl::init(200))
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2207
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
auto pred_size(const MachineBasicBlock *BB)
static cl::opt< bool > ClViewCfgBefore("dfa-jump-view-cfg-before", cl::desc("View the CFG before DFA Jump Threading"), cl::Hidden, cl::init(false))
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:365
static cl::opt< double > MaxClonedRate("dfa-max-cloned-rate", cl::desc("Maximum cloned instructions rate accepted for the transformation"), cl::Hidden, cl::init(7.5))
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1745
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
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(2500))
TargetTransformInfo TTI
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
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))
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
LLVM_ABI void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI bool VerifyDomInfo
Enables verification of dominator trees.
static cl::opt< unsigned > MaxOuterUseBlocks("dfa-max-out-use-blocks", cl::desc("Maximum unduplicated blocks with outer uses " "accepted for the transformation"), cl::Hidden, cl::init(40))
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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:1771
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))
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
static cl::opt< unsigned > CostThreshold("dfa-cost-threshold", cl::desc("Maximum cost accepted for the transformation"), cl::Hidden, cl::init(50))
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
static LLVM_ABI 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).
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Integrate with the new Pass Manager.