blob: 4915447c502f23d30095365715f8bc53eb19e438 [file] [log] [blame]
Jakob Stoklund Olesenf8a63a12012-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
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000019#include "llvm/ADT/BitVector.h"
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +000020#include "llvm/ADT/PostOrderIterator.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000021#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesend0af1d92012-08-13 21:03:27 +000024#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000025#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +000026#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +000029#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesen965665b2013-01-17 01:06:04 +000031#include "llvm/CodeGen/MachineTraceMetrics.h"
32#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetRegisterInfo.h"
38#include "llvm/Target/TargetSubtargetInfo.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000039
40using namespace llvm;
41
Chandler Carruth1b9dde02014-04-22 02:02:50 +000042#define DEBUG_TYPE "early-ifcvt"
43
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000044// 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 Olesend0af1d92012-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 Olesenf8a63a12012-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-Gay11d08b22012-07-04 01:09:45 +000064// determining if it is possible. The class contains no heuristics; external
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000065// code should be used to determine when if-conversion is a good idea.
66//
Matt Beaumont-Gay11d08b22012-07-04 01:09:45 +000067// SSAIfConv can convert both triangles and diamonds:
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000068//
69// Triangle: Head Diamond: Head
Matt Beaumont-Gay11d08b22012-07-04 01:09:45 +000070// | \ / \_
71// | \ / |
Jakob Stoklund Olesenf8a63a12012-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-Gay11d08b22012-07-04 01:09:45 +000078// Head block, and phis in the Tail block are converted to select instructions.
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000079//
80namespace {
81class SSAIfConv {
82 const TargetInstrInfo *TII;
83 const TargetRegisterInfo *TRI;
84 MachineRegisterInfo *MRI;
85
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +000086public:
Jakob Stoklund Olesenf8a63a12012-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 Olesen0a990622012-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 Olesenf8a63a12012-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 Olesen02638392012-07-10 22:18:23 +0000122private:
123 /// The branch condition determined by AnalyzeBranch.
124 SmallVector<MachineOperand, 4> Cond;
125
Jakob Stoklund Olesenf8a63a12012-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 Olesen83a927d2012-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 Olesenf8a63a12012-07-04 00:09:54 +0000153public:
154 /// runOnMachineFunction - Initialize per-function data structures.
155 void runOnMachineFunction(MachineFunction &MF) {
Eric Christopherfc6de422014-08-05 02:39:49 +0000156 TII = MF.getSubtarget().getInstrInfo();
157 TRI = MF.getSubtarget().getRegisterInfo();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000158 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 Olesen02638392012-07-10 22:18:23 +0000170 /// it is possible. Add any erased blocks to RemovedBlocks.
171 void convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks);
Jakob Stoklund Olesenf8a63a12012-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 Olesen3f1bb932012-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 Olesenf8a63a12012-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;
Matthias Braun07066cc2015-05-19 21:22:20 +0000223 if (!I->isSafeToMove(nullptr, DontMoveAcrossStore)) {
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000224 DEBUG(dbgs() << "Can't speculate: " << *I);
225 return false;
226 }
227
228 // Check for any dependencies on Head instructions.
Matthias Braun27a6cfd2015-05-29 02:59:59 +0000229 for (const MachineOperand &MO : I->operands()) {
Matthias Braune41e1462015-05-29 02:56:46 +0000230 if (MO.isRegMask()) {
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000231 DEBUG(dbgs() << "Won't speculate regmask: " << *I);
232 return false;
233 }
Matthias Braune41e1462015-05-29 02:56:46 +0000234 if (!MO.isReg())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000235 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000236 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000237
238 // Remember clobbered regunits.
Matthias Braune41e1462015-05-29 02:56:46 +0000239 if (MO.isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000240 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
241 ClobberedRegUnits.set(*Units);
242
Matthias Braune41e1462015-05-29 02:56:46 +0000243 if (!MO.readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000244 continue;
245 MachineInstr *DefMI = MRI->getVRegDef(Reg);
246 if (!DefMI || DefMI->getParent() != Head)
247 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000248 if (InsertAfter.insert(DefMI).second)
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000249 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.
Duncan P. N. Exon Smith395bd9c2016-02-22 02:53:42 +0000281 if (InsertAfter.count(&*I)) {
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000282 DEBUG(dbgs() << "Can't insert code after " << *I);
283 return false;
284 }
285
286 // Update live regunits.
Matthias Braune41e1462015-05-29 02:56:46 +0000287 for (const MachineOperand &MO : I->operands()) {
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000288 // We're ignoring regmask operands. That is conservatively correct.
Matthias Braune41e1462015-05-29 02:56:46 +0000289 if (!MO.isReg())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000290 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000291 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000292 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
293 continue;
294 // I clobbers Reg, so it isn't live before I.
Matthias Braune41e1462015-05-29 02:56:46 +0000295 if (MO.isDef())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000296 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
297 LiveRegUnits.erase(*Units);
298 // Unless I reads Reg.
Matthias Braune41e1462015-05-29 02:56:46 +0000299 if (MO.readsReg())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000300 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;
Craig Topperc0196b12014-04-14 00:51:57 +0000342 TBB = FBB = Tail = nullptr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000343
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 Olesenf8a63a12012-07-04 00:09:54 +0000356 Tail = Succ0->succ_begin()[0];
Jakob Stoklund Olesenf8a63a12012-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 Olesen0a990622012-08-10 20:19:17 +0000406 MachineBasicBlock *TPred = getTPred();
407 MachineBasicBlock *FPred = getFPred();
Jakob Stoklund Olesenf8a63a12012-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 Olesend0af1d92012-08-13 21:03:27 +0000443 if (isTriangle())
444 ++NumTrianglesSeen;
445 else
446 ++NumDiamondsSeen;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000447 return true;
448}
449
Jakob Stoklund Olesen83a927d2012-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 Olesenf8a63a12012-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);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000463 unsigned DstReg = PI.PHI->getOperand(0).getReg();
464 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000465 DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000466 PI.PHI->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +0000467 PI.PHI = nullptr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000468 }
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000469}
470
471/// rewritePHIOperands - When there are additional Tail predecessors, insert
472/// select instructions in Head and rewrite PHI operands to use the selects.
473/// Keep the PHI instructions in Tail to handle the other predecessors.
474void SSAIfConv::rewritePHIOperands() {
475 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
476 assert(FirstTerm != Head->end() && "No terminators");
477 DebugLoc HeadDL = FirstTerm->getDebugLoc();
478
479 // Convert all PHIs to select instructions inserted before FirstTerm.
480 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
481 PHIInfo &PI = PHIs[i];
Yi Jiange0b34992015-06-18 22:34:09 +0000482 unsigned DstReg = 0;
Junmo Park67bb3f12016-01-29 01:39:39 +0000483
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000484 DEBUG(dbgs() << "If-converting " << *PI.PHI);
Yi Jiange0b34992015-06-18 22:34:09 +0000485 if (PI.TReg == PI.FReg) {
486 // We do not need the select instruction if both incoming values are
487 // equal.
488 DstReg = PI.TReg;
489 } else {
490 unsigned PHIDst = PI.PHI->getOperand(0).getReg();
491 DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
492 TII->insertSelect(*Head, FirstTerm, HeadDL,
493 DstReg, Cond, PI.TReg, PI.FReg);
494 DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
495 }
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000496
497 // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
498 for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
499 MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
500 if (MBB == getTPred()) {
501 PI.PHI->getOperand(i-1).setMBB(Head);
502 PI.PHI->getOperand(i-2).setReg(DstReg);
503 } else if (MBB == getFPred()) {
504 PI.PHI->RemoveOperand(i-1);
505 PI.PHI->RemoveOperand(i-2);
506 }
507 }
508 DEBUG(dbgs() << " --> " << *PI.PHI);
509 }
510}
511
512/// convertIf - Execute the if conversion after canConvertIf has determined the
513/// feasibility.
514///
515/// Any basic blocks erased will be added to RemovedBlocks.
516///
517void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks) {
518 assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
519
Jakob Stoklund Olesend0af1d92012-08-13 21:03:27 +0000520 // Update statistics.
521 if (isTriangle())
522 ++NumTrianglesConv;
523 else
524 ++NumDiamondsConv;
525
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000526 // Move all instructions into Head, except for the terminators.
527 if (TBB != Tail)
528 Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
529 if (FBB != Tail)
530 Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
531
532 // Are there extra Tail predecessors?
533 bool ExtraPreds = Tail->pred_size() != 2;
534 if (ExtraPreds)
535 rewritePHIOperands();
536 else
537 replacePHIInstrs();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000538
539 // Fix up the CFG, temporarily leave Head without any successors.
540 Head->removeSuccessor(TBB);
Cong Houc1069892015-12-13 09:26:17 +0000541 Head->removeSuccessor(FBB, true);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000542 if (TBB != Tail)
Cong Houc1069892015-12-13 09:26:17 +0000543 TBB->removeSuccessor(Tail, true);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000544 if (FBB != Tail)
Cong Houc1069892015-12-13 09:26:17 +0000545 FBB->removeSuccessor(Tail, true);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000546
547 // Fix up Head's terminators.
548 // It should become a single branch or a fallthrough.
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000549 DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000550 TII->RemoveBranch(*Head);
551
552 // Erase the now empty conditional blocks. It is likely that Head can fall
553 // through to Tail, and we can join the two blocks.
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000554 if (TBB != Tail) {
555 RemovedBlocks.push_back(TBB);
556 TBB->eraseFromParent();
557 }
558 if (FBB != Tail) {
559 RemovedBlocks.push_back(FBB);
560 FBB->eraseFromParent();
561 }
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000562
563 assert(Head->succ_empty() && "Additional head successors?");
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000564 if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000565 // Splice Tail onto the end of Head.
566 DEBUG(dbgs() << "Joining tail BB#" << Tail->getNumber()
567 << " into head BB#" << Head->getNumber() << '\n');
568 Head->splice(Head->end(), Tail,
569 Tail->begin(), Tail->end());
570 Head->transferSuccessorsAndUpdatePHIs(Tail);
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000571 RemovedBlocks.push_back(Tail);
572 Tail->eraseFromParent();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000573 } else {
574 // We need a branch to Tail, let code placement work it out later.
575 DEBUG(dbgs() << "Converting to unconditional branch.\n");
576 SmallVector<MachineOperand, 0> EmptyCond;
Craig Topperc0196b12014-04-14 00:51:57 +0000577 TII->InsertBranch(*Head, Tail, nullptr, EmptyCond, HeadDL);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000578 Head->addSuccessor(Tail);
579 }
580 DEBUG(dbgs() << *Head);
581}
582
583
584//===----------------------------------------------------------------------===//
585// EarlyIfConverter Pass
586//===----------------------------------------------------------------------===//
587
588namespace {
589class EarlyIfConverter : public MachineFunctionPass {
590 const TargetInstrInfo *TII;
591 const TargetRegisterInfo *TRI;
Pete Cooper11759452014-09-02 17:43:54 +0000592 MCSchedModel SchedModel;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000593 MachineRegisterInfo *MRI;
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000594 MachineDominatorTree *DomTree;
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000595 MachineLoopInfo *Loops;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000596 MachineTraceMetrics *Traces;
597 MachineTraceMetrics::Ensemble *MinInstr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000598 SSAIfConv IfConv;
599
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000600public:
601 static char ID;
602 EarlyIfConverter() : MachineFunctionPass(ID) {}
Craig Topper4584cd52014-03-07 09:26:03 +0000603 void getAnalysisUsage(AnalysisUsage &AU) const override;
604 bool runOnMachineFunction(MachineFunction &MF) override;
605 const char *getPassName() const override { return "Early If-Conversion"; }
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000606
607private:
608 bool tryConvertIf(MachineBasicBlock*);
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000609 void updateDomTree(ArrayRef<MachineBasicBlock*> Removed);
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000610 void updateLoops(ArrayRef<MachineBasicBlock*> Removed);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000611 void invalidateTraces();
612 bool shouldConvertIf();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000613};
614} // end anonymous namespace
615
616char EarlyIfConverter::ID = 0;
617char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
618
619INITIALIZE_PASS_BEGIN(EarlyIfConverter,
620 "early-ifcvt", "Early If Converter", false, false)
621INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000622INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000623INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000624INITIALIZE_PASS_END(EarlyIfConverter,
625 "early-ifcvt", "Early If Converter", false, false)
626
627void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
628 AU.addRequired<MachineBranchProbabilityInfo>();
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000629 AU.addRequired<MachineDominatorTree>();
630 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000631 AU.addRequired<MachineLoopInfo>();
632 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000633 AU.addRequired<MachineTraceMetrics>();
634 AU.addPreserved<MachineTraceMetrics>();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000635 MachineFunctionPass::getAnalysisUsage(AU);
636}
637
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000638/// Update the dominator tree after if-conversion erased some blocks.
639void EarlyIfConverter::updateDomTree(ArrayRef<MachineBasicBlock*> Removed) {
640 // convertIf can remove TBB, FBB, and Tail can be merged into Head.
641 // TBB and FBB should not dominate any blocks.
642 // Tail children should be transferred to Head.
643 MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
644 for (unsigned i = 0, e = Removed.size(); i != e; ++i) {
645 MachineDomTreeNode *Node = DomTree->getNode(Removed[i]);
646 assert(Node != HeadNode && "Cannot erase the head node");
647 while (Node->getNumChildren()) {
648 assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
649 DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode);
650 }
651 DomTree->eraseNode(Removed[i]);
652 }
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000653}
654
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000655/// Update LoopInfo after if-conversion.
656void EarlyIfConverter::updateLoops(ArrayRef<MachineBasicBlock*> Removed) {
657 if (!Loops)
658 return;
659 // If-conversion doesn't change loop structure, and it doesn't mess with back
660 // edges, so updating LoopInfo is simply removing the dead blocks.
661 for (unsigned i = 0, e = Removed.size(); i != e; ++i)
662 Loops->removeBlock(Removed[i]);
663}
664
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000665/// Invalidate MachineTraceMetrics before if-conversion.
666void EarlyIfConverter::invalidateTraces() {
Jakob Stoklund Olesena12a7d52012-07-30 20:57:50 +0000667 Traces->verifyAnalysis();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000668 Traces->invalidate(IfConv.Head);
669 Traces->invalidate(IfConv.Tail);
670 Traces->invalidate(IfConv.TBB);
671 Traces->invalidate(IfConv.FBB);
Jakob Stoklund Olesena12a7d52012-07-30 20:57:50 +0000672 Traces->verifyAnalysis();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000673}
674
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000675// Adjust cycles with downward saturation.
676static unsigned adjCycles(unsigned Cyc, int Delta) {
677 if (Delta < 0 && Cyc + Delta > Cyc)
678 return 0;
679 return Cyc + Delta;
680}
681
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000682/// Apply cost model and heuristics to the if-conversion in IfConv.
683/// Return true if the conversion is a good idea.
684///
685bool EarlyIfConverter::shouldConvertIf() {
Jakob Stoklund Olesenfa8a26f2012-08-08 18:24:23 +0000686 // Stress testing mode disables all cost considerations.
687 if (Stress)
688 return true;
689
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000690 if (!MinInstr)
691 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +0000692
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000693 MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
694 MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +0000695 DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000696 unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
697 FBBTrace.getCriticalPath());
698
699 // Set a somewhat arbitrary limit on the critical path extension we accept.
Pete Cooper11759452014-09-02 17:43:54 +0000700 unsigned CritLimit = SchedModel.MispredictPenalty/2;
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000701
702 // If-conversion only makes sense when there is unexploited ILP. Compute the
703 // maximum-ILP resource length of the trace after if-conversion. Compare it
704 // to the shortest critical path.
705 SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
706 if (IfConv.TBB != IfConv.Tail)
707 ExtraBlocks.push_back(IfConv.TBB);
708 unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
709 DEBUG(dbgs() << "Resource length " << ResLength
710 << ", minimal critical path " << MinCrit << '\n');
711 if (ResLength > MinCrit + CritLimit) {
712 DEBUG(dbgs() << "Not enough available ILP.\n");
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +0000713 return false;
714 }
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000715
716 // Assume that the depth of the first head terminator will also be the depth
717 // of the select instruction inserted, as determined by the flag dependency.
718 // TBB / FBB data dependencies may delay the select even more.
719 MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
720 unsigned BranchDepth =
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000721 HeadTrace.getInstrCycles(*IfConv.Head->getFirstTerminator()).Depth;
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000722 DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
723
724 // Look at all the tail phis, and compute the critical path extension caused
725 // by inserting select instructions.
726 MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
727 for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
728 SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000729 unsigned Slack = TailTrace.getInstrSlack(*PI.PHI);
730 unsigned MaxDepth = Slack + TailTrace.getInstrCycles(*PI.PHI).Depth;
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000731 DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
732
733 // The condition is pulled into the critical path.
734 unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
735 if (CondDepth > MaxDepth) {
736 unsigned Extra = CondDepth - MaxDepth;
737 DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
738 if (Extra > CritLimit) {
739 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
740 return false;
741 }
742 }
743
744 // The TBB value is pulled into the critical path.
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000745 unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(*PI.PHI), PI.TCycles);
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000746 if (TDepth > MaxDepth) {
747 unsigned Extra = TDepth - MaxDepth;
748 DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
749 if (Extra > CritLimit) {
750 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
751 return false;
752 }
753 }
754
755 // The FBB value is pulled into the critical path.
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000756 unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(*PI.PHI), PI.FCycles);
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000757 if (FDepth > MaxDepth) {
758 unsigned Extra = FDepth - MaxDepth;
759 DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
760 if (Extra > CritLimit) {
761 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
762 return false;
763 }
764 }
765 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000766 return true;
767}
768
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000769/// Attempt repeated if-conversion on MBB, return true if successful.
770///
771bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
772 bool Changed = false;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000773 while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000774 // If-convert MBB and update analyses.
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000775 invalidateTraces();
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000776 SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
777 IfConv.convertIf(RemovedBlocks);
778 Changed = true;
779 updateDomTree(RemovedBlocks);
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000780 updateLoops(RemovedBlocks);
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000781 }
782 return Changed;
783}
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000784
785bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
786 DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
David Blaikiec8c29202012-08-22 17:18:53 +0000787 << "********** Function: " << MF.getName() << '\n');
Andrew Kaylor50271f72016-05-03 22:32:30 +0000788 if (skipFunction(*MF.getFunction()))
789 return false;
790
Eric Christopher6b0fcfe2014-05-21 23:40:26 +0000791 // Only run if conversion if the target wants it.
Eric Christopher3d4276f2015-01-27 07:31:29 +0000792 const TargetSubtargetInfo &STI = MF.getSubtarget();
793 if (!STI.enableEarlyIfConversion())
Eric Christopher9eff5178f2014-05-22 17:49:33 +0000794 return false;
Eric Christopher6b0fcfe2014-05-21 23:40:26 +0000795
Eric Christopher3d4276f2015-01-27 07:31:29 +0000796 TII = STI.getInstrInfo();
797 TRI = STI.getRegisterInfo();
798 SchedModel = STI.getSchedModel();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000799 MRI = &MF.getRegInfo();
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000800 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000801 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000802 Traces = &getAnalysis<MachineTraceMetrics>();
Craig Topperc0196b12014-04-14 00:51:57 +0000803 MinInstr = nullptr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000804
805 bool Changed = false;
806 IfConv.runOnMachineFunction(MF);
807
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000808 // Visit blocks in dominator tree post-order. The post-order enables nested
809 // if-conversion in a single pass. The tryConvertIf() function may erase
810 // blocks, but only blocks dominated by the head block. This makes it safe to
811 // update the dominator tree while the post-order iterator is still active.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000812 for (auto DomNode : post_order(DomTree))
813 if (tryConvertIf(DomNode->getBlock()))
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000814 Changed = true;
815
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000816 return Changed;
817}