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/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
41 // Absolute maximum number of instructions allowed per speculated block.
42 // This bypasses all other heuristics, so it should be set fairly high.
43 static cl::opt<unsigned>
44 BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
45 cl::desc("Maximum number of instructions per speculated block."));
47 // Stress testing mode - disable heuristics.
48 static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
49 cl::desc("Turn all knobs to 11"));
51 typedef SmallSetVector<MachineBasicBlock*, 8> BlockSetVector;
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
57 // The SSAIfConv class performs if-conversion on SSA form machine code after
58 // determining if it is possible. The class contains no heuristics; external
59 // code should be used to determine when if-conversion is a good idea.
61 // SSAIfConv can convert both triangles and diamonds:
63 // Triangle: Head Diamond: Head
71 // Instructions in the conditional blocks TBB and/or FBB are spliced into the
72 // Head block, and phis in the Tail block are converted to select instructions.
76 const TargetInstrInfo *TII;
77 const TargetRegisterInfo *TRI;
78 MachineRegisterInfo *MRI;
81 /// The block containing the conditional branch.
82 MachineBasicBlock *Head;
84 /// The block containing phis after the if-then-else.
85 MachineBasicBlock *Tail;
87 /// The 'true' conditional block as determined by AnalyzeBranch.
88 MachineBasicBlock *TBB;
90 /// The 'false' conditional block as determined by AnalyzeBranch.
91 MachineBasicBlock *FBB;
93 /// isTriangle - When there is no 'else' block, either TBB or FBB will be
95 bool isTriangle() const { return TBB == Tail || FBB == Tail; }
97 /// Information about each phi in the Tail block.
101 // Latencies from Cond+Branch, TReg, and FReg to DstReg.
102 int CondCycles, TCycles, FCycles;
104 PHIInfo(MachineInstr *phi)
105 : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
108 SmallVector<PHIInfo, 8> PHIs;
111 /// The branch condition determined by AnalyzeBranch.
112 SmallVector<MachineOperand, 4> Cond;
114 /// Instructions in Head that define values used by the conditional blocks.
115 /// The hoisted instructions must be inserted after these instructions.
116 SmallPtrSet<MachineInstr*, 8> InsertAfter;
118 /// Register units clobbered by the conditional blocks.
119 BitVector ClobberedRegUnits;
121 // Scratch pad for findInsertionPoint.
122 SparseSet<unsigned> LiveRegUnits;
124 /// Insertion point in Head for speculatively executed instructions form TBB
126 MachineBasicBlock::iterator InsertionPoint;
128 /// Return true if all non-terminator instructions in MBB can be safely
130 bool canSpeculateInstrs(MachineBasicBlock *MBB);
132 /// Find a valid insertion point in Head.
133 bool findInsertionPoint();
136 /// runOnMachineFunction - Initialize per-function data structures.
137 void runOnMachineFunction(MachineFunction &MF) {
138 TII = MF.getTarget().getInstrInfo();
139 TRI = MF.getTarget().getRegisterInfo();
140 MRI = &MF.getRegInfo();
141 LiveRegUnits.clear();
142 LiveRegUnits.setUniverse(TRI->getNumRegUnits());
143 ClobberedRegUnits.clear();
144 ClobberedRegUnits.resize(TRI->getNumRegUnits());
147 /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
148 /// initialize the internal state, and return true.
149 bool canConvertIf(MachineBasicBlock *MBB);
151 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
152 /// it is possible. Add any erased blocks to RemovedBlocks.
153 void convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks);
155 } // end anonymous namespace
158 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
159 /// be speculated. The terminators are not considered.
161 /// If instructions use any values that are defined in the head basic block,
162 /// the defining instructions are added to InsertAfter.
164 /// Any clobbered regunits are added to ClobberedRegUnits.
166 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
167 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
169 if (!MBB->livein_empty()) {
170 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n");
174 unsigned InstrCount = 0;
176 // Check all instructions, except the terminators. It is assumed that
177 // terminators never have side effects or define any used register values.
178 for (MachineBasicBlock::iterator I = MBB->begin(),
179 E = MBB->getFirstTerminator(); I != E; ++I) {
180 if (I->isDebugValue())
183 if (++InstrCount > BlockInstrLimit && !Stress) {
184 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than "
185 << BlockInstrLimit << " instructions.\n");
189 // There shouldn't normally be any phis in a single-predecessor block.
191 DEBUG(dbgs() << "Can't hoist: " << *I);
195 // Don't speculate loads. Note that it may be possible and desirable to
196 // speculate GOT or constant pool loads that are guaranteed not to trap,
197 // but we don't support that for now.
199 DEBUG(dbgs() << "Won't speculate load: " << *I);
203 // We never speculate stores, so an AA pointer isn't necessary.
204 bool DontMoveAcrossStore = true;
205 if (!I->isSafeToMove(TII, 0, DontMoveAcrossStore)) {
206 DEBUG(dbgs() << "Can't speculate: " << *I);
210 // Check for any dependencies on Head instructions.
211 for (MIOperands MO(I); MO.isValid(); ++MO) {
212 if (MO->isRegMask()) {
213 DEBUG(dbgs() << "Won't speculate regmask: " << *I);
218 unsigned Reg = MO->getReg();
220 // Remember clobbered regunits.
221 if (MO->isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
222 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
223 ClobberedRegUnits.set(*Units);
225 if (!MO->readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
227 MachineInstr *DefMI = MRI->getVRegDef(Reg);
228 if (!DefMI || DefMI->getParent() != Head)
230 if (InsertAfter.insert(DefMI))
231 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " depends on " << *DefMI);
232 if (DefMI->isTerminator()) {
233 DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
242 /// Find an insertion point in Head for the speculated instructions. The
243 /// insertion point must be:
245 /// 1. Before any terminators.
246 /// 2. After any instructions in InsertAfter.
247 /// 3. Not have any clobbered regunits live.
249 /// This function sets InsertionPoint and returns true when successful, it
250 /// returns false if no valid insertion point could be found.
252 bool SSAIfConv::findInsertionPoint() {
253 // Keep track of live regunits before the current position.
254 // Only track RegUnits that are also in ClobberedRegUnits.
255 LiveRegUnits.clear();
256 SmallVector<unsigned, 8> Reads;
257 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
258 MachineBasicBlock::iterator I = Head->end();
259 MachineBasicBlock::iterator B = Head->begin();
262 // Some of the conditional code depends in I.
263 if (InsertAfter.count(I)) {
264 DEBUG(dbgs() << "Can't insert code after " << *I);
268 // Update live regunits.
269 for (MIOperands MO(I); MO.isValid(); ++MO) {
270 // We're ignoring regmask operands. That is conservatively correct.
273 unsigned Reg = MO->getReg();
274 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
276 // I clobbers Reg, so it isn't live before I.
278 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
279 LiveRegUnits.erase(*Units);
280 // Unless I reads Reg.
282 Reads.push_back(Reg);
284 // Anything read by I is live before I.
285 while (!Reads.empty())
286 for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
288 if (ClobberedRegUnits.test(*Units))
289 LiveRegUnits.insert(*Units);
291 // We can't insert before a terminator.
292 if (I != FirstTerm && I->isTerminator())
295 // Some of the clobbered registers are live before I, not a valid insertion
297 if (!LiveRegUnits.empty()) {
299 dbgs() << "Would clobber";
300 for (SparseSet<unsigned>::const_iterator
301 i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
302 dbgs() << ' ' << PrintRegUnit(*i, TRI);
303 dbgs() << " live before " << *I;
308 // This is a valid insertion point.
310 DEBUG(dbgs() << "Can insert before " << *I);
313 DEBUG(dbgs() << "No legal insertion point found.\n");
319 /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
320 /// a potential candidate for if-conversion. Fill out the internal state.
322 bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
324 TBB = FBB = Tail = 0;
326 if (Head->succ_size() != 2)
328 MachineBasicBlock *Succ0 = Head->succ_begin()[0];
329 MachineBasicBlock *Succ1 = Head->succ_begin()[1];
331 // Canonicalize so Succ0 has MBB as its single predecessor.
332 if (Succ0->pred_size() != 1)
333 std::swap(Succ0, Succ1);
335 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
338 // We could support additional Tail predecessors by updating phis instead of
339 // eliminating them. Let's see an example where it matters first.
340 Tail = Succ0->succ_begin()[0];
341 if (Tail->pred_size() != 2)
344 // This is not a triangle.
346 // Check for a diamond. We won't deal with any critical edges.
347 if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
348 Succ1->succ_begin()[0] != Tail)
350 DEBUG(dbgs() << "\nDiamond: BB#" << Head->getNumber()
351 << " -> BB#" << Succ0->getNumber()
352 << "/BB#" << Succ1->getNumber()
353 << " -> BB#" << Tail->getNumber() << '\n');
355 // Live-in physregs are tricky to get right when speculating code.
356 if (!Tail->livein_empty()) {
357 DEBUG(dbgs() << "Tail has live-ins.\n");
361 DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber()
362 << " -> BB#" << Succ0->getNumber()
363 << " -> BB#" << Tail->getNumber() << '\n');
366 // This is a triangle or a diamond.
367 // If Tail doesn't have any phis, there must be side effects.
368 if (Tail->empty() || !Tail->front().isPHI()) {
369 DEBUG(dbgs() << "No phis in tail.\n");
373 // The branch we're looking to eliminate must be analyzable.
375 if (TII->AnalyzeBranch(*Head, TBB, FBB, Cond)) {
376 DEBUG(dbgs() << "Branch not analyzable.\n");
380 // This is weird, probably some sort of degenerate CFG.
382 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
386 // AnalyzeBranch doesn't set FBB on a fall-through branch.
387 // Make sure it is always set.
388 FBB = TBB == Succ0 ? Succ1 : Succ0;
390 // Any phis in the tail block must be convertible to selects.
392 MachineBasicBlock *TPred = TBB == Tail ? Head : TBB;
393 MachineBasicBlock *FPred = FBB == Tail ? Head : FBB;
394 for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
395 I != E && I->isPHI(); ++I) {
397 PHIInfo &PI = PHIs.back();
398 // Find PHI operands corresponding to TPred and FPred.
399 for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
400 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
401 PI.TReg = PI.PHI->getOperand(i).getReg();
402 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
403 PI.FReg = PI.PHI->getOperand(i).getReg();
405 assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
406 assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
408 // Get target information.
409 if (!TII->canInsertSelect(*Head, Cond, PI.TReg, PI.FReg,
410 PI.CondCycles, PI.TCycles, PI.FCycles)) {
411 DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
416 // Check that the conditional instructions can be speculated.
418 ClobberedRegUnits.reset();
419 if (TBB != Tail && !canSpeculateInstrs(TBB))
421 if (FBB != Tail && !canSpeculateInstrs(FBB))
424 // Try to find a valid insertion point for the speculated instructions in the
426 if (!findInsertionPoint())
433 /// convertIf - Execute the if conversion after canConvertIf has determined the
436 /// Any basic blocks erased will be added to RemovedBlocks.
438 void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks) {
439 assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
441 // Move all instructions into Head, except for the terminators.
443 Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
445 Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
447 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
448 assert(FirstTerm != Head->end() && "No terminators");
449 DebugLoc HeadDL = FirstTerm->getDebugLoc();
451 // Convert all PHIs to select instructions inserted before FirstTerm.
452 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
453 PHIInfo &PI = PHIs[i];
454 DEBUG(dbgs() << "If-converting " << *PI.PHI);
455 assert(PI.PHI->getNumOperands() == 5 && "Unexpected PHI operands.");
456 unsigned DstReg = PI.PHI->getOperand(0).getReg();
457 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
458 DEBUG(dbgs() << " --> " << *llvm::prior(FirstTerm));
459 PI.PHI->eraseFromParent();
463 // Fix up the CFG, temporarily leave Head without any successors.
464 Head->removeSuccessor(TBB);
465 Head->removeSuccessor(FBB);
467 TBB->removeSuccessor(Tail);
469 FBB->removeSuccessor(Tail);
471 // Fix up Head's terminators.
472 // It should become a single branch or a fallthrough.
473 TII->RemoveBranch(*Head);
475 // Erase the now empty conditional blocks. It is likely that Head can fall
476 // through to Tail, and we can join the two blocks.
478 RemovedBlocks.push_back(TBB);
479 TBB->eraseFromParent();
482 RemovedBlocks.push_back(FBB);
483 FBB->eraseFromParent();
486 assert(Head->succ_empty() && "Additional head successors?");
487 if (Head->isLayoutSuccessor(Tail)) {
488 // Splice Tail onto the end of Head.
489 DEBUG(dbgs() << "Joining tail BB#" << Tail->getNumber()
490 << " into head BB#" << Head->getNumber() << '\n');
491 Head->splice(Head->end(), Tail,
492 Tail->begin(), Tail->end());
493 Head->transferSuccessorsAndUpdatePHIs(Tail);
494 RemovedBlocks.push_back(Tail);
495 Tail->eraseFromParent();
497 // We need a branch to Tail, let code placement work it out later.
498 DEBUG(dbgs() << "Converting to unconditional branch.\n");
499 SmallVector<MachineOperand, 0> EmptyCond;
500 TII->InsertBranch(*Head, Tail, 0, EmptyCond, HeadDL);
501 Head->addSuccessor(Tail);
503 DEBUG(dbgs() << *Head);
507 //===----------------------------------------------------------------------===//
508 // EarlyIfConverter Pass
509 //===----------------------------------------------------------------------===//
512 class EarlyIfConverter : public MachineFunctionPass {
513 const TargetInstrInfo *TII;
514 const TargetRegisterInfo *TRI;
515 MachineRegisterInfo *MRI;
516 MachineDominatorTree *DomTree;
517 MachineLoopInfo *Loops;
522 EarlyIfConverter() : MachineFunctionPass(ID) {}
523 void getAnalysisUsage(AnalysisUsage &AU) const;
524 bool runOnMachineFunction(MachineFunction &MF);
527 bool tryConvertIf(MachineBasicBlock*);
528 void updateDomTree(ArrayRef<MachineBasicBlock*> Removed);
529 void updateLoops(ArrayRef<MachineBasicBlock*> Removed);
531 } // end anonymous namespace
533 char EarlyIfConverter::ID = 0;
534 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
536 INITIALIZE_PASS_BEGIN(EarlyIfConverter,
537 "early-ifcvt", "Early If Converter", false, false)
538 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
539 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
540 INITIALIZE_PASS_END(EarlyIfConverter,
541 "early-ifcvt", "Early If Converter", false, false)
543 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
544 AU.addRequired<MachineBranchProbabilityInfo>();
545 AU.addRequired<MachineDominatorTree>();
546 AU.addPreserved<MachineDominatorTree>();
547 AU.addRequired<MachineLoopInfo>();
548 AU.addPreserved<MachineLoopInfo>();
549 MachineFunctionPass::getAnalysisUsage(AU);
552 /// Update the dominator tree after if-conversion erased some blocks.
553 void EarlyIfConverter::updateDomTree(ArrayRef<MachineBasicBlock*> Removed) {
554 // convertIf can remove TBB, FBB, and Tail can be merged into Head.
555 // TBB and FBB should not dominate any blocks.
556 // Tail children should be transferred to Head.
557 MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
558 for (unsigned i = 0, e = Removed.size(); i != e; ++i) {
559 MachineDomTreeNode *Node = DomTree->getNode(Removed[i]);
560 assert(Node != HeadNode && "Cannot erase the head node");
561 while (Node->getNumChildren()) {
562 assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
563 DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode);
565 DomTree->eraseNode(Removed[i]);
569 /// Update LoopInfo after if-conversion.
570 void EarlyIfConverter::updateLoops(ArrayRef<MachineBasicBlock*> Removed) {
573 // If-conversion doesn't change loop structure, and it doesn't mess with back
574 // edges, so updating LoopInfo is simply removing the dead blocks.
575 for (unsigned i = 0, e = Removed.size(); i != e; ++i)
576 Loops->removeBlock(Removed[i]);
579 /// Attempt repeated if-conversion on MBB, return true if successful.
581 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
582 bool Changed = false;
583 while (IfConv.canConvertIf(MBB)) {
584 // If-convert MBB and update analyses.
585 SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
586 IfConv.convertIf(RemovedBlocks);
588 updateDomTree(RemovedBlocks);
589 updateLoops(RemovedBlocks);
594 bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
595 DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
596 << "********** Function: "
597 << ((Value*)MF.getFunction())->getName() << '\n');
598 TII = MF.getTarget().getInstrInfo();
599 TRI = MF.getTarget().getRegisterInfo();
600 MRI = &MF.getRegInfo();
601 DomTree = &getAnalysis<MachineDominatorTree>();
602 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
604 bool Changed = false;
605 IfConv.runOnMachineFunction(MF);
607 // Visit blocks in dominator tree post-order. The post-order enables nested
608 // if-conversion in a single pass. The tryConvertIf() function may erase
609 // blocks, but only blocks dominated by the head block. This makes it safe to
610 // update the dominator tree while the post-order iterator is still active.
611 for (po_iterator<MachineDominatorTree*>
612 I = po_begin(DomTree), E = po_end(DomTree); I != E; ++I)
613 if (tryConvertIf(I->getBlock()))
616 MF.verify(this, "After early if-conversion");