blob: f9347efdb0e9c6ca17af1428027c92665dc05bcf [file] [log] [blame]
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +00001//===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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
12// may mispredict.
13//
14// Instructions from both sides of the branch are executed specutatively, and a
15// cmov instruction selects the result.
16//
17//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "early-ifcvt"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000020#include "MachineTraceMetrics.h"
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000021#include "llvm/Function.h"
22#include "llvm/ADT/BitVector.h"
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +000023#include "llvm/ADT/PostOrderIterator.h"
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000024#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesen786556c2012-08-13 21:03:27 +000027#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000028#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +000029#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesen47730a72012-07-10 22:39:56 +000032#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000033#include "llvm/CodeGen/MachineRegisterInfo.h"
34#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen0fac6aa2012-08-08 18:19:58 +000035#include "llvm/MC/MCInstrItineraries.h"
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000036#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetRegisterInfo.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/raw_ostream.h"
41
42using namespace llvm;
43
44// Absolute maximum number of instructions allowed per speculated block.
45// This bypasses all other heuristics, so it should be set fairly high.
46static cl::opt<unsigned>
47BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
48 cl::desc("Maximum number of instructions per speculated block."));
49
50// Stress testing mode - disable heuristics.
51static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
52 cl::desc("Turn all knobs to 11"));
53
Jakob Stoklund Olesen786556c2012-08-13 21:03:27 +000054STATISTIC(NumDiamondsSeen, "Number of diamonds");
55STATISTIC(NumDiamondsConv, "Number of diamonds converted");
56STATISTIC(NumTrianglesSeen, "Number of triangles");
57STATISTIC(NumTrianglesConv, "Number of triangles converted");
58
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000059//===----------------------------------------------------------------------===//
60// SSAIfConv
61//===----------------------------------------------------------------------===//
62//
63// The SSAIfConv class performs if-conversion on SSA form machine code after
Matt Beaumont-Gay00f43072012-07-04 01:09:45 +000064// determining if it is possible. The class contains no heuristics; external
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000065// code should be used to determine when if-conversion is a good idea.
66//
Matt Beaumont-Gay00f43072012-07-04 01:09:45 +000067// SSAIfConv can convert both triangles and diamonds:
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000068//
69// Triangle: Head Diamond: Head
Matt Beaumont-Gay00f43072012-07-04 01:09:45 +000070// | \ / \_
71// | \ / |
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000072// | [TF]BB FBB TBB
73// | / \ /
74// | / \ /
75// Tail Tail
76//
77// Instructions in the conditional blocks TBB and/or FBB are spliced into the
Matt Beaumont-Gay00f43072012-07-04 01:09:45 +000078// Head block, and phis in the Tail block are converted to select instructions.
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000079//
80namespace {
81class SSAIfConv {
82 const TargetInstrInfo *TII;
83 const TargetRegisterInfo *TRI;
84 MachineRegisterInfo *MRI;
85
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +000086public:
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +000087 /// The block containing the conditional branch.
88 MachineBasicBlock *Head;
89
90 /// The block containing phis after the if-then-else.
91 MachineBasicBlock *Tail;
92
93 /// The 'true' conditional block as determined by AnalyzeBranch.
94 MachineBasicBlock *TBB;
95
96 /// The 'false' conditional block as determined by AnalyzeBranch.
97 MachineBasicBlock *FBB;
98
99 /// isTriangle - When there is no 'else' block, either TBB or FBB will be
100 /// equal to Tail.
101 bool isTriangle() const { return TBB == Tail || FBB == Tail; }
102
Jakob Stoklund Olesen870da6d2012-08-10 20:19:17 +0000103 /// Returns the Tail predecessor for the True side.
104 MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
105
106 /// Returns the Tail predecessor for the False side.
107 MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
108
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000109 /// Information about each phi in the Tail block.
110 struct PHIInfo {
111 MachineInstr *PHI;
112 unsigned TReg, FReg;
113 // Latencies from Cond+Branch, TReg, and FReg to DstReg.
114 int CondCycles, TCycles, FCycles;
115
116 PHIInfo(MachineInstr *phi)
117 : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
118 };
119
120 SmallVector<PHIInfo, 8> PHIs;
121
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000122private:
123 /// The branch condition determined by AnalyzeBranch.
124 SmallVector<MachineOperand, 4> Cond;
125
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000126 /// Instructions in Head that define values used by the conditional blocks.
127 /// The hoisted instructions must be inserted after these instructions.
128 SmallPtrSet<MachineInstr*, 8> InsertAfter;
129
130 /// Register units clobbered by the conditional blocks.
131 BitVector ClobberedRegUnits;
132
133 // Scratch pad for findInsertionPoint.
134 SparseSet<unsigned> LiveRegUnits;
135
136 /// Insertion point in Head for speculatively executed instructions form TBB
137 /// and FBB.
138 MachineBasicBlock::iterator InsertionPoint;
139
140 /// Return true if all non-terminator instructions in MBB can be safely
141 /// speculated.
142 bool canSpeculateInstrs(MachineBasicBlock *MBB);
143
144 /// Find a valid insertion point in Head.
145 bool findInsertionPoint();
146
Jakob Stoklund Olesenbc70ff32012-08-13 20:49:04 +0000147 /// Replace PHI instructions in Tail with selects.
148 void replacePHIInstrs();
149
150 /// Insert selects and rewrite PHI operands to use them.
151 void rewritePHIOperands();
152
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000153public:
154 /// runOnMachineFunction - Initialize per-function data structures.
155 void runOnMachineFunction(MachineFunction &MF) {
156 TII = MF.getTarget().getInstrInfo();
157 TRI = MF.getTarget().getRegisterInfo();
158 MRI = &MF.getRegInfo();
159 LiveRegUnits.clear();
160 LiveRegUnits.setUniverse(TRI->getNumRegUnits());
161 ClobberedRegUnits.clear();
162 ClobberedRegUnits.resize(TRI->getNumRegUnits());
163 }
164
165 /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
166 /// initialize the internal state, and return true.
167 bool canConvertIf(MachineBasicBlock *MBB);
168
169 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000170 /// it is possible. Add any erased blocks to RemovedBlocks.
171 void convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks);
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000172};
173} // end anonymous namespace
174
175
176/// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
177/// be speculated. The terminators are not considered.
178///
179/// If instructions use any values that are defined in the head basic block,
180/// the defining instructions are added to InsertAfter.
181///
182/// Any clobbered regunits are added to ClobberedRegUnits.
183///
184bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
185 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
186 // get right.
187 if (!MBB->livein_empty()) {
188 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n");
189 return false;
190 }
191
192 unsigned InstrCount = 0;
Jakob Stoklund Olesen86fc3102012-07-06 02:31:22 +0000193
194 // Check all instructions, except the terminators. It is assumed that
195 // terminators never have side effects or define any used register values.
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000196 for (MachineBasicBlock::iterator I = MBB->begin(),
197 E = MBB->getFirstTerminator(); I != E; ++I) {
198 if (I->isDebugValue())
199 continue;
200
201 if (++InstrCount > BlockInstrLimit && !Stress) {
202 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than "
203 << BlockInstrLimit << " instructions.\n");
204 return false;
205 }
206
207 // There shouldn't normally be any phis in a single-predecessor block.
208 if (I->isPHI()) {
209 DEBUG(dbgs() << "Can't hoist: " << *I);
210 return false;
211 }
212
213 // Don't speculate loads. Note that it may be possible and desirable to
214 // speculate GOT or constant pool loads that are guaranteed not to trap,
215 // but we don't support that for now.
216 if (I->mayLoad()) {
217 DEBUG(dbgs() << "Won't speculate load: " << *I);
218 return false;
219 }
220
221 // We never speculate stores, so an AA pointer isn't necessary.
222 bool DontMoveAcrossStore = true;
223 if (!I->isSafeToMove(TII, 0, DontMoveAcrossStore)) {
224 DEBUG(dbgs() << "Can't speculate: " << *I);
225 return false;
226 }
227
228 // Check for any dependencies on Head instructions.
229 for (MIOperands MO(I); MO.isValid(); ++MO) {
230 if (MO->isRegMask()) {
231 DEBUG(dbgs() << "Won't speculate regmask: " << *I);
232 return false;
233 }
234 if (!MO->isReg())
235 continue;
236 unsigned Reg = MO->getReg();
237
238 // Remember clobbered regunits.
239 if (MO->isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
240 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
241 ClobberedRegUnits.set(*Units);
242
243 if (!MO->readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
244 continue;
245 MachineInstr *DefMI = MRI->getVRegDef(Reg);
246 if (!DefMI || DefMI->getParent() != Head)
247 continue;
248 if (InsertAfter.insert(DefMI))
249 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " depends on " << *DefMI);
250 if (DefMI->isTerminator()) {
251 DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
252 return false;
253 }
254 }
255 }
256 return true;
257}
258
259
260/// Find an insertion point in Head for the speculated instructions. The
261/// insertion point must be:
262///
263/// 1. Before any terminators.
264/// 2. After any instructions in InsertAfter.
265/// 3. Not have any clobbered regunits live.
266///
267/// This function sets InsertionPoint and returns true when successful, it
268/// returns false if no valid insertion point could be found.
269///
270bool SSAIfConv::findInsertionPoint() {
271 // Keep track of live regunits before the current position.
272 // Only track RegUnits that are also in ClobberedRegUnits.
273 LiveRegUnits.clear();
274 SmallVector<unsigned, 8> Reads;
275 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
276 MachineBasicBlock::iterator I = Head->end();
277 MachineBasicBlock::iterator B = Head->begin();
278 while (I != B) {
279 --I;
280 // Some of the conditional code depends in I.
281 if (InsertAfter.count(I)) {
282 DEBUG(dbgs() << "Can't insert code after " << *I);
283 return false;
284 }
285
286 // Update live regunits.
287 for (MIOperands MO(I); MO.isValid(); ++MO) {
288 // We're ignoring regmask operands. That is conservatively correct.
289 if (!MO->isReg())
290 continue;
291 unsigned Reg = MO->getReg();
292 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
293 continue;
294 // I clobbers Reg, so it isn't live before I.
295 if (MO->isDef())
296 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
297 LiveRegUnits.erase(*Units);
298 // Unless I reads Reg.
299 if (MO->readsReg())
300 Reads.push_back(Reg);
301 }
302 // Anything read by I is live before I.
303 while (!Reads.empty())
304 for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
305 ++Units)
306 if (ClobberedRegUnits.test(*Units))
307 LiveRegUnits.insert(*Units);
308
309 // We can't insert before a terminator.
310 if (I != FirstTerm && I->isTerminator())
311 continue;
312
313 // Some of the clobbered registers are live before I, not a valid insertion
314 // point.
315 if (!LiveRegUnits.empty()) {
316 DEBUG({
317 dbgs() << "Would clobber";
318 for (SparseSet<unsigned>::const_iterator
319 i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
320 dbgs() << ' ' << PrintRegUnit(*i, TRI);
321 dbgs() << " live before " << *I;
322 });
323 continue;
324 }
325
326 // This is a valid insertion point.
327 InsertionPoint = I;
328 DEBUG(dbgs() << "Can insert before " << *I);
329 return true;
330 }
331 DEBUG(dbgs() << "No legal insertion point found.\n");
332 return false;
333}
334
335
336
337/// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
338/// a potential candidate for if-conversion. Fill out the internal state.
339///
340bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
341 Head = MBB;
342 TBB = FBB = Tail = 0;
343
344 if (Head->succ_size() != 2)
345 return false;
346 MachineBasicBlock *Succ0 = Head->succ_begin()[0];
347 MachineBasicBlock *Succ1 = Head->succ_begin()[1];
348
349 // Canonicalize so Succ0 has MBB as its single predecessor.
350 if (Succ0->pred_size() != 1)
351 std::swap(Succ0, Succ1);
352
353 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
354 return false;
355
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000356 Tail = Succ0->succ_begin()[0];
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000357
358 // This is not a triangle.
359 if (Tail != Succ1) {
360 // Check for a diamond. We won't deal with any critical edges.
361 if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
362 Succ1->succ_begin()[0] != Tail)
363 return false;
364 DEBUG(dbgs() << "\nDiamond: BB#" << Head->getNumber()
365 << " -> BB#" << Succ0->getNumber()
366 << "/BB#" << Succ1->getNumber()
367 << " -> BB#" << Tail->getNumber() << '\n');
368
369 // Live-in physregs are tricky to get right when speculating code.
370 if (!Tail->livein_empty()) {
371 DEBUG(dbgs() << "Tail has live-ins.\n");
372 return false;
373 }
374 } else {
375 DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber()
376 << " -> BB#" << Succ0->getNumber()
377 << " -> BB#" << Tail->getNumber() << '\n');
378 }
379
380 // This is a triangle or a diamond.
381 // If Tail doesn't have any phis, there must be side effects.
382 if (Tail->empty() || !Tail->front().isPHI()) {
383 DEBUG(dbgs() << "No phis in tail.\n");
384 return false;
385 }
386
387 // The branch we're looking to eliminate must be analyzable.
388 Cond.clear();
389 if (TII->AnalyzeBranch(*Head, TBB, FBB, Cond)) {
390 DEBUG(dbgs() << "Branch not analyzable.\n");
391 return false;
392 }
393
394 // This is weird, probably some sort of degenerate CFG.
395 if (!TBB) {
396 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
397 return false;
398 }
399
400 // AnalyzeBranch doesn't set FBB on a fall-through branch.
401 // Make sure it is always set.
402 FBB = TBB == Succ0 ? Succ1 : Succ0;
403
404 // Any phis in the tail block must be convertible to selects.
405 PHIs.clear();
Jakob Stoklund Olesen870da6d2012-08-10 20:19:17 +0000406 MachineBasicBlock *TPred = getTPred();
407 MachineBasicBlock *FPred = getFPred();
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000408 for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
409 I != E && I->isPHI(); ++I) {
410 PHIs.push_back(&*I);
411 PHIInfo &PI = PHIs.back();
412 // Find PHI operands corresponding to TPred and FPred.
413 for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
414 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
415 PI.TReg = PI.PHI->getOperand(i).getReg();
416 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
417 PI.FReg = PI.PHI->getOperand(i).getReg();
418 }
419 assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
420 assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
421
422 // Get target information.
423 if (!TII->canInsertSelect(*Head, Cond, PI.TReg, PI.FReg,
424 PI.CondCycles, PI.TCycles, PI.FCycles)) {
425 DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
426 return false;
427 }
428 }
429
430 // Check that the conditional instructions can be speculated.
431 InsertAfter.clear();
432 ClobberedRegUnits.reset();
433 if (TBB != Tail && !canSpeculateInstrs(TBB))
434 return false;
435 if (FBB != Tail && !canSpeculateInstrs(FBB))
436 return false;
437
438 // Try to find a valid insertion point for the speculated instructions in the
439 // head basic block.
440 if (!findInsertionPoint())
441 return false;
442
Jakob Stoklund Olesen786556c2012-08-13 21:03:27 +0000443 if (isTriangle())
444 ++NumTrianglesSeen;
445 else
446 ++NumDiamondsSeen;
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000447 return true;
448}
449
Jakob Stoklund Olesenbc70ff32012-08-13 20:49:04 +0000450/// replacePHIInstrs - Completely replace PHI instructions with selects.
451/// This is possible when the only Tail predecessors are the if-converted
452/// blocks.
453void SSAIfConv::replacePHIInstrs() {
454 assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000455 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
456 assert(FirstTerm != Head->end() && "No terminators");
457 DebugLoc HeadDL = FirstTerm->getDebugLoc();
458
459 // Convert all PHIs to select instructions inserted before FirstTerm.
460 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
461 PHIInfo &PI = PHIs[i];
462 DEBUG(dbgs() << "If-converting " << *PI.PHI);
463 assert(PI.PHI->getNumOperands() == 5 && "Unexpected PHI operands.");
464 unsigned DstReg = PI.PHI->getOperand(0).getReg();
465 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
466 DEBUG(dbgs() << " --> " << *llvm::prior(FirstTerm));
467 PI.PHI->eraseFromParent();
468 PI.PHI = 0;
469 }
Jakob Stoklund Olesenbc70ff32012-08-13 20:49:04 +0000470}
471
472/// rewritePHIOperands - When there are additional Tail predecessors, insert
473/// select instructions in Head and rewrite PHI operands to use the selects.
474/// Keep the PHI instructions in Tail to handle the other predecessors.
475void SSAIfConv::rewritePHIOperands() {
476 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
477 assert(FirstTerm != Head->end() && "No terminators");
478 DebugLoc HeadDL = FirstTerm->getDebugLoc();
479
480 // Convert all PHIs to select instructions inserted before FirstTerm.
481 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
482 PHIInfo &PI = PHIs[i];
483 DEBUG(dbgs() << "If-converting " << *PI.PHI);
484 unsigned PHIDst = PI.PHI->getOperand(0).getReg();
485 unsigned DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
486 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
487 DEBUG(dbgs() << " --> " << *llvm::prior(FirstTerm));
488
489 // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
490 for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
491 MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
492 if (MBB == getTPred()) {
493 PI.PHI->getOperand(i-1).setMBB(Head);
494 PI.PHI->getOperand(i-2).setReg(DstReg);
495 } else if (MBB == getFPred()) {
496 PI.PHI->RemoveOperand(i-1);
497 PI.PHI->RemoveOperand(i-2);
498 }
499 }
500 DEBUG(dbgs() << " --> " << *PI.PHI);
501 }
502}
503
504/// convertIf - Execute the if conversion after canConvertIf has determined the
505/// feasibility.
506///
507/// Any basic blocks erased will be added to RemovedBlocks.
508///
509void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks) {
510 assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
511
Jakob Stoklund Olesen786556c2012-08-13 21:03:27 +0000512 // Update statistics.
513 if (isTriangle())
514 ++NumTrianglesConv;
515 else
516 ++NumDiamondsConv;
517
Jakob Stoklund Olesenbc70ff32012-08-13 20:49:04 +0000518 // Move all instructions into Head, except for the terminators.
519 if (TBB != Tail)
520 Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
521 if (FBB != Tail)
522 Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
523
524 // Are there extra Tail predecessors?
525 bool ExtraPreds = Tail->pred_size() != 2;
526 if (ExtraPreds)
527 rewritePHIOperands();
528 else
529 replacePHIInstrs();
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000530
531 // Fix up the CFG, temporarily leave Head without any successors.
532 Head->removeSuccessor(TBB);
533 Head->removeSuccessor(FBB);
534 if (TBB != Tail)
535 TBB->removeSuccessor(Tail);
536 if (FBB != Tail)
537 FBB->removeSuccessor(Tail);
538
539 // Fix up Head's terminators.
540 // It should become a single branch or a fallthrough.
Jakob Stoklund Olesenbc70ff32012-08-13 20:49:04 +0000541 DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000542 TII->RemoveBranch(*Head);
543
544 // Erase the now empty conditional blocks. It is likely that Head can fall
545 // through to Tail, and we can join the two blocks.
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000546 if (TBB != Tail) {
547 RemovedBlocks.push_back(TBB);
548 TBB->eraseFromParent();
549 }
550 if (FBB != Tail) {
551 RemovedBlocks.push_back(FBB);
552 FBB->eraseFromParent();
553 }
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000554
555 assert(Head->succ_empty() && "Additional head successors?");
Jakob Stoklund Olesenbc70ff32012-08-13 20:49:04 +0000556 if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000557 // Splice Tail onto the end of Head.
558 DEBUG(dbgs() << "Joining tail BB#" << Tail->getNumber()
559 << " into head BB#" << Head->getNumber() << '\n');
560 Head->splice(Head->end(), Tail,
561 Tail->begin(), Tail->end());
562 Head->transferSuccessorsAndUpdatePHIs(Tail);
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000563 RemovedBlocks.push_back(Tail);
564 Tail->eraseFromParent();
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000565 } else {
566 // We need a branch to Tail, let code placement work it out later.
567 DEBUG(dbgs() << "Converting to unconditional branch.\n");
568 SmallVector<MachineOperand, 0> EmptyCond;
569 TII->InsertBranch(*Head, Tail, 0, EmptyCond, HeadDL);
570 Head->addSuccessor(Tail);
571 }
572 DEBUG(dbgs() << *Head);
573}
574
575
576//===----------------------------------------------------------------------===//
577// EarlyIfConverter Pass
578//===----------------------------------------------------------------------===//
579
580namespace {
581class EarlyIfConverter : public MachineFunctionPass {
582 const TargetInstrInfo *TII;
583 const TargetRegisterInfo *TRI;
Jakob Stoklund Olesen0fac6aa2012-08-08 18:19:58 +0000584 const MCSchedModel *SchedModel;
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000585 MachineRegisterInfo *MRI;
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000586 MachineDominatorTree *DomTree;
Jakob Stoklund Olesen47730a72012-07-10 22:39:56 +0000587 MachineLoopInfo *Loops;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000588 MachineTraceMetrics *Traces;
589 MachineTraceMetrics::Ensemble *MinInstr;
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000590 SSAIfConv IfConv;
591
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000592public:
593 static char ID;
594 EarlyIfConverter() : MachineFunctionPass(ID) {}
595 void getAnalysisUsage(AnalysisUsage &AU) const;
596 bool runOnMachineFunction(MachineFunction &MF);
597
598private:
599 bool tryConvertIf(MachineBasicBlock*);
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000600 void updateDomTree(ArrayRef<MachineBasicBlock*> Removed);
Jakob Stoklund Olesen47730a72012-07-10 22:39:56 +0000601 void updateLoops(ArrayRef<MachineBasicBlock*> Removed);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000602 void invalidateTraces();
603 bool shouldConvertIf();
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000604};
605} // end anonymous namespace
606
607char EarlyIfConverter::ID = 0;
608char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
609
610INITIALIZE_PASS_BEGIN(EarlyIfConverter,
611 "early-ifcvt", "Early If Converter", false, false)
612INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000613INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000614INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000615INITIALIZE_PASS_END(EarlyIfConverter,
616 "early-ifcvt", "Early If Converter", false, false)
617
618void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
619 AU.addRequired<MachineBranchProbabilityInfo>();
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000620 AU.addRequired<MachineDominatorTree>();
621 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesen47730a72012-07-10 22:39:56 +0000622 AU.addRequired<MachineLoopInfo>();
623 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000624 AU.addRequired<MachineTraceMetrics>();
625 AU.addPreserved<MachineTraceMetrics>();
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000626 MachineFunctionPass::getAnalysisUsage(AU);
627}
628
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000629/// Update the dominator tree after if-conversion erased some blocks.
630void EarlyIfConverter::updateDomTree(ArrayRef<MachineBasicBlock*> Removed) {
631 // convertIf can remove TBB, FBB, and Tail can be merged into Head.
632 // TBB and FBB should not dominate any blocks.
633 // Tail children should be transferred to Head.
634 MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
635 for (unsigned i = 0, e = Removed.size(); i != e; ++i) {
636 MachineDomTreeNode *Node = DomTree->getNode(Removed[i]);
637 assert(Node != HeadNode && "Cannot erase the head node");
638 while (Node->getNumChildren()) {
639 assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
640 DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode);
641 }
642 DomTree->eraseNode(Removed[i]);
643 }
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000644}
645
Jakob Stoklund Olesen47730a72012-07-10 22:39:56 +0000646/// Update LoopInfo after if-conversion.
647void EarlyIfConverter::updateLoops(ArrayRef<MachineBasicBlock*> Removed) {
648 if (!Loops)
649 return;
650 // If-conversion doesn't change loop structure, and it doesn't mess with back
651 // edges, so updating LoopInfo is simply removing the dead blocks.
652 for (unsigned i = 0, e = Removed.size(); i != e; ++i)
653 Loops->removeBlock(Removed[i]);
654}
655
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000656/// Invalidate MachineTraceMetrics before if-conversion.
657void EarlyIfConverter::invalidateTraces() {
Jakob Stoklund Olesenef6c76c2012-07-30 20:57:50 +0000658 Traces->verifyAnalysis();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000659 Traces->invalidate(IfConv.Head);
660 Traces->invalidate(IfConv.Tail);
661 Traces->invalidate(IfConv.TBB);
662 Traces->invalidate(IfConv.FBB);
Jakob Stoklund Olesenef6c76c2012-07-30 20:57:50 +0000663 Traces->verifyAnalysis();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000664}
665
Jakob Stoklund Oleseneb74c082012-08-10 22:27:31 +0000666// Adjust cycles with downward saturation.
667static unsigned adjCycles(unsigned Cyc, int Delta) {
668 if (Delta < 0 && Cyc + Delta > Cyc)
669 return 0;
670 return Cyc + Delta;
671}
672
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000673/// Apply cost model and heuristics to the if-conversion in IfConv.
674/// Return true if the conversion is a good idea.
675///
676bool EarlyIfConverter::shouldConvertIf() {
Jakob Stoklund Olesend6cf5f42012-08-08 18:24:23 +0000677 // Stress testing mode disables all cost considerations.
678 if (Stress)
679 return true;
680
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000681 if (!MinInstr)
682 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +0000683
Jakob Stoklund Oleseneb74c082012-08-10 22:27:31 +0000684 MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
685 MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +0000686 DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
Jakob Stoklund Oleseneb74c082012-08-10 22:27:31 +0000687 unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
688 FBBTrace.getCriticalPath());
689
690 // Set a somewhat arbitrary limit on the critical path extension we accept.
691 unsigned CritLimit = SchedModel->MispredictPenalty/2;
692
693 // If-conversion only makes sense when there is unexploited ILP. Compute the
694 // maximum-ILP resource length of the trace after if-conversion. Compare it
695 // to the shortest critical path.
696 SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
697 if (IfConv.TBB != IfConv.Tail)
698 ExtraBlocks.push_back(IfConv.TBB);
699 unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
700 DEBUG(dbgs() << "Resource length " << ResLength
701 << ", minimal critical path " << MinCrit << '\n');
702 if (ResLength > MinCrit + CritLimit) {
703 DEBUG(dbgs() << "Not enough available ILP.\n");
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +0000704 return false;
705 }
Jakob Stoklund Oleseneb74c082012-08-10 22:27:31 +0000706
707 // Assume that the depth of the first head terminator will also be the depth
708 // of the select instruction inserted, as determined by the flag dependency.
709 // TBB / FBB data dependencies may delay the select even more.
710 MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
711 unsigned BranchDepth =
712 HeadTrace.getInstrCycles(IfConv.Head->getFirstTerminator()).Depth;
713 DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
714
715 // Look at all the tail phis, and compute the critical path extension caused
716 // by inserting select instructions.
717 MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
718 for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
719 SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
720 unsigned Slack = TailTrace.getInstrSlack(PI.PHI);
721 unsigned MaxDepth = Slack + TailTrace.getInstrCycles(PI.PHI).Depth;
722 DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
723
724 // The condition is pulled into the critical path.
725 unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
726 if (CondDepth > MaxDepth) {
727 unsigned Extra = CondDepth - MaxDepth;
728 DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
729 if (Extra > CritLimit) {
730 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
731 return false;
732 }
733 }
734
735 // The TBB value is pulled into the critical path.
736 unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(PI.PHI), PI.TCycles);
737 if (TDepth > MaxDepth) {
738 unsigned Extra = TDepth - MaxDepth;
739 DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
740 if (Extra > CritLimit) {
741 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
742 return false;
743 }
744 }
745
746 // The FBB value is pulled into the critical path.
747 unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(PI.PHI), PI.FCycles);
748 if (FDepth > MaxDepth) {
749 unsigned Extra = FDepth - MaxDepth;
750 DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
751 if (Extra > CritLimit) {
752 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
753 return false;
754 }
755 }
756 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000757 return true;
758}
759
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000760/// Attempt repeated if-conversion on MBB, return true if successful.
761///
762bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
763 bool Changed = false;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000764 while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000765 // If-convert MBB and update analyses.
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000766 invalidateTraces();
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000767 SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
768 IfConv.convertIf(RemovedBlocks);
769 Changed = true;
770 updateDomTree(RemovedBlocks);
Jakob Stoklund Olesen47730a72012-07-10 22:39:56 +0000771 updateLoops(RemovedBlocks);
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000772 }
773 return Changed;
774}
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000775
776bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
777 DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
778 << "********** Function: "
779 << ((Value*)MF.getFunction())->getName() << '\n');
780 TII = MF.getTarget().getInstrInfo();
781 TRI = MF.getTarget().getRegisterInfo();
Jakob Stoklund Olesen0fac6aa2012-08-08 18:19:58 +0000782 SchedModel = MF.getTarget().getInstrItineraryData()->SchedModel;
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000783 MRI = &MF.getRegInfo();
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000784 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesen47730a72012-07-10 22:39:56 +0000785 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000786 Traces = &getAnalysis<MachineTraceMetrics>();
787 MinInstr = 0;
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000788
789 bool Changed = false;
790 IfConv.runOnMachineFunction(MF);
791
Jakob Stoklund Olesen1f523dc2012-07-10 22:18:23 +0000792 // Visit blocks in dominator tree post-order. The post-order enables nested
793 // if-conversion in a single pass. The tryConvertIf() function may erase
794 // blocks, but only blocks dominated by the head block. This makes it safe to
795 // update the dominator tree while the post-order iterator is still active.
796 for (po_iterator<MachineDominatorTree*>
797 I = po_begin(DomTree), E = po_end(DomTree); I != E; ++I)
798 if (tryConvertIf(I->getBlock()))
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000799 Changed = true;
800
Jakob Stoklund Olesen33242fd2012-07-04 00:09:54 +0000801 MF.verify(this, "After early if-conversion");
802 return Changed;
803}