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 // The branch from NewBlock and the new CondBr from StartBlock collectively
221 // substitute the existing Select+Br instructions, so following the rules
222 // for updating source locations we assign each of them the merged location
223 // of the Select+Br.
224 DebugLoc SelectBranchLoc = DebugLoc::getMergedLocation(
225 StartBlockTerm->getDebugLoc(), SI->getDebugLoc());
226 Instruction *NewToEndBr = UncondBrInst::Create(EndBlock, NewBlock);
227 NewToEndBr->setDebugLoc(SelectBranchLoc);
228 DTU->applyUpdates({{DominatorTree::Insert, NewBlock, EndBlock}});
229
230 // StartBlock
231 // | \
232 // | NewBlock
233 // | /
234 // EndBlock
235 Value *SIOp1 = SI->getTrueValue();
236 Value *SIOp2 = SI->getFalseValue();
237
238 PHINode *NewPhi = PHINode::Create(SIUse->getType(), 1,
239 Twine(SIOp2->getName(), ".si.unfold.phi"),
240 NewBlock->getFirstInsertionPt());
241 NewPhi->addIncoming(SIOp2, StartBlock);
242
243 // Update any other PHI nodes in EndBlock.
244 for (PHINode &Phi : EndBlock->phis()) {
245 if (SIUse == &Phi)
246 continue;
247 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), NewBlock);
248 }
249
250 // Update the phi node of SI, which is its only use.
251 if (EndBlock == SIUse->getParent()) {
252 SIUse->addIncoming(NewPhi, NewBlock);
253 SIUse->replaceUsesOfWith(SI, SIOp1);
254 } else {
255 PHINode *EndPhi = PHINode::Create(SIUse->getType(), pred_size(EndBlock),
256 Twine(SI->getName(), ".si.unfold.phi"),
257 EndBlock->getFirstInsertionPt());
258 for (BasicBlock *Pred : predecessors(EndBlock)) {
259 if (Pred != StartBlock && Pred != NewBlock)
260 EndPhi->addIncoming(EndPhi, Pred);
261 }
262
263 EndPhi->addIncoming(SIOp1, StartBlock);
264 EndPhi->addIncoming(NewPhi, NewBlock);
265 SIUse->replaceUsesOfWith(SI, EndPhi);
266 SIUse = EndPhi;
267 }
268
269 if (auto *OpSi = dyn_cast<SelectInst>(SIOp1))
270 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, SIUse));
271 if (auto *OpSi = dyn_cast<SelectInst>(SIOp2))
272 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, NewPhi));
273
274 // Insert the real conditional branch based on the original condition.
275 StartBlockTerm->eraseFromParent();
276 auto *BI =
277 CondBrInst::Create(SI->getCondition(), EndBlock, NewBlock, StartBlock);
278 BI->setDebugLoc(SelectBranchLoc);
280 BI->setMetadata(LLVMContext::MD_prof,
281 SI->getMetadata(LLVMContext::MD_prof));
282 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, NewBlock}});
283 } else {
284 BasicBlock *EndBlock = SIUse->getParent();
285 BasicBlock *NewBlockT = BasicBlock::Create(
286 SI->getContext(), Twine(SI->getName(), ".si.unfold.true"),
287 EndBlock->getParent(), EndBlock);
288 BasicBlock *NewBlockF = BasicBlock::Create(
289 SI->getContext(), Twine(SI->getName(), ".si.unfold.false"),
290 EndBlock->getParent(), EndBlock);
291
292 NewBBs->push_back(NewBlockT);
293 NewBBs->push_back(NewBlockF);
294
295 // Def only has one use in EndBlock.
296 // Before transformation:
297 // StartBlock(Def)
298 // | \
299 // EndBlock OtherBlock
300 // (Use)
301 //
302 // After transformation:
303 // StartBlock(Def)
304 // | \
305 // | OtherBlock
306 // NewBlockT
307 // | \
308 // | NewBlockF
309 // | /
310 // | /
311 // EndBlock
312 // (Use)
313 Instruction *NewFToEnd = UncondBrInst::Create(EndBlock, NewBlockF);
314 // Insert the real conditional branch based on the original condition.
315 auto *BI =
316 CondBrInst::Create(SI->getCondition(), EndBlock, NewBlockF, NewBlockT);
317 // The branches from NewBlockT and NewBlockF are performing the Select
318 // logic, and so assume its source location.
319 DebugLoc SelectLoc = SI->getDebugLoc();
320 NewFToEnd->setDebugLoc(SelectLoc);
321 BI->setDebugLoc(SelectLoc);
323 BI->setMetadata(LLVMContext::MD_prof,
324 SI->getMetadata(LLVMContext::MD_prof));
325 DTU->applyUpdates({{DominatorTree::Insert, NewBlockT, NewBlockF},
326 {DominatorTree::Insert, NewBlockT, EndBlock},
327 {DominatorTree::Insert, NewBlockF, EndBlock}});
328
329 Value *TrueVal = SI->getTrueValue();
330 Value *FalseVal = SI->getFalseValue();
331
332 PHINode *NewPhiT = PHINode::Create(
333 SIUse->getType(), 1, Twine(TrueVal->getName(), ".si.unfold.phi"),
334 NewBlockT->getFirstInsertionPt());
335 PHINode *NewPhiF = PHINode::Create(
336 SIUse->getType(), 1, Twine(FalseVal->getName(), ".si.unfold.phi"),
337 NewBlockF->getFirstInsertionPt());
338 NewPhiT->addIncoming(TrueVal, StartBlock);
339 NewPhiF->addIncoming(FalseVal, NewBlockT);
340
341 if (auto *TrueSI = dyn_cast<SelectInst>(TrueVal))
342 NewSIsToUnfold->push_back(SelectInstToUnfold(TrueSI, NewPhiT));
343 if (auto *FalseSi = dyn_cast<SelectInst>(FalseVal))
344 NewSIsToUnfold->push_back(SelectInstToUnfold(FalseSi, NewPhiF));
345
346 SIUse->addIncoming(NewPhiT, NewBlockT);
347 SIUse->addIncoming(NewPhiF, NewBlockF);
348 SIUse->removeIncomingValue(StartBlock);
349
350 // Update any other PHI nodes in EndBlock.
351 for (PHINode &Phi : EndBlock->phis()) {
352 if (SIUse == &Phi)
353 continue;
354 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), NewBlockT);
355 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), NewBlockF);
356 Phi.removeIncomingValue(StartBlock);
357 }
358
359 // Update the appropriate successor of the start block to point to the new
360 // unfolded block.
361 CondBrInst *CondBr = cast<CondBrInst>(StartBlock->getTerminator());
362 unsigned SuccNum = CondBr->getSuccessor(1) == EndBlock ? 1 : 0;
363 CondBr->setSuccessor(SuccNum, NewBlockT);
364 DTU->applyUpdates({{DominatorTree::Delete, StartBlock, EndBlock},
365 {DominatorTree::Insert, StartBlock, NewBlockT}});
366 }
367
368 // Preserve loop info
369 if (Loop *L = LI->getLoopFor(StartBlock)) {
370 for (BasicBlock *NewBB : *NewBBs)
371 L->addBasicBlockToLoop(NewBB, *LI);
372 }
373
374 // The select is now dead.
375 assert(SI->use_empty() && "Select must be dead now");
376 SI->eraseFromParent();
377}
378
379namespace {
380struct ClonedBlock {
381 BasicBlock *BB;
382 APInt State; ///< \p State corresponds to the next value of a switch stmnt.
383};
384} // namespace
385
386typedef std::deque<BasicBlock *> PathType;
387typedef std::vector<PathType> PathsType;
389typedef std::vector<ClonedBlock> CloneList;
390
391// This data structure keeps track of all blocks that have been cloned. If two
392// different ThreadingPaths clone the same block for a certain state it should
393// be reused, and it can be looked up in this map.
395
396// This map keeps track of all the new definitions for an instruction. This
397// information is needed when restoring SSA form after cloning blocks.
399
400inline raw_ostream &operator<<(raw_ostream &OS, const PathType &Path) {
401 auto BBNames = llvm::map_range(
402 Path, [](const BasicBlock *BB) { return BB->getNameOrAsOperand(); });
403 OS << "< " << llvm::join(BBNames, ", ") << " >";
404 return OS;
405}
406
407namespace {
408/// ThreadingPath is a path in the control flow of a loop that can be threaded
409/// by cloning necessary basic blocks and replacing conditional branches with
410/// unconditional ones. A threading path includes a list of basic blocks, the
411/// exit state, and the block that determines the next state.
412struct ThreadingPath {
413 /// Exit value is DFA's exit state for the given path.
414 APInt getExitValue() const { return ExitVal; }
415 void setExitValue(const ConstantInt *V) {
416 ExitVal = V->getValue();
417 IsExitValSet = true;
418 }
419 void setExitValue(const APInt &V) {
420 ExitVal = V;
421 IsExitValSet = true;
422 }
423 bool isExitValueSet() const { return IsExitValSet; }
424
425 /// Determinator is the basic block that determines the next state of the DFA.
426 const BasicBlock *getDeterminatorBB() const { return DBB; }
427 void setDeterminator(const BasicBlock *BB) { DBB = BB; }
428
429 /// Path is a list of basic blocks.
430 const PathType &getPath() const { return Path; }
431 void setPath(const PathType &NewPath) { Path = NewPath; }
432 void push_back(BasicBlock *BB) { Path.push_back(BB); }
433 void push_front(BasicBlock *BB) { Path.push_front(BB); }
434 void appendExcludingFirst(const PathType &OtherPath) {
435 llvm::append_range(Path, llvm::drop_begin(OtherPath));
436 }
437
438 void print(raw_ostream &OS) const {
439 OS << Path << " [ " << ExitVal << ", " << DBB->getNameOrAsOperand() << " ]";
440 }
441
442private:
443 PathType Path;
444 APInt ExitVal;
445 const BasicBlock *DBB = nullptr;
446 bool IsExitValSet = false;
447};
448
449#ifndef NDEBUG
450inline raw_ostream &operator<<(raw_ostream &OS, const ThreadingPath &TPath) {
451 TPath.print(OS);
452 return OS;
453}
454#endif
455
456struct MainSwitch {
457 MainSwitch(SwitchInst *SI, LoopInfo *LI, OptimizationRemarkEmitter *ORE)
458 : LI(LI) {
459 if (isCandidate(SI)) {
460 Instr = SI;
461 } else {
462 ORE->emit([&]() {
463 return OptimizationRemarkMissed(DEBUG_TYPE, "SwitchNotPredictable", SI)
464 << "Switch instruction is not predictable.";
465 });
466 }
467 }
468
469 virtual ~MainSwitch() = default;
470
471 SwitchInst *getInstr() const { return Instr; }
472 const SmallVector<SelectInstToUnfold, 4> getSelectInsts() {
473 return SelectInsts;
474 }
475
476private:
477 /// Do a use-def chain traversal starting from the switch condition to see if
478 /// \p SI is a potential condidate.
479 ///
480 /// Also, collect select instructions to unfold.
481 bool isCandidate(const SwitchInst *SI) {
482 std::deque<std::pair<Value *, BasicBlock *>> Q;
483 SmallPtrSet<Value *, 16> SeenValues;
484 SelectInsts.clear();
485
486 Value *SICond = SI->getCondition();
487 LLVM_DEBUG(dbgs() << "\tSICond: " << *SICond << "\n");
488 if (!isa<PHINode>(SICond))
489 return false;
490
491 // The switch must be in a loop.
492 const Loop *L = LI->getLoopFor(SI->getParent());
493 if (!L)
494 return false;
495
496 addToQueue(SICond, nullptr, Q, SeenValues);
497
498 while (!Q.empty()) {
499 Value *Current = Q.front().first;
500 BasicBlock *CurrentIncomingBB = Q.front().second;
501 Q.pop_front();
502
503 if (auto *Phi = dyn_cast<PHINode>(Current)) {
504 for (BasicBlock *IncomingBB : Phi->blocks()) {
505 Value *Incoming = Phi->getIncomingValueForBlock(IncomingBB);
506 addToQueue(Incoming, IncomingBB, Q, SeenValues);
507 }
508 LLVM_DEBUG(dbgs() << "\tphi: " << *Phi << "\n");
509 } else if (SelectInst *SelI = dyn_cast<SelectInst>(Current)) {
510 if (!isValidSelectInst(SelI))
511 return false;
512 addToQueue(SelI->getTrueValue(), CurrentIncomingBB, Q, SeenValues);
513 addToQueue(SelI->getFalseValue(), CurrentIncomingBB, Q, SeenValues);
514 LLVM_DEBUG(dbgs() << "\tselect: " << *SelI << "\n");
515 if (auto *SelIUse = dyn_cast<PHINode>(SelI->user_back()))
516 SelectInsts.push_back(SelectInstToUnfold(SelI, SelIUse));
517 } else if (isa<Constant>(Current)) {
518 LLVM_DEBUG(dbgs() << "\tconst: " << *Current << "\n");
519 continue;
520 } else {
521 LLVM_DEBUG(dbgs() << "\tother: " << *Current << "\n");
522 // Allow unpredictable values. The hope is that those will be the
523 // initial switch values that can be ignored (they will hit the
524 // unthreaded switch) but this assumption will get checked later after
525 // paths have been enumerated (in function getStateDefMap).
526
527 // If the unpredictable value comes from the same inner loop it is
528 // likely that it will also be on the enumerated paths, causing us to
529 // exit after we have enumerated all the paths. This heuristic save
530 // compile time because a search for all the paths can become expensive.
531 if (EarlyExitHeuristic &&
532 L->contains(LI->getLoopFor(CurrentIncomingBB))) {
534 << "\tExiting early due to unpredictability heuristic.\n");
535 return false;
536 }
537
538 continue;
539 }
540 }
541
542 return true;
543 }
544
545 void addToQueue(Value *Val, BasicBlock *BB,
546 std::deque<std::pair<Value *, BasicBlock *>> &Q,
547 SmallPtrSet<Value *, 16> &SeenValues) {
548 if (SeenValues.insert(Val).second)
549 Q.push_back({Val, BB});
550 }
551
552 bool isValidSelectInst(SelectInst *SI) {
553 if (!SI->hasOneUse())
554 return false;
555
556 Instruction *SIUse = SI->user_back();
557 // The use of the select inst should be either a phi or another select.
558 if (!isa<PHINode, SelectInst>(SIUse))
559 return false;
560
561 BasicBlock *SIBB = SI->getParent();
562
563 // Currently, we can only expand select instructions in basic blocks with
564 // one successor.
565 UncondBrInst *SITerm = dyn_cast<UncondBrInst>(SIBB->getTerminator());
566 if (!SITerm)
567 return false;
568
569 // Only fold the select coming from directly where it is defined.
570 // TODO: We have dealt with the select coming indirectly now. This
571 // constraint can be relaxed.
572 PHINode *PHIUser = dyn_cast<PHINode>(SIUse);
573 if (PHIUser && PHIUser->getIncomingBlock(*SI->use_begin()) != SIBB)
574 return false;
575
576 // If select will not be sunk during unfolding, and it is in the same basic
577 // block as another state defining select, then cannot unfold both.
578 for (SelectInstToUnfold SIToUnfold : SelectInsts) {
579 SelectInst *PrevSI = SIToUnfold.getInst();
580 if (PrevSI->getTrueValue() != SI && PrevSI->getFalseValue() != SI &&
581 PrevSI->getParent() == SI->getParent())
582 return false;
583 }
584
585 return true;
586 }
587
588 LoopInfo *LI;
589 SwitchInst *Instr = nullptr;
591};
592
593struct AllSwitchPaths {
594 AllSwitchPaths(const MainSwitch *MSwitch, OptimizationRemarkEmitter *ORE,
595 LoopInfo *LI, Loop *L)
596 : Switch(MSwitch->getInstr()), SwitchBlock(Switch->getParent()), ORE(ORE),
597 LI(LI), SwitchOuterLoop(L) {}
598
599 std::vector<ThreadingPath> &getThreadingPaths() { return TPaths; }
600 unsigned getNumThreadingPaths() { return TPaths.size(); }
601 SwitchInst *getSwitchInst() { return Switch; }
602 BasicBlock *getSwitchBlock() { return SwitchBlock; }
603
604 void run() {
605 findTPaths();
606 unifyTPaths();
607 }
608
609private:
610 // Value: an instruction that defines a switch state;
611 // Key: the parent basic block of that instruction.
612 typedef DenseMap<const BasicBlock *, const PHINode *> StateDefMap;
613 std::vector<ThreadingPath> getPathsFromStateDefMap(StateDefMap &StateDef,
614 PHINode *Phi,
615 VisitedBlocks &VB,
616 unsigned PathsLimit) {
617 std::vector<ThreadingPath> Res;
618 auto *PhiBB = Phi->getParent();
619 VB.insert(PhiBB);
620
621 VisitedBlocks UniqueBlocks;
622 for (auto *IncomingBB : Phi->blocks()) {
623 if (Res.size() >= PathsLimit)
624 break;
625 if (!UniqueBlocks.insert(IncomingBB).second)
626 continue;
627 if (!SwitchOuterLoop->contains(IncomingBB))
628 continue;
629
630 Value *IncomingValue = Phi->getIncomingValueForBlock(IncomingBB);
631 // We found the determinator. This is the start of our path.
632 if (auto *C = dyn_cast<ConstantInt>(IncomingValue)) {
633 // SwitchBlock is the determinator, unsupported unless its also the def.
634 if (PhiBB == SwitchBlock &&
635 SwitchBlock != cast<PHINode>(Switch->getOperand(0))->getParent())
636 continue;
637 ThreadingPath NewPath;
638 NewPath.setDeterminator(PhiBB);
639 NewPath.setExitValue(C);
640 // Don't add SwitchBlock at the start, this is handled later.
641 if (IncomingBB != SwitchBlock) {
642 // Don't add a cycle to the path.
643 if (VB.contains(IncomingBB))
644 continue;
645 NewPath.push_back(IncomingBB);
646 }
647 NewPath.push_back(PhiBB);
648 Res.push_back(NewPath);
649 continue;
650 }
651 // Don't get into a cycle.
652 if (VB.contains(IncomingBB) || IncomingBB == SwitchBlock)
653 continue;
654 // Recurse up the PHI chain.
655 auto *IncomingPhi = dyn_cast<PHINode>(IncomingValue);
656 if (!IncomingPhi)
657 continue;
658 auto *IncomingPhiDefBB = IncomingPhi->getParent();
659 if (!StateDef.contains(IncomingPhiDefBB))
660 continue;
661
662 // Direct predecessor, just add to the path.
663 if (IncomingPhiDefBB == IncomingBB) {
664 assert(PathsLimit > Res.size());
665 std::vector<ThreadingPath> PredPaths = getPathsFromStateDefMap(
666 StateDef, IncomingPhi, VB, PathsLimit - Res.size());
667 for (ThreadingPath &Path : PredPaths) {
668 Path.push_back(PhiBB);
669 Res.push_back(std::move(Path));
670 }
671 continue;
672 }
673 // Not a direct predecessor, find intermediate paths to append to the
674 // existing path.
675 if (VB.contains(IncomingPhiDefBB))
676 continue;
677
678 PathsType IntermediatePaths;
679 assert(PathsLimit > Res.size());
680 auto InterPathLimit = PathsLimit - Res.size();
681 IntermediatePaths = paths(IncomingPhiDefBB, IncomingBB, VB,
682 /* PathDepth = */ 1, InterPathLimit);
683 if (IntermediatePaths.empty())
684 continue;
685
686 assert(InterPathLimit >= IntermediatePaths.size());
687 auto PredPathLimit = InterPathLimit / IntermediatePaths.size();
688 std::vector<ThreadingPath> PredPaths =
689 getPathsFromStateDefMap(StateDef, IncomingPhi, VB, PredPathLimit);
690 for (const ThreadingPath &Path : PredPaths) {
691 for (const PathType &IPath : IntermediatePaths) {
692 ThreadingPath NewPath(Path);
693 NewPath.appendExcludingFirst(IPath);
694 NewPath.push_back(PhiBB);
695 Res.push_back(NewPath);
696 }
697 }
698 }
699 VB.erase(PhiBB);
700 return Res;
701 }
702
703 PathsType paths(BasicBlock *BB, BasicBlock *ToBB, VisitedBlocks &Visited,
704 unsigned PathDepth, unsigned PathsLimit) {
705 PathsType Res;
706
707 // Stop exploring paths after visiting MaxPathLength blocks
708 if (PathDepth > MaxPathLength) {
709 ORE->emit([&]() {
710 return OptimizationRemarkAnalysis(DEBUG_TYPE, "MaxPathLengthReached",
711 Switch)
712 << "Exploration stopped after visiting MaxPathLength="
713 << ore::NV("MaxPathLength", MaxPathLength) << " blocks.";
714 });
715 return Res;
716 }
717
718 Visited.insert(BB);
719 if (++NumVisited > MaxNumVisitiedPaths)
720 return Res;
721
722 // Stop if we have reached the BB out of loop, since its successors have no
723 // impact on the DFA.
724 if (!SwitchOuterLoop->contains(BB))
725 return Res;
726
727 // Some blocks have multiple edges to the same successor, and this set
728 // is used to prevent a duplicate path from being generated
729 SmallPtrSet<BasicBlock *, 4> Successors;
730 for (BasicBlock *Succ : successors(BB)) {
731 if (Res.size() >= PathsLimit)
732 break;
733 if (!Successors.insert(Succ).second)
734 continue;
735
736 // Found a cycle through the final block.
737 if (Succ == ToBB) {
738 Res.push_back({BB, ToBB});
739 continue;
740 }
741
742 // We have encountered a cycle, do not get caught in it
743 if (Visited.contains(Succ))
744 continue;
745
746 auto *CurrLoop = LI->getLoopFor(BB);
747 // Unlikely to be beneficial.
748 if (Succ == CurrLoop->getHeader())
749 continue;
750 // Skip for now, revisit this condition later to see the impact on
751 // coverage and compile time.
752 if (LI->getLoopFor(Succ) != CurrLoop)
753 continue;
754 assert(PathsLimit > Res.size());
755 PathsType SuccPaths =
756 paths(Succ, ToBB, Visited, PathDepth + 1, PathsLimit - Res.size());
757 for (PathType &Path : SuccPaths) {
758 Path.push_front(BB);
759 Res.push_back(Path);
760 }
761 }
762 // This block could now be visited again from a different predecessor. Note
763 // that this will result in exponential runtime. Subpaths could possibly be
764 // cached but it takes a lot of memory to store them.
765 Visited.erase(BB);
766 return Res;
767 }
768
769 /// Walk the use-def chain and collect all the state-defining blocks and the
770 /// PHI nodes in those blocks that define the state.
771 StateDefMap getStateDefMap() const {
772 StateDefMap Res;
773 DenseSet<const BasicBlock *> MultipleDefBBs;
774 PHINode *FirstDef = dyn_cast<PHINode>(Switch->getOperand(0));
775 assert(FirstDef && "The first definition must be a phi.");
776
778 Stack.push_back(FirstDef);
779 SmallPtrSet<Value *, 16> SeenValues;
780
781 while (!Stack.empty()) {
782 PHINode *CurPhi = Stack.pop_back_val();
783 BasicBlock *CurDefBlock = CurPhi->getParent();
784
785 auto [_, Inserted] = Res.try_emplace(CurDefBlock, CurPhi);
786 if (!Inserted)
787 MultipleDefBBs.insert(CurDefBlock);
788
789 SeenValues.insert(CurPhi);
790
791 for (BasicBlock *IncomingBB : CurPhi->blocks()) {
792 PHINode *IncomingPhi =
793 dyn_cast<PHINode>(CurPhi->getIncomingValueForBlock(IncomingBB));
794 if (!IncomingPhi)
795 continue;
796 bool IsOutsideLoops = !SwitchOuterLoop->contains(IncomingBB);
797 if (SeenValues.contains(IncomingPhi) || IsOutsideLoops)
798 continue;
799
800 Stack.push_back(IncomingPhi);
801 }
802 }
803
804 // NOTE: If multiple phi definitions exist in a block, we cannot
805 // thread the paths with such block by simple cloning. For example:
806 // < then, det, lbl_entry, switch_bb > [ 0, det ]
807 // < then, det, switch_bb > [ 1, det ]
808 // In this case, it is impossible to diverge then->det into then->det.0 and
809 // then->det.1 by simple path cloning.
810 for (auto *BB : MultipleDefBBs) {
811 LLVM_DEBUG(dbgs() << "Not a state-defining block: Multiple defs in "
812 << BB->getNameOrAsOperand() << "\n");
813 Res.erase(BB);
814 }
815 return Res;
816 }
817
818 // Find all threadable paths.
819 void findTPaths() {
820 StateDefMap StateDef = getStateDefMap();
821 if (StateDef.empty()) {
822 ORE->emit([&]() {
823 return OptimizationRemarkMissed(DEBUG_TYPE, "SwitchNotPredictable",
824 Switch)
825 << "Switch instruction is not predictable.";
826 });
827 return;
828 }
829
830 auto *SwitchPhi = cast<PHINode>(Switch->getOperand(0));
831 auto *SwitchPhiDefBB = SwitchPhi->getParent();
832 VisitedBlocks VB;
833 // Get paths from the determinator BBs to SwitchPhiDefBB
834 std::vector<ThreadingPath> PathsToPhiDef =
835 getPathsFromStateDefMap(StateDef, SwitchPhi, VB, MaxNumPaths);
836 if (SwitchPhiDefBB == SwitchBlock || PathsToPhiDef.empty()) {
837 TPaths = std::move(PathsToPhiDef);
838 return;
839 }
840
841 assert(MaxNumPaths >= PathsToPhiDef.size() && !PathsToPhiDef.empty());
842 auto PathsLimit = MaxNumPaths / PathsToPhiDef.size();
843 // Find and append paths from SwitchPhiDefBB to SwitchBlock.
844 PathsType PathsToSwitchBB =
845 paths(SwitchPhiDefBB, SwitchBlock, VB, /* PathDepth = */ 1, PathsLimit);
846 if (PathsToSwitchBB.empty())
847 return;
848
849 std::vector<ThreadingPath> TempList;
850 for (const ThreadingPath &Path : PathsToPhiDef) {
851 SmallPtrSet<BasicBlock *, 32> PathSet(Path.getPath().begin(),
852 Path.getPath().end());
853 for (const PathType &PathToSw : PathsToSwitchBB) {
854 if (any_of(llvm::drop_begin(PathToSw),
855 [&](const BasicBlock *BB) { return PathSet.contains(BB); }))
856 continue;
857 ThreadingPath PathCopy(Path);
858 PathCopy.appendExcludingFirst(PathToSw);
859 TempList.push_back(PathCopy);
860 }
861 }
862 TPaths = std::move(TempList);
863 }
864
865 /// Fast helper to get the successor corresponding to a particular case value
866 /// for a switch statement.
867 BasicBlock *getNextCaseSuccessor(const APInt &NextState) {
868 // Precompute the value => successor mapping
869 if (CaseValToDest.empty()) {
870 for (auto Case : Switch->cases()) {
871 APInt CaseVal = Case.getCaseValue()->getValue();
872 CaseValToDest[CaseVal] = Case.getCaseSuccessor();
873 }
874 }
875
876 auto SuccIt = CaseValToDest.find(NextState);
877 return SuccIt == CaseValToDest.end() ? Switch->getDefaultDest()
878 : SuccIt->second;
879 }
880
881 // Two states are equivalent if they have the same switch destination.
882 // Unify the states in different threading path if the states are equivalent.
883 void unifyTPaths() {
884 SmallDenseMap<BasicBlock *, APInt> DestToState;
885 for (ThreadingPath &Path : TPaths) {
886 APInt NextState = Path.getExitValue();
887 BasicBlock *Dest = getNextCaseSuccessor(NextState);
888 auto [StateIt, Inserted] = DestToState.try_emplace(Dest, NextState);
889 if (Inserted)
890 continue;
891 if (NextState != StateIt->second) {
892 LLVM_DEBUG(dbgs() << "Next state in " << Path << " is equivalent to "
893 << StateIt->second << "\n");
894 Path.setExitValue(StateIt->second);
895 }
896 }
897 }
898
899 unsigned NumVisited = 0;
900 SwitchInst *Switch;
901 BasicBlock *SwitchBlock;
902 OptimizationRemarkEmitter *ORE;
903 std::vector<ThreadingPath> TPaths;
904 DenseMap<APInt, BasicBlock *> CaseValToDest;
905 LoopInfo *LI;
906 Loop *SwitchOuterLoop;
907};
908
909struct TransformDFA {
910 TransformDFA(AllSwitchPaths *SwitchPaths, DomTreeUpdater *DTU,
911 AssumptionCache *AC, TargetTransformInfo *TTI,
912 OptimizationRemarkEmitter *ORE,
913 SmallPtrSet<const Value *, 32> EphValues)
914 : SwitchPaths(SwitchPaths), DTU(DTU), AC(AC), TTI(TTI), ORE(ORE),
915 EphValues(EphValues) {}
916
917 bool run() {
918 if (isLegalAndProfitableToTransform()) {
919 createAllExitPaths();
920 NumTransforms++;
921 return true;
922 }
923 return false;
924 }
925
926private:
927 /// This function performs both a legality check and profitability check at
928 /// the same time since it is convenient to do so. It iterates through all
929 /// blocks that will be cloned, and keeps track of the duplication cost. It
930 /// also returns false if it is illegal to clone some required block.
931 bool isLegalAndProfitableToTransform() {
932 CodeMetrics Metrics;
933 uint64_t NumClonedInst = 0;
934 SwitchInst *Switch = SwitchPaths->getSwitchInst();
935
936 // Don't thread switch without multiple successors.
937 if (Switch->getNumSuccessors() <= 1)
938 return false;
939
940 // Note that DuplicateBlockMap is not being used as intended here. It is
941 // just being used to ensure (BB, State) pairs are only counted once.
942 DuplicateBlockMap DuplicateMap;
943 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
944 PathType PathBBs = TPath.getPath();
945 APInt NextState = TPath.getExitValue();
946 const BasicBlock *Determinator = TPath.getDeterminatorBB();
947
948 // Update Metrics for the Switch block, this is always cloned
949 BasicBlock *BB = SwitchPaths->getSwitchBlock();
950 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
951 if (!VisitedBB) {
952 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
953 NumClonedInst += BB->size();
954 DuplicateMap[BB].push_back({BB, NextState});
955 }
956
957 // If the Switch block is the Determinator, then we can continue since
958 // this is the only block that is cloned and we already counted for it.
959 if (PathBBs.front() == Determinator)
960 continue;
961
962 // Otherwise update Metrics for all blocks that will be cloned. If any
963 // block is already cloned and would be reused, don't double count it.
964 auto DetIt = llvm::find(PathBBs, Determinator);
965 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
966 BB = *BBIt;
967 VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
968 if (VisitedBB)
969 continue;
970 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
971 NumClonedInst += BB->size();
972 DuplicateMap[BB].push_back({BB, NextState});
973 }
974
975 if (Metrics.notDuplicatable) {
976 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
977 << "non-duplicatable instructions.\n");
978 ORE->emit([&]() {
979 return OptimizationRemarkMissed(DEBUG_TYPE, "NonDuplicatableInst",
980 Switch)
981 << "Contains non-duplicatable instructions.";
982 });
983 return false;
984 }
985
986 // FIXME: Allow jump threading with controlled convergence.
987 if (Metrics.Convergence != ConvergenceKind::None) {
988 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
989 << "convergent instructions.\n");
990 ORE->emit([&]() {
991 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch)
992 << "Contains convergent instructions.";
993 });
994 return false;
995 }
996
997 if (!Metrics.NumInsts.isValid()) {
998 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
999 << "instructions with invalid cost.\n");
1000 ORE->emit([&]() {
1001 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch)
1002 << "Contains instructions with invalid cost.";
1003 });
1004 return false;
1005 }
1006 }
1007
1008 // Too much cloned instructions slow down later optimizations, especially
1009 // SLPVectorizer.
1010 // TODO: Thread the switch partially before reaching the threshold.
1011 uint64_t NumOrigInst = 0;
1012 uint64_t NumOuterUseBlock = 0;
1013 for (auto *BB : DuplicateMap.keys()) {
1014 NumOrigInst += BB->size();
1015 // Only unduplicated blocks with single predecessor require new phi
1016 // nodes.
1017 for (auto *Succ : successors(BB))
1018 if (!DuplicateMap.count(Succ) && Succ->getSinglePredecessor())
1019 NumOuterUseBlock++;
1020 }
1021
1022 if (double(NumClonedInst) / double(NumOrigInst) > MaxClonedRate) {
1023 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, too much "
1024 "instructions wll be cloned\n");
1025 ORE->emit([&]() {
1026 return OptimizationRemarkMissed(DEBUG_TYPE, "NotProfitable", Switch)
1027 << "Too much instructions will be cloned.";
1028 });
1029 return false;
1030 }
1031
1032 // Too much unduplicated blocks with outer uses may cause too much
1033 // insertions of phi nodes for duplicated definitions. TODO: Drop this
1034 // threshold if we come up with another way to reduce the number of inserted
1035 // phi nodes.
1036 if (NumOuterUseBlock > MaxOuterUseBlocks) {
1037 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, too much "
1038 "blocks with outer uses\n");
1039 ORE->emit([&]() {
1040 return OptimizationRemarkMissed(DEBUG_TYPE, "NotProfitable", Switch)
1041 << "Too much blocks with outer uses.";
1042 });
1043 return false;
1044 }
1045
1046 InstructionCost DuplicationCost = 0;
1047
1048 unsigned JumpTableSize = 0;
1049 TTI->getEstimatedNumberOfCaseClusters(*Switch, JumpTableSize, nullptr,
1050 nullptr);
1051 if (JumpTableSize == 0) {
1052 // Factor in the number of conditional branches reduced from jump
1053 // threading. Assume that lowering the switch block is implemented by
1054 // using binary search, hence the LogBase2().
1055 unsigned CondBranches =
1056 APInt(32, Switch->getNumSuccessors()).ceilLogBase2();
1057 assert(CondBranches > 0 &&
1058 "The threaded switch must have multiple branches");
1059 DuplicationCost = Metrics.NumInsts / CondBranches;
1060 } else {
1061 // Compared with jump tables, the DFA optimizer removes an indirect branch
1062 // on each loop iteration, thus making branch prediction more precise. The
1063 // more branch targets there are, the more likely it is for the branch
1064 // predictor to make a mistake, and the more benefit there is in the DFA
1065 // optimizer. Thus, the more branch targets there are, the lower is the
1066 // cost of the DFA opt.
1067 DuplicationCost = Metrics.NumInsts / JumpTableSize;
1068 }
1069
1070 LLVM_DEBUG(dbgs() << "\nDFA Jump Threading: Cost to jump thread block "
1071 << SwitchPaths->getSwitchBlock()->getName()
1072 << " is: " << DuplicationCost << "\n\n");
1073
1074 if (DuplicationCost > CostThreshold) {
1075 LLVM_DEBUG(dbgs() << "Not jump threading, duplication cost exceeds the "
1076 << "cost threshold.\n");
1077 ORE->emit([&]() {
1078 return OptimizationRemarkMissed(DEBUG_TYPE, "NotProfitable", Switch)
1079 << "Duplication cost exceeds the cost threshold (cost="
1080 << ore::NV("Cost", DuplicationCost)
1081 << ", threshold=" << ore::NV("Threshold", CostThreshold) << ").";
1082 });
1083 return false;
1084 }
1085
1086 ORE->emit([&]() {
1087 return OptimizationRemark(DEBUG_TYPE, "JumpThreaded", Switch)
1088 << "Switch statement jump-threaded.";
1089 });
1090
1091 return true;
1092 }
1093
1094 /// Transform each threading path to effectively jump thread the DFA.
1095 void createAllExitPaths() {
1096 // Move the switch block to the end of the path, since it will be duplicated
1097 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock();
1098 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
1099 LLVM_DEBUG(dbgs() << TPath << "\n");
1100 // TODO: Fix exit path creation logic so that we dont need this
1101 // placeholder.
1102 TPath.push_front(SwitchBlock);
1103 }
1104
1105 // Transform the ThreadingPaths and keep track of the cloned values
1106 DuplicateBlockMap DuplicateMap;
1107 DefMap NewDefs;
1108
1109 SmallPtrSet<BasicBlock *, 16> BlocksToClean;
1110 BlocksToClean.insert_range(successors(SwitchBlock));
1111
1112 for (const ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
1113 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, DTU);
1114 NumPaths++;
1115 }
1116
1117 // After all paths are cloned, now update the last successor of the cloned
1118 // path so it skips over the switch statement
1119 for (const ThreadingPath &TPath : SwitchPaths->getThreadingPaths())
1120 updateLastSuccessor(TPath, DuplicateMap, DTU);
1121
1122 // For each instruction that was cloned and used outside, update its uses
1123 updateSSA(NewDefs);
1124
1125 // Clean PHI Nodes for the newly created blocks
1126 for (BasicBlock *BB : BlocksToClean)
1127 cleanPhiNodes(BB);
1128 }
1129
1130 /// For a specific ThreadingPath \p Path, create an exit path starting from
1131 /// the determinator block.
1132 ///
1133 /// To remember the correct destination, we have to duplicate blocks
1134 /// corresponding to each state. Also update the terminating instruction of
1135 /// the predecessors, and phis in the successor blocks.
1136 void createExitPath(DefMap &NewDefs, const ThreadingPath &Path,
1137 DuplicateBlockMap &DuplicateMap,
1138 SmallPtrSet<BasicBlock *, 16> &BlocksToClean,
1139 DomTreeUpdater *DTU) {
1140 APInt NextState = Path.getExitValue();
1141 const BasicBlock *Determinator = Path.getDeterminatorBB();
1142 PathType PathBBs = Path.getPath();
1143
1144 // Don't select the placeholder block in front
1145 if (PathBBs.front() == Determinator)
1146 PathBBs.pop_front();
1147
1148 auto DetIt = llvm::find(PathBBs, Determinator);
1149 // When there is only one BB in PathBBs, the determinator takes itself as a
1150 // direct predecessor.
1151 BasicBlock *PrevBB = PathBBs.size() == 1 ? *DetIt : *std::prev(DetIt);
1152 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
1153 BasicBlock *BB = *BBIt;
1154 BlocksToClean.insert(BB);
1155
1156 // We already cloned BB for this NextState, now just update the branch
1157 // and continue.
1158 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap);
1159 if (NextBB) {
1160 updatePredecessor(PrevBB, BB, NextBB, DTU);
1161 PrevBB = NextBB;
1162 continue;
1163 }
1164
1165 // Clone the BB and update the successor of Prev to jump to the new block
1166 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor(
1167 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU);
1168 DuplicateMap[BB].push_back({NewBB, NextState});
1169 BlocksToClean.insert(NewBB);
1170 PrevBB = NewBB;
1171 }
1172 }
1173
1174 /// Restore SSA form after cloning blocks.
1175 ///
1176 /// Each cloned block creates new defs for a variable, and the uses need to be
1177 /// updated to reflect this. The uses may be replaced with a cloned value, or
1178 /// some derived phi instruction. Note that all uses of a value defined in the
1179 /// same block were already remapped when cloning the block.
1180 void updateSSA(DefMap &NewDefs) {
1181 SSAUpdaterBulk SSAUpdate;
1182 SmallVector<Use *, 16> UsesToRename;
1183
1184 for (const auto &KV : NewDefs) {
1185 Instruction *I = KV.first;
1186 BasicBlock *BB = I->getParent();
1187 std::vector<Instruction *> Cloned = KV.second;
1188
1189 // Scan all uses of this instruction to see if it is used outside of its
1190 // block, and if so, record them in UsesToRename.
1191 for (Use &U : I->uses()) {
1192 Instruction *User = cast<Instruction>(U.getUser());
1193 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1194 if (UserPN->getIncomingBlock(U) == BB)
1195 continue;
1196 } else if (User->getParent() == BB) {
1197 continue;
1198 }
1199
1200 UsesToRename.push_back(&U);
1201 }
1202
1203 // If there are no uses outside the block, we're done with this
1204 // instruction.
1205 if (UsesToRename.empty())
1206 continue;
1207 LLVM_DEBUG(dbgs() << "DFA-JT: Renaming non-local uses of: " << *I
1208 << "\n");
1209
1210 // We found a use of I outside of BB. Rename all uses of I that are
1211 // outside its block to be uses of the appropriate PHI node etc. See
1212 // ValuesInBlocks with the values we know.
1213 unsigned VarNum = SSAUpdate.AddVariable(I->getName(), I->getType());
1214 SSAUpdate.AddAvailableValue(VarNum, BB, I);
1215 for (Instruction *New : Cloned)
1216 SSAUpdate.AddAvailableValue(VarNum, New->getParent(), New);
1217
1218 while (!UsesToRename.empty())
1219 SSAUpdate.AddUse(VarNum, UsesToRename.pop_back_val());
1220
1221 LLVM_DEBUG(dbgs() << "\n");
1222 }
1223 // SSAUpdater handles phi placement and renaming uses with the appropriate
1224 // value.
1225 SSAUpdate.RewriteAllUses(&DTU->getDomTree());
1226 }
1227
1228 /// Helper to get the successor corresponding to a particular case value for
1229 /// a switch statement.
1230 /// TODO: Unify it with SwitchPaths->getNextCaseSuccessor(SwitchInst *Switch)
1231 /// by updating cached value => successor mapping during threading.
1232 static BasicBlock *getNextCaseSuccessor(SwitchInst *Switch,
1233 const APInt &NextState) {
1234 BasicBlock *NextCase = nullptr;
1235 for (auto Case : Switch->cases()) {
1236 if (Case.getCaseValue()->getValue() == NextState) {
1237 NextCase = Case.getCaseSuccessor();
1238 break;
1239 }
1240 }
1241 if (!NextCase)
1242 NextCase = Switch->getDefaultDest();
1243 return NextCase;
1244 }
1245
1246 /// Clones a basic block, and adds it to the CFG.
1247 ///
1248 /// This function also includes updating phi nodes in the successors of the
1249 /// BB, and remapping uses that were defined locally in the cloned BB.
1250 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB,
1251 const APInt &NextState,
1252 DuplicateBlockMap &DuplicateMap,
1253 DefMap &NewDefs,
1254 DomTreeUpdater *DTU) {
1255 ValueToValueMapTy VMap;
1256 BasicBlock *NewBB = CloneBasicBlock(
1257 BB, VMap, ".jt" + std::to_string(NextState.getLimitedValue()),
1258 BB->getParent());
1259 NewBB->moveAfter(BB);
1260 NumCloned++;
1261
1262 // Give the clone fresh noalias scopes; otherwise it shares BB's scopes and
1263 // AA can treat aliasing accesses on different threaded paths as noalias.
1264 SmallVector<MDNode *> NoAliasScopes;
1265 identifyNoAliasScopesToClone({NewBB}, NoAliasScopes);
1266 cloneAndAdaptNoAliasScopes(NoAliasScopes, {NewBB}, BB->getContext(), "dfa");
1267
1268 for (Instruction &I : *NewBB) {
1269 // Do not remap operands of PHINode in case a definition in BB is an
1270 // incoming value to a phi in the same block. This incoming value will
1271 // be renamed later while restoring SSA.
1272 if (isa<PHINode>(&I))
1273 continue;
1274 RemapInstruction(&I, VMap,
1276 if (AssumeInst *II = dyn_cast<AssumeInst>(&I))
1278 }
1279
1280 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap);
1281 updatePredecessor(PrevBB, BB, NewBB, DTU);
1282 updateDefMap(NewDefs, VMap);
1283
1284 // Add all successors to the DominatorTree
1285 SmallPtrSet<BasicBlock *, 4> SuccSet;
1286 for (auto *SuccBB : successors(NewBB)) {
1287 if (SuccSet.insert(SuccBB).second)
1288 DTU->applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}});
1289 }
1290 SuccSet.clear();
1291 return NewBB;
1292 }
1293
1294 /// Update the phi nodes in BB's successors.
1295 ///
1296 /// This means creating a new incoming value from NewBB with the new
1297 /// instruction wherever there is an incoming value from BB.
1298 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB,
1299 const APInt &NextState, ValueToValueMapTy &VMap,
1300 DuplicateBlockMap &DuplicateMap) {
1301 std::vector<BasicBlock *> BlocksToUpdate;
1302
1303 // If BB is the last block in the path, we can simply update the one case
1304 // successor that will be reached.
1305 if (BB == SwitchPaths->getSwitchBlock()) {
1306 SwitchInst *Switch = SwitchPaths->getSwitchInst();
1307 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1308 BlocksToUpdate.push_back(NextCase);
1309 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap);
1310 if (ClonedSucc)
1311 BlocksToUpdate.push_back(ClonedSucc);
1312 }
1313 // Otherwise update phis in all successors.
1314 else {
1315 for (BasicBlock *Succ : successors(BB)) {
1316 BlocksToUpdate.push_back(Succ);
1317
1318 // Check if a successor has already been cloned for the particular exit
1319 // value. In this case if a successor was already cloned, the phi nodes
1320 // in the cloned block should be updated directly.
1321 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap);
1322 if (ClonedSucc)
1323 BlocksToUpdate.push_back(ClonedSucc);
1324 }
1325 }
1326
1327 // If there is a phi with an incoming value from BB, create a new incoming
1328 // value for the new predecessor ClonedBB. The value will either be the same
1329 // value from BB or a cloned value.
1330 for (BasicBlock *Succ : BlocksToUpdate) {
1331 for (PHINode &Phi : Succ->phis()) {
1332 Value *Incoming = Phi.getIncomingValueForBlock(BB);
1333 if (Incoming) {
1334 if (isa<Constant>(Incoming)) {
1335 Phi.addIncoming(Incoming, ClonedBB);
1336 continue;
1337 }
1338 Value *ClonedVal = VMap[Incoming];
1339 if (ClonedVal)
1340 Phi.addIncoming(ClonedVal, ClonedBB);
1341 else
1342 Phi.addIncoming(Incoming, ClonedBB);
1343 }
1344 }
1345 }
1346 }
1347
1348 /// Sets the successor of PrevBB to be NewBB instead of OldBB. Note that all
1349 /// other successors are kept as well.
1350 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB,
1351 BasicBlock *NewBB, DomTreeUpdater *DTU) {
1352 // When a path is reused, there is a chance that predecessors were already
1353 // updated before. Check if the predecessor needs to be updated first.
1354 if (!isPredecessor(OldBB, PrevBB))
1355 return;
1356
1357 Instruction *PrevTerm = PrevBB->getTerminator();
1358 for (unsigned Idx = 0; Idx < PrevTerm->getNumSuccessors(); Idx++) {
1359 if (PrevTerm->getSuccessor(Idx) == OldBB) {
1360 OldBB->removePredecessor(PrevBB, /* KeepOneInputPHIs = */ true);
1361 PrevTerm->setSuccessor(Idx, NewBB);
1362 }
1363 }
1364 DTU->applyUpdates({{DominatorTree::Delete, PrevBB, OldBB},
1365 {DominatorTree::Insert, PrevBB, NewBB}});
1366 }
1367
1368 /// Add new value mappings to the DefMap to keep track of all new definitions
1369 /// for a particular instruction. These will be used while updating SSA form.
1370 void updateDefMap(DefMap &NewDefs, ValueToValueMapTy &VMap) {
1372 NewDefsVector.reserve(VMap.size());
1373
1374 for (auto Entry : VMap) {
1375 Instruction *Inst =
1376 dyn_cast<Instruction>(const_cast<Value *>(Entry.first));
1377 if (!Inst || !Entry.second ||
1379 continue;
1380
1381 Instruction *Cloned = dyn_cast<Instruction>(Entry.second);
1382 if (!Cloned)
1383 continue;
1384
1385 NewDefsVector.push_back({Inst, Cloned});
1386 }
1387
1388 // Sort the defs to get deterministic insertion order into NewDefs.
1389 sort(NewDefsVector, [](const auto &LHS, const auto &RHS) {
1390 if (LHS.first == RHS.first)
1391 return LHS.second->comesBefore(RHS.second);
1392 return LHS.first->comesBefore(RHS.first);
1393 });
1394
1395 for (const auto &KV : NewDefsVector)
1396 NewDefs[KV.first].push_back(KV.second);
1397 }
1398
1399 /// Update the last branch of a particular cloned path to point to the correct
1400 /// case successor.
1401 ///
1402 /// Note that this is an optional step and would have been done in later
1403 /// optimizations, but it makes the CFG significantly easier to work with.
1404 void updateLastSuccessor(const ThreadingPath &TPath,
1405 DuplicateBlockMap &DuplicateMap,
1406 DomTreeUpdater *DTU) {
1407 APInt NextState = TPath.getExitValue();
1408 BasicBlock *BB = TPath.getPath().back();
1409 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap);
1410
1411 // Note multiple paths can end at the same block so check that it is not
1412 // updated yet
1413 if (!isa<SwitchInst>(LastBlock->getTerminator()))
1414 return;
1415 SwitchInst *Switch = cast<SwitchInst>(LastBlock->getTerminator());
1416 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1417
1418 std::vector<DominatorTree::UpdateType> DTUpdates;
1419 SmallPtrSet<BasicBlock *, 4> SuccSet;
1420 for (BasicBlock *Succ : successors(LastBlock)) {
1421 if (Succ != NextCase && SuccSet.insert(Succ).second)
1422 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ});
1423 }
1424
1425 DebugLoc SwitchLoc = Switch->getDebugLoc();
1426 Switch->eraseFromParent();
1427 UncondBrInst::Create(NextCase, LastBlock)->setDebugLoc(SwitchLoc);
1428
1429 DTU->applyUpdates(DTUpdates);
1430 }
1431
1432 /// After cloning blocks, some of the phi nodes have extra incoming values
1433 /// that are no longer used. This function removes them.
1434 void cleanPhiNodes(BasicBlock *BB) {
1435 // If BB is no longer reachable, remove any remaining phi nodes
1436 if (pred_empty(BB)) {
1437 for (PHINode &PN : make_early_inc_range(BB->phis())) {
1438 PN.replaceAllUsesWith(PoisonValue::get(PN.getType()));
1439 PN.eraseFromParent();
1440 }
1441 return;
1442 }
1443
1444 // Remove any incoming values that come from an invalid predecessor
1445 for (PHINode &Phi : BB->phis())
1446 Phi.removeIncomingValueIf([&](unsigned Index) {
1447 BasicBlock *IncomingBB = Phi.getIncomingBlock(Index);
1448 return !isPredecessor(BB, IncomingBB);
1449 });
1450 }
1451
1452 /// Checks if BB was already cloned for a particular next state value. If it
1453 /// was then it returns this cloned block, and otherwise null.
1454 BasicBlock *getClonedBB(BasicBlock *BB, const APInt &NextState,
1455 DuplicateBlockMap &DuplicateMap) {
1456 CloneList ClonedBBs = DuplicateMap[BB];
1457
1458 // Find an entry in the CloneList with this NextState. If it exists then
1459 // return the corresponding BB
1460 auto It = llvm::find_if(ClonedBBs, [NextState](const ClonedBlock &C) {
1461 return C.State == NextState;
1462 });
1463 return It != ClonedBBs.end() ? (*It).BB : nullptr;
1464 }
1465
1466 /// Returns true if IncomingBB is a predecessor of BB.
1467 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) {
1468 return llvm::is_contained(predecessors(BB), IncomingBB);
1469 }
1470
1471 AllSwitchPaths *SwitchPaths;
1472 DomTreeUpdater *DTU;
1473 AssumptionCache *AC;
1474 TargetTransformInfo *TTI;
1475 OptimizationRemarkEmitter *ORE;
1476 SmallPtrSet<const Value *, 32> EphValues;
1477 std::vector<ThreadingPath> TPaths;
1478};
1479} // namespace
1480
1481bool DFAJumpThreading::run(Function &F) {
1482 LLVM_DEBUG(dbgs() << "\nDFA Jump threading: " << F.getName() << "\n");
1483
1484 if (F.hasOptSize()) {
1485 LLVM_DEBUG(dbgs() << "Skipping due to the 'minsize' attribute\n");
1486 return false;
1487 }
1488
1489 if (ClViewCfgBefore)
1490 F.viewCFG();
1491
1492 SmallVector<AllSwitchPaths, 2> ThreadableLoops;
1493 bool MadeChanges = false;
1494 LoopInfoBroken = false;
1495
1496 for (BasicBlock &BB : F) {
1498 if (!SI)
1499 continue;
1500
1501 LLVM_DEBUG(dbgs() << "\nCheck if SwitchInst in BB " << BB.getName()
1502 << " is a candidate\n");
1503 MainSwitch Switch(SI, LI, ORE);
1504
1505 if (!Switch.getInstr()) {
1506 LLVM_DEBUG(dbgs() << "\nSwitchInst in BB " << BB.getName() << " is not a "
1507 << "candidate for jump threading\n");
1508 continue;
1509 }
1510
1511 LLVM_DEBUG(dbgs() << "\nSwitchInst in BB " << BB.getName() << " is a "
1512 << "candidate for jump threading\n");
1513 LLVM_DEBUG(SI->dump());
1514
1515 unfoldSelectInstrs(Switch.getSelectInsts());
1516 if (!Switch.getSelectInsts().empty())
1517 MadeChanges = true;
1518
1519 AllSwitchPaths SwitchPaths(&Switch, ORE, LI,
1520 LI->getLoopFor(&BB)->getOutermostLoop());
1521 SwitchPaths.run();
1522
1523 if (SwitchPaths.getNumThreadingPaths() > 0) {
1524 ThreadableLoops.push_back(SwitchPaths);
1525
1526 // For the time being limit this optimization to occurring once in a
1527 // function since it can change the CFG significantly. This is not a
1528 // strict requirement but it can cause buggy behavior if there is an
1529 // overlap of blocks in different opportunities. There is a lot of room to
1530 // experiment with catching more opportunities here.
1531 // NOTE: To release this contraint, we must handle LoopInfo invalidation
1532 break;
1533 }
1534 }
1535
1536#ifdef NDEBUG
1537 LI->verify(DTU->getDomTree());
1538#endif
1539
1540 SmallPtrSet<const Value *, 32> EphValues;
1541 if (ThreadableLoops.size() > 0)
1542 CodeMetrics::collectEphemeralValues(&F, AC, EphValues);
1543
1544 for (AllSwitchPaths SwitchPaths : ThreadableLoops) {
1545 TransformDFA Transform(&SwitchPaths, DTU, AC, TTI, ORE, EphValues);
1546 if (Transform.run())
1547 MadeChanges = LoopInfoBroken = true;
1548 }
1549
1550 DTU->flush();
1551
1552#ifdef EXPENSIVE_CHECKS
1553 verifyFunction(F, &dbgs());
1554#endif
1555
1556 if (MadeChanges && VerifyDomInfo)
1557 assert(DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full) &&
1558 "Failed to maintain validity of domtree!");
1559
1560 return MadeChanges;
1561}
1562
1563/// Integrate with the new Pass Manager
1568 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
1571
1572 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1573 DFAJumpThreading ThreadImpl(&AC, &DTU, &LI, &TTI, &ORE);
1574 if (!ThreadImpl.run(F))
1575 return PreservedAnalyses::all();
1576
1579 if (!ThreadImpl.LoopInfoBroken)
1580 PA.preserve<LoopAnalysis>();
1581 return PA;
1582}
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
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:172
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
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:219
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.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
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:209
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:392
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
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:1765
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:2208
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
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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:1746
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
@ 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:1772
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:1947
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.