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