1 //===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Early if-conversion is for out-of-order CPUs that don't have a lot of
11 // predicable instructions. The goal is to eliminate conditional branches that
14 // Instructions from both sides of the branch are executed specutatively, and a
15 // cmov instruction selects the result.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "early-ifcvt"
20 #include "llvm/Function.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/PostOrderIterator.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SparseSet.h"
26 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
27 #include "llvm/CodeGen/MachineDominators.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
40 // Absolute maximum number of instructions allowed per speculated block.
41 // This bypasses all other heuristics, so it should be set fairly high.
42 static cl::opt<unsigned>
43 BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
44 cl::desc("Maximum number of instructions per speculated block."));
46 // Stress testing mode - disable heuristics.
47 static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
48 cl::desc("Turn all knobs to 11"));
50 typedef SmallSetVector<MachineBasicBlock*, 8> BlockSetVector;
52 //===----------------------------------------------------------------------===//
54 //===----------------------------------------------------------------------===//
56 // The SSAIfConv class performs if-conversion on SSA form machine code after
57 // determining if it is possible. The class contains no heuristics; external
58 // code should be used to determine when if-conversion is a good idea.
60 // SSAIfConv can convert both triangles and diamonds:
62 // Triangle: Head Diamond: Head
70 // Instructions in the conditional blocks TBB and/or FBB are spliced into the
71 // Head block, and phis in the Tail block are converted to select instructions.
75 const TargetInstrInfo *TII;
76 const TargetRegisterInfo *TRI;
77 MachineRegisterInfo *MRI;
80 /// The block containing the conditional branch.
81 MachineBasicBlock *Head;
83 /// The block containing phis after the if-then-else.
84 MachineBasicBlock *Tail;
86 /// The 'true' conditional block as determined by AnalyzeBranch.
87 MachineBasicBlock *TBB;
89 /// The 'false' conditional block as determined by AnalyzeBranch.
90 MachineBasicBlock *FBB;
92 /// isTriangle - When there is no 'else' block, either TBB or FBB will be
94 bool isTriangle() const { return TBB == Tail || FBB == Tail; }
96 /// Information about each phi in the Tail block.
100 // Latencies from Cond+Branch, TReg, and FReg to DstReg.
101 int CondCycles, TCycles, FCycles;
103 PHIInfo(MachineInstr *phi)
104 : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
107 SmallVector<PHIInfo, 8> PHIs;
110 /// The branch condition determined by AnalyzeBranch.
111 SmallVector<MachineOperand, 4> Cond;
113 /// Instructions in Head that define values used by the conditional blocks.
114 /// The hoisted instructions must be inserted after these instructions.
115 SmallPtrSet<MachineInstr*, 8> InsertAfter;
117 /// Register units clobbered by the conditional blocks.
118 BitVector ClobberedRegUnits;
120 // Scratch pad for findInsertionPoint.
121 SparseSet<unsigned> LiveRegUnits;
123 /// Insertion point in Head for speculatively executed instructions form TBB
125 MachineBasicBlock::iterator InsertionPoint;
127 /// Return true if all non-terminator instructions in MBB can be safely
129 bool canSpeculateInstrs(MachineBasicBlock *MBB);
131 /// Find a valid insertion point in Head.
132 bool findInsertionPoint();
135 /// runOnMachineFunction - Initialize per-function data structures.
136 void runOnMachineFunction(MachineFunction &MF) {
137 TII = MF.getTarget().getInstrInfo();
138 TRI = MF.getTarget().getRegisterInfo();
139 MRI = &MF.getRegInfo();
140 LiveRegUnits.clear();
141 LiveRegUnits.setUniverse(TRI->getNumRegUnits());
142 ClobberedRegUnits.clear();
143 ClobberedRegUnits.resize(TRI->getNumRegUnits());
146 /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
147 /// initialize the internal state, and return true.
148 bool canConvertIf(MachineBasicBlock *MBB);
150 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
151 /// it is possible. Add any erased blocks to RemovedBlocks.
152 void convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks);
154 } // end anonymous namespace
157 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
158 /// be speculated. The terminators are not considered.
160 /// If instructions use any values that are defined in the head basic block,
161 /// the defining instructions are added to InsertAfter.
163 /// Any clobbered regunits are added to ClobberedRegUnits.
165 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
166 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
168 if (!MBB->livein_empty()) {
169 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n");
173 unsigned InstrCount = 0;
175 // Check all instructions, except the terminators. It is assumed that
176 // terminators never have side effects or define any used register values.
177 for (MachineBasicBlock::iterator I = MBB->begin(),
178 E = MBB->getFirstTerminator(); I != E; ++I) {
179 if (I->isDebugValue())
182 if (++InstrCount > BlockInstrLimit && !Stress) {
183 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than "
184 << BlockInstrLimit << " instructions.\n");
188 // There shouldn't normally be any phis in a single-predecessor block.
190 DEBUG(dbgs() << "Can't hoist: " << *I);
194 // Don't speculate loads. Note that it may be possible and desirable to
195 // speculate GOT or constant pool loads that are guaranteed not to trap,
196 // but we don't support that for now.
198 DEBUG(dbgs() << "Won't speculate load: " << *I);
202 // We never speculate stores, so an AA pointer isn't necessary.
203 bool DontMoveAcrossStore = true;
204 if (!I->isSafeToMove(TII, 0, DontMoveAcrossStore)) {
205 DEBUG(dbgs() << "Can't speculate: " << *I);
209 // Check for any dependencies on Head instructions.
210 for (MIOperands MO(I); MO.isValid(); ++MO) {
211 if (MO->isRegMask()) {
212 DEBUG(dbgs() << "Won't speculate regmask: " << *I);
217 unsigned Reg = MO->getReg();
219 // Remember clobbered regunits.
220 if (MO->isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
221 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
222 ClobberedRegUnits.set(*Units);
224 if (!MO->readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
226 MachineInstr *DefMI = MRI->getVRegDef(Reg);
227 if (!DefMI || DefMI->getParent() != Head)
229 if (InsertAfter.insert(DefMI))
230 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " depends on " << *DefMI);
231 if (DefMI->isTerminator()) {
232 DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
241 /// Find an insertion point in Head for the speculated instructions. The
242 /// insertion point must be:
244 /// 1. Before any terminators.
245 /// 2. After any instructions in InsertAfter.
246 /// 3. Not have any clobbered regunits live.
248 /// This function sets InsertionPoint and returns true when successful, it
249 /// returns false if no valid insertion point could be found.
251 bool SSAIfConv::findInsertionPoint() {
252 // Keep track of live regunits before the current position.
253 // Only track RegUnits that are also in ClobberedRegUnits.
254 LiveRegUnits.clear();
255 SmallVector<unsigned, 8> Reads;
256 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
257 MachineBasicBlock::iterator I = Head->end();
258 MachineBasicBlock::iterator B = Head->begin();
261 // Some of the conditional code depends in I.
262 if (InsertAfter.count(I)) {
263 DEBUG(dbgs() << "Can't insert code after " << *I);
267 // Update live regunits.
268 for (MIOperands MO(I); MO.isValid(); ++MO) {
269 // We're ignoring regmask operands. That is conservatively correct.
272 unsigned Reg = MO->getReg();
273 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
275 // I clobbers Reg, so it isn't live before I.
277 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
278 LiveRegUnits.erase(*Units);
279 // Unless I reads Reg.
281 Reads.push_back(Reg);
283 // Anything read by I is live before I.
284 while (!Reads.empty())
285 for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
287 if (ClobberedRegUnits.test(*Units))
288 LiveRegUnits.insert(*Units);
290 // We can't insert before a terminator.
291 if (I != FirstTerm && I->isTerminator())
294 // Some of the clobbered registers are live before I, not a valid insertion
296 if (!LiveRegUnits.empty()) {
298 dbgs() << "Would clobber";
299 for (SparseSet<unsigned>::const_iterator
300 i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
301 dbgs() << ' ' << PrintRegUnit(*i, TRI);
302 dbgs() << " live before " << *I;
307 // This is a valid insertion point.
309 DEBUG(dbgs() << "Can insert before " << *I);
312 DEBUG(dbgs() << "No legal insertion point found.\n");
318 /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
319 /// a potential candidate for if-conversion. Fill out the internal state.
321 bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
323 TBB = FBB = Tail = 0;
325 if (Head->succ_size() != 2)
327 MachineBasicBlock *Succ0 = Head->succ_begin()[0];
328 MachineBasicBlock *Succ1 = Head->succ_begin()[1];
330 // Canonicalize so Succ0 has MBB as its single predecessor.
331 if (Succ0->pred_size() != 1)
332 std::swap(Succ0, Succ1);
334 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
337 // We could support additional Tail predecessors by updating phis instead of
338 // eliminating them. Let's see an example where it matters first.
339 Tail = Succ0->succ_begin()[0];
340 if (Tail->pred_size() != 2)
343 // This is not a triangle.
345 // Check for a diamond. We won't deal with any critical edges.
346 if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
347 Succ1->succ_begin()[0] != Tail)
349 DEBUG(dbgs() << "\nDiamond: BB#" << Head->getNumber()
350 << " -> BB#" << Succ0->getNumber()
351 << "/BB#" << Succ1->getNumber()
352 << " -> BB#" << Tail->getNumber() << '\n');
354 // Live-in physregs are tricky to get right when speculating code.
355 if (!Tail->livein_empty()) {
356 DEBUG(dbgs() << "Tail has live-ins.\n");
360 DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber()
361 << " -> BB#" << Succ0->getNumber()
362 << " -> BB#" << Tail->getNumber() << '\n');
365 // This is a triangle or a diamond.
366 // If Tail doesn't have any phis, there must be side effects.
367 if (Tail->empty() || !Tail->front().isPHI()) {
368 DEBUG(dbgs() << "No phis in tail.\n");
372 // The branch we're looking to eliminate must be analyzable.
374 if (TII->AnalyzeBranch(*Head, TBB, FBB, Cond)) {
375 DEBUG(dbgs() << "Branch not analyzable.\n");
379 // This is weird, probably some sort of degenerate CFG.
381 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
385 // AnalyzeBranch doesn't set FBB on a fall-through branch.
386 // Make sure it is always set.
387 FBB = TBB == Succ0 ? Succ1 : Succ0;
389 // Any phis in the tail block must be convertible to selects.
391 MachineBasicBlock *TPred = TBB == Tail ? Head : TBB;
392 MachineBasicBlock *FPred = FBB == Tail ? Head : FBB;
393 for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
394 I != E && I->isPHI(); ++I) {
396 PHIInfo &PI = PHIs.back();
397 // Find PHI operands corresponding to TPred and FPred.
398 for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
399 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
400 PI.TReg = PI.PHI->getOperand(i).getReg();
401 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
402 PI.FReg = PI.PHI->getOperand(i).getReg();
404 assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
405 assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
407 // Get target information.
408 if (!TII->canInsertSelect(*Head, Cond, PI.TReg, PI.FReg,
409 PI.CondCycles, PI.TCycles, PI.FCycles)) {
410 DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
415 // Check that the conditional instructions can be speculated.
417 ClobberedRegUnits.reset();
418 if (TBB != Tail && !canSpeculateInstrs(TBB))
420 if (FBB != Tail && !canSpeculateInstrs(FBB))
423 // Try to find a valid insertion point for the speculated instructions in the
425 if (!findInsertionPoint())
432 /// convertIf - Execute the if conversion after canConvertIf has determined the
435 /// Any basic blocks erased will be added to RemovedBlocks.
437 void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks) {
438 assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
440 // Move all instructions into Head, except for the terminators.
442 Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
444 Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
446 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
447 assert(FirstTerm != Head->end() && "No terminators");
448 DebugLoc HeadDL = FirstTerm->getDebugLoc();
450 // Convert all PHIs to select instructions inserted before FirstTerm.
451 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
452 PHIInfo &PI = PHIs[i];
453 DEBUG(dbgs() << "If-converting " << *PI.PHI);
454 assert(PI.PHI->getNumOperands() == 5 && "Unexpected PHI operands.");
455 unsigned DstReg = PI.PHI->getOperand(0).getReg();
456 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
457 DEBUG(dbgs() << " --> " << *llvm::prior(FirstTerm));
458 PI.PHI->eraseFromParent();
462 // Fix up the CFG, temporarily leave Head without any successors.
463 Head->removeSuccessor(TBB);
464 Head->removeSuccessor(FBB);
466 TBB->removeSuccessor(Tail);
468 FBB->removeSuccessor(Tail);
470 // Fix up Head's terminators.
471 // It should become a single branch or a fallthrough.
472 TII->RemoveBranch(*Head);
474 // Erase the now empty conditional blocks. It is likely that Head can fall
475 // through to Tail, and we can join the two blocks.
477 RemovedBlocks.push_back(TBB);
478 TBB->eraseFromParent();
481 RemovedBlocks.push_back(FBB);
482 FBB->eraseFromParent();
485 assert(Head->succ_empty() && "Additional head successors?");
486 if (Head->isLayoutSuccessor(Tail)) {
487 // Splice Tail onto the end of Head.
488 DEBUG(dbgs() << "Joining tail BB#" << Tail->getNumber()
489 << " into head BB#" << Head->getNumber() << '\n');
490 Head->splice(Head->end(), Tail,
491 Tail->begin(), Tail->end());
492 Head->transferSuccessorsAndUpdatePHIs(Tail);
493 RemovedBlocks.push_back(Tail);
494 Tail->eraseFromParent();
496 // We need a branch to Tail, let code placement work it out later.
497 DEBUG(dbgs() << "Converting to unconditional branch.\n");
498 SmallVector<MachineOperand, 0> EmptyCond;
499 TII->InsertBranch(*Head, Tail, 0, EmptyCond, HeadDL);
500 Head->addSuccessor(Tail);
502 DEBUG(dbgs() << *Head);
506 //===----------------------------------------------------------------------===//
507 // EarlyIfConverter Pass
508 //===----------------------------------------------------------------------===//
511 class EarlyIfConverter : public MachineFunctionPass {
512 const TargetInstrInfo *TII;
513 const TargetRegisterInfo *TRI;
514 MachineRegisterInfo *MRI;
515 MachineDominatorTree *DomTree;
520 EarlyIfConverter() : MachineFunctionPass(ID) {}
521 void getAnalysisUsage(AnalysisUsage &AU) const;
522 bool runOnMachineFunction(MachineFunction &MF);
525 bool tryConvertIf(MachineBasicBlock*);
526 void updateDomTree(ArrayRef<MachineBasicBlock*> Removed);
528 } // end anonymous namespace
530 char EarlyIfConverter::ID = 0;
531 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
533 INITIALIZE_PASS_BEGIN(EarlyIfConverter,
534 "early-ifcvt", "Early If Converter", false, false)
535 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
536 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
537 INITIALIZE_PASS_END(EarlyIfConverter,
538 "early-ifcvt", "Early If Converter", false, false)
540 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
541 AU.addRequired<MachineBranchProbabilityInfo>();
542 AU.addRequired<MachineDominatorTree>();
543 AU.addPreserved<MachineDominatorTree>();
544 MachineFunctionPass::getAnalysisUsage(AU);
547 /// Update the dominator tree after if-conversion erased some blocks.
548 void EarlyIfConverter::updateDomTree(ArrayRef<MachineBasicBlock*> Removed) {
549 // convertIf can remove TBB, FBB, and Tail can be merged into Head.
550 // TBB and FBB should not dominate any blocks.
551 // Tail children should be transferred to Head.
552 MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
553 for (unsigned i = 0, e = Removed.size(); i != e; ++i) {
554 MachineDomTreeNode *Node = DomTree->getNode(Removed[i]);
555 assert(Node != HeadNode && "Cannot erase the head node");
556 while (Node->getNumChildren()) {
557 assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
558 DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode);
560 DomTree->eraseNode(Removed[i]);
564 /// Attempt repeated if-conversion on MBB, return true if successful.
566 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
567 bool Changed = false;
568 while (IfConv.canConvertIf(MBB)) {
569 // If-convert MBB and update analyses.
570 SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
571 IfConv.convertIf(RemovedBlocks);
573 updateDomTree(RemovedBlocks);
578 bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
579 DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
580 << "********** Function: "
581 << ((Value*)MF.getFunction())->getName() << '\n');
582 TII = MF.getTarget().getInstrInfo();
583 TRI = MF.getTarget().getRegisterInfo();
584 MRI = &MF.getRegInfo();
585 DomTree = &getAnalysis<MachineDominatorTree>();
587 bool Changed = false;
588 IfConv.runOnMachineFunction(MF);
590 // Visit blocks in dominator tree post-order. The post-order enables nested
591 // if-conversion in a single pass. The tryConvertIf() function may erase
592 // blocks, but only blocks dominated by the head block. This makes it safe to
593 // update the dominator tree while the post-order iterator is still active.
594 for (po_iterator<MachineDominatorTree*>
595 I = po_begin(DomTree), E = po_end(DomTree); I != E; ++I)
596 if (tryConvertIf(I->getBlock()))
599 MF.verify(this, "After early if-conversion");