blob: e5694218b5c3ec9cc95b317dde86c0784b7b752a [file] [log] [blame]
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +00001//===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Early if-conversion is for out-of-order CPUs that don't have a lot of
10// predicable instructions. The goal is to eliminate conditional branches that
11// may mispredict.
12//
13// Instructions from both sides of the branch are executed specutatively, and a
14// cmov instruction selects the result.
15//
16//===----------------------------------------------------------------------===//
17
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000018#include "llvm/ADT/BitVector.h"
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +000019#include "llvm/ADT/PostOrderIterator.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000020#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesend0af1d92012-08-13 21:03:27 +000023#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000024#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +000025#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000026#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
Thomas Raouxbe699bf2019-08-20 15:54:59 +000028#include "llvm/CodeGen/MachineInstr.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"
David Blaikie3f833ed2017-11-08 01:01:31 +000033#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000034#include "llvm/CodeGen/TargetRegisterInfo.h"
35#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/raw_ostream.h"
39
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
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000144 /// Return true if all non-terminator instructions in MBB can be safely
145 /// predicated.
146 bool canPredicateInstrs(MachineBasicBlock *MBB);
147
148 /// Scan through instruction dependencies and update InsertAfter array.
149 /// Return false if any dependency is incompatible with if conversion.
150 bool InstrDependenciesAllowIfConv(MachineInstr *I);
151
152 /// Predicate all instructions of the basic block with current condition
153 /// except for terminators. Reverse the condition if ReversePredicate is set.
154 void PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate);
155
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000156 /// Find a valid insertion point in Head.
157 bool findInsertionPoint();
158
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000159 /// Replace PHI instructions in Tail with selects.
160 void replacePHIInstrs();
161
162 /// Insert selects and rewrite PHI operands to use them.
163 void rewritePHIOperands();
164
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000165public:
166 /// runOnMachineFunction - Initialize per-function data structures.
167 void runOnMachineFunction(MachineFunction &MF) {
Eric Christopherfc6de422014-08-05 02:39:49 +0000168 TII = MF.getSubtarget().getInstrInfo();
169 TRI = MF.getSubtarget().getRegisterInfo();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000170 MRI = &MF.getRegInfo();
171 LiveRegUnits.clear();
172 LiveRegUnits.setUniverse(TRI->getNumRegUnits());
173 ClobberedRegUnits.clear();
174 ClobberedRegUnits.resize(TRI->getNumRegUnits());
175 }
176
177 /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
178 /// initialize the internal state, and return true.
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000179 /// If predicate is set try to predicate the block otherwise try to
180 /// speculatively execute it.
181 bool canConvertIf(MachineBasicBlock *MBB, bool Predicate = false);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000182
183 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000184 /// it is possible. Add any erased blocks to RemovedBlocks.
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000185 void convertIf(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks,
186 bool Predicate = false);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000187};
188} // end anonymous namespace
189
190
191/// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
192/// be speculated. The terminators are not considered.
193///
194/// If instructions use any values that are defined in the head basic block,
195/// the defining instructions are added to InsertAfter.
196///
197/// Any clobbered regunits are added to ClobberedRegUnits.
198///
199bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
200 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
201 // get right.
202 if (!MBB->livein_empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000203 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000204 return false;
205 }
206
207 unsigned InstrCount = 0;
Jakob Stoklund Olesen3f1bb932012-07-06 02:31:22 +0000208
209 // Check all instructions, except the terminators. It is assumed that
210 // terminators never have side effects or define any used register values.
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000211 for (MachineBasicBlock::iterator I = MBB->begin(),
212 E = MBB->getFirstTerminator(); I != E; ++I) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000213 if (I->isDebugInstr())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000214 continue;
215
216 if (++InstrCount > BlockInstrLimit && !Stress) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000217 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
218 << BlockInstrLimit << " instructions.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000219 return false;
220 }
221
222 // There shouldn't normally be any phis in a single-predecessor block.
223 if (I->isPHI()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000224 LLVM_DEBUG(dbgs() << "Can't hoist: " << *I);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000225 return false;
226 }
227
228 // Don't speculate loads. Note that it may be possible and desirable to
229 // speculate GOT or constant pool loads that are guaranteed not to trap,
230 // but we don't support that for now.
231 if (I->mayLoad()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000232 LLVM_DEBUG(dbgs() << "Won't speculate load: " << *I);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000233 return false;
234 }
235
236 // We never speculate stores, so an AA pointer isn't necessary.
237 bool DontMoveAcrossStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000238 if (!I->isSafeToMove(nullptr, DontMoveAcrossStore)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000239 LLVM_DEBUG(dbgs() << "Can't speculate: " << *I);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000240 return false;
241 }
242
243 // Check for any dependencies on Head instructions.
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000244 if (!InstrDependenciesAllowIfConv(&(*I)))
245 return false;
246 }
247 return true;
248}
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000249
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000250/// Check that there is no dependencies preventing if conversion.
251///
252/// If instruction uses any values that are defined in the head basic block,
253/// the defining instructions are added to InsertAfter.
254bool SSAIfConv::InstrDependenciesAllowIfConv(MachineInstr *I) {
255 for (const MachineOperand &MO : I->operands()) {
256 if (MO.isRegMask()) {
257 LLVM_DEBUG(dbgs() << "Won't speculate regmask: " << *I);
258 return false;
259 }
260 if (!MO.isReg())
261 continue;
262 Register Reg = MO.getReg();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000263
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000264 // Remember clobbered regunits.
265 if (MO.isDef() && Register::isPhysicalRegister(Reg))
266 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
267 ClobberedRegUnits.set(*Units);
268
269 if (!MO.readsReg() || !Register::isVirtualRegister(Reg))
270 continue;
271 MachineInstr *DefMI = MRI->getVRegDef(Reg);
272 if (!DefMI || DefMI->getParent() != Head)
273 continue;
274 if (InsertAfter.insert(DefMI).second)
275 LLVM_DEBUG(dbgs() << printMBBReference(*I->getParent()) << " depends on "
276 << *DefMI);
277 if (DefMI->isTerminator()) {
278 LLVM_DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
279 return false;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000280 }
281 }
282 return true;
283}
284
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000285/// canPredicateInstrs - Returns true if all the instructions in MBB can safely
286/// be predicates. The terminators are not considered.
287///
288/// If instructions use any values that are defined in the head basic block,
289/// the defining instructions are added to InsertAfter.
290///
291/// Any clobbered regunits are added to ClobberedRegUnits.
292///
293bool SSAIfConv::canPredicateInstrs(MachineBasicBlock *MBB) {
294 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
295 // get right.
296 if (!MBB->livein_empty()) {
297 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
298 return false;
299 }
300
301 unsigned InstrCount = 0;
302
303 // Check all instructions, except the terminators. It is assumed that
304 // terminators never have side effects or define any used register values.
305 for (MachineBasicBlock::iterator I = MBB->begin(),
306 E = MBB->getFirstTerminator();
307 I != E; ++I) {
308 if (I->isDebugInstr())
309 continue;
310
311 if (++InstrCount > BlockInstrLimit && !Stress) {
312 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
313 << BlockInstrLimit << " instructions.\n");
314 return false;
315 }
316
317 // There shouldn't normally be any phis in a single-predecessor block.
318 if (I->isPHI()) {
319 LLVM_DEBUG(dbgs() << "Can't predicate: " << *I);
320 return false;
321 }
322
323 // Check that instruction is predicable and that it is not already
324 // predicated.
325 if (!TII->isPredicable(*I) || TII->isPredicated(*I)) {
326 return false;
327 }
328
329 // Check for any dependencies on Head instructions.
330 if (!InstrDependenciesAllowIfConv(&(*I)))
331 return false;
332 }
333 return true;
334}
335
336// Apply predicate to all instructions in the machine block.
337void SSAIfConv::PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate) {
338 auto Condition = Cond;
339 if (ReversePredicate)
340 TII->reverseBranchCondition(Condition);
341 // Terminators don't need to be predicated as they will be removed.
342 for (MachineBasicBlock::iterator I = MBB->begin(),
343 E = MBB->getFirstTerminator();
344 I != E; ++I) {
345 if (I->isDebugInstr())
346 continue;
347 TII->PredicateInstruction(*I, Condition);
348 }
349}
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000350
351/// Find an insertion point in Head for the speculated instructions. The
352/// insertion point must be:
353///
354/// 1. Before any terminators.
355/// 2. After any instructions in InsertAfter.
356/// 3. Not have any clobbered regunits live.
357///
358/// This function sets InsertionPoint and returns true when successful, it
359/// returns false if no valid insertion point could be found.
360///
361bool SSAIfConv::findInsertionPoint() {
362 // Keep track of live regunits before the current position.
363 // Only track RegUnits that are also in ClobberedRegUnits.
364 LiveRegUnits.clear();
365 SmallVector<unsigned, 8> Reads;
366 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
367 MachineBasicBlock::iterator I = Head->end();
368 MachineBasicBlock::iterator B = Head->begin();
369 while (I != B) {
370 --I;
371 // Some of the conditional code depends in I.
Duncan P. N. Exon Smith395bd9c2016-02-22 02:53:42 +0000372 if (InsertAfter.count(&*I)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000373 LLVM_DEBUG(dbgs() << "Can't insert code after " << *I);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000374 return false;
375 }
376
377 // Update live regunits.
Matthias Braune41e1462015-05-29 02:56:46 +0000378 for (const MachineOperand &MO : I->operands()) {
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000379 // We're ignoring regmask operands. That is conservatively correct.
Matthias Braune41e1462015-05-29 02:56:46 +0000380 if (!MO.isReg())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000381 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +0000382 Register Reg = MO.getReg();
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000383 if (!Register::isPhysicalRegister(Reg))
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000384 continue;
385 // I clobbers Reg, so it isn't live before I.
Matthias Braune41e1462015-05-29 02:56:46 +0000386 if (MO.isDef())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000387 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
388 LiveRegUnits.erase(*Units);
389 // Unless I reads Reg.
Matthias Braune41e1462015-05-29 02:56:46 +0000390 if (MO.readsReg())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000391 Reads.push_back(Reg);
392 }
393 // Anything read by I is live before I.
394 while (!Reads.empty())
395 for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
396 ++Units)
397 if (ClobberedRegUnits.test(*Units))
398 LiveRegUnits.insert(*Units);
399
400 // We can't insert before a terminator.
401 if (I != FirstTerm && I->isTerminator())
402 continue;
403
404 // Some of the clobbered registers are live before I, not a valid insertion
405 // point.
406 if (!LiveRegUnits.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000407 LLVM_DEBUG({
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000408 dbgs() << "Would clobber";
409 for (SparseSet<unsigned>::const_iterator
410 i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000411 dbgs() << ' ' << printRegUnit(*i, TRI);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000412 dbgs() << " live before " << *I;
413 });
414 continue;
415 }
416
417 // This is a valid insertion point.
418 InsertionPoint = I;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000419 LLVM_DEBUG(dbgs() << "Can insert before " << *I);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000420 return true;
421 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000422 LLVM_DEBUG(dbgs() << "No legal insertion point found.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000423 return false;
424}
425
426
427
428/// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
429/// a potential candidate for if-conversion. Fill out the internal state.
430///
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000431bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB, bool Predicate) {
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000432 Head = MBB;
Craig Topperc0196b12014-04-14 00:51:57 +0000433 TBB = FBB = Tail = nullptr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000434
435 if (Head->succ_size() != 2)
436 return false;
437 MachineBasicBlock *Succ0 = Head->succ_begin()[0];
438 MachineBasicBlock *Succ1 = Head->succ_begin()[1];
439
440 // Canonicalize so Succ0 has MBB as its single predecessor.
441 if (Succ0->pred_size() != 1)
442 std::swap(Succ0, Succ1);
443
444 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
445 return false;
446
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000447 Tail = Succ0->succ_begin()[0];
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000448
449 // This is not a triangle.
450 if (Tail != Succ1) {
451 // Check for a diamond. We won't deal with any critical edges.
452 if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
453 Succ1->succ_begin()[0] != Tail)
454 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000455 LLVM_DEBUG(dbgs() << "\nDiamond: " << printMBBReference(*Head) << " -> "
456 << printMBBReference(*Succ0) << "/"
457 << printMBBReference(*Succ1) << " -> "
458 << printMBBReference(*Tail) << '\n');
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000459
460 // Live-in physregs are tricky to get right when speculating code.
461 if (!Tail->livein_empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000462 LLVM_DEBUG(dbgs() << "Tail has live-ins.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000463 return false;
464 }
465 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000466 LLVM_DEBUG(dbgs() << "\nTriangle: " << printMBBReference(*Head) << " -> "
467 << printMBBReference(*Succ0) << " -> "
468 << printMBBReference(*Tail) << '\n');
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000469 }
470
471 // This is a triangle or a diamond.
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000472 // Skip if we cannot predicate and there are no phis skip as there must be
473 // side effects that can only be handled with predication.
474 if (!Predicate && (Tail->empty() || !Tail->front().isPHI())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000475 LLVM_DEBUG(dbgs() << "No phis in tail.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000476 return false;
477 }
478
479 // The branch we're looking to eliminate must be analyzable.
480 Cond.clear();
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000481 if (TII->analyzeBranch(*Head, TBB, FBB, Cond)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000482 LLVM_DEBUG(dbgs() << "Branch not analyzable.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000483 return false;
484 }
485
486 // This is weird, probably some sort of degenerate CFG.
487 if (!TBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000488 LLVM_DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000489 return false;
490 }
491
Eli Friedman295e3462019-01-15 00:19:46 +0000492 // Make sure the analyzed branch is conditional; one of the successors
493 // could be a landing pad. (Empty landing pads can be generated on Windows.)
494 if (Cond.empty()) {
495 LLVM_DEBUG(dbgs() << "AnalyzeBranch found an unconditional branch.\n");
496 return false;
497 }
498
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000499 // AnalyzeBranch doesn't set FBB on a fall-through branch.
500 // Make sure it is always set.
501 FBB = TBB == Succ0 ? Succ1 : Succ0;
502
503 // Any phis in the tail block must be convertible to selects.
504 PHIs.clear();
Jakob Stoklund Olesen0a990622012-08-10 20:19:17 +0000505 MachineBasicBlock *TPred = getTPred();
506 MachineBasicBlock *FPred = getFPred();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000507 for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
508 I != E && I->isPHI(); ++I) {
509 PHIs.push_back(&*I);
510 PHIInfo &PI = PHIs.back();
511 // Find PHI operands corresponding to TPred and FPred.
512 for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
513 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
514 PI.TReg = PI.PHI->getOperand(i).getReg();
515 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
516 PI.FReg = PI.PHI->getOperand(i).getReg();
517 }
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000518 assert(Register::isVirtualRegister(PI.TReg) && "Bad PHI");
519 assert(Register::isVirtualRegister(PI.FReg) && "Bad PHI");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000520
521 // Get target information.
522 if (!TII->canInsertSelect(*Head, Cond, PI.TReg, PI.FReg,
523 PI.CondCycles, PI.TCycles, PI.FCycles)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000524 LLVM_DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000525 return false;
526 }
527 }
528
529 // Check that the conditional instructions can be speculated.
530 InsertAfter.clear();
531 ClobberedRegUnits.reset();
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000532 if (Predicate) {
533 if (TBB != Tail && !canPredicateInstrs(TBB))
534 return false;
535 if (FBB != Tail && !canPredicateInstrs(FBB))
536 return false;
537 } else {
538 if (TBB != Tail && !canSpeculateInstrs(TBB))
539 return false;
540 if (FBB != Tail && !canSpeculateInstrs(FBB))
541 return false;
542 }
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000543
544 // Try to find a valid insertion point for the speculated instructions in the
545 // head basic block.
546 if (!findInsertionPoint())
547 return false;
548
Jakob Stoklund Olesend0af1d92012-08-13 21:03:27 +0000549 if (isTriangle())
550 ++NumTrianglesSeen;
551 else
552 ++NumDiamondsSeen;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000553 return true;
554}
555
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000556/// replacePHIInstrs - Completely replace PHI instructions with selects.
557/// This is possible when the only Tail predecessors are the if-converted
558/// blocks.
559void SSAIfConv::replacePHIInstrs() {
560 assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000561 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
562 assert(FirstTerm != Head->end() && "No terminators");
563 DebugLoc HeadDL = FirstTerm->getDebugLoc();
564
565 // Convert all PHIs to select instructions inserted before FirstTerm.
566 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
567 PHIInfo &PI = PHIs[i];
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000568 LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
Daniel Sanders0c476112019-08-15 19:22:08 +0000569 Register DstReg = PI.PHI->getOperand(0).getReg();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000570 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000571 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000572 PI.PHI->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +0000573 PI.PHI = nullptr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000574 }
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000575}
576
577/// rewritePHIOperands - When there are additional Tail predecessors, insert
578/// select instructions in Head and rewrite PHI operands to use the selects.
579/// Keep the PHI instructions in Tail to handle the other predecessors.
580void SSAIfConv::rewritePHIOperands() {
581 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
582 assert(FirstTerm != Head->end() && "No terminators");
583 DebugLoc HeadDL = FirstTerm->getDebugLoc();
584
585 // Convert all PHIs to select instructions inserted before FirstTerm.
586 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
587 PHIInfo &PI = PHIs[i];
Yi Jiange0b34992015-06-18 22:34:09 +0000588 unsigned DstReg = 0;
Junmo Park67bb3f12016-01-29 01:39:39 +0000589
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000590 LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
Yi Jiange0b34992015-06-18 22:34:09 +0000591 if (PI.TReg == PI.FReg) {
592 // We do not need the select instruction if both incoming values are
593 // equal.
594 DstReg = PI.TReg;
595 } else {
Daniel Sanders0c476112019-08-15 19:22:08 +0000596 Register PHIDst = PI.PHI->getOperand(0).getReg();
Yi Jiange0b34992015-06-18 22:34:09 +0000597 DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
598 TII->insertSelect(*Head, FirstTerm, HeadDL,
599 DstReg, Cond, PI.TReg, PI.FReg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000600 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
Yi Jiange0b34992015-06-18 22:34:09 +0000601 }
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000602
603 // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
604 for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
605 MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
606 if (MBB == getTPred()) {
607 PI.PHI->getOperand(i-1).setMBB(Head);
608 PI.PHI->getOperand(i-2).setReg(DstReg);
609 } else if (MBB == getFPred()) {
610 PI.PHI->RemoveOperand(i-1);
611 PI.PHI->RemoveOperand(i-2);
612 }
613 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000614 LLVM_DEBUG(dbgs() << " --> " << *PI.PHI);
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000615 }
616}
617
618/// convertIf - Execute the if conversion after canConvertIf has determined the
619/// feasibility.
620///
621/// Any basic blocks erased will be added to RemovedBlocks.
622///
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000623void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks,
624 bool Predicate) {
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000625 assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
626
Jakob Stoklund Olesend0af1d92012-08-13 21:03:27 +0000627 // Update statistics.
628 if (isTriangle())
629 ++NumTrianglesConv;
630 else
631 ++NumDiamondsConv;
632
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000633 // Move all instructions into Head, except for the terminators.
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000634 if (TBB != Tail) {
635 if (Predicate)
636 PredicateBlock(TBB, /*ReversePredicate=*/false);
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000637 Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000638 }
639 if (FBB != Tail) {
640 if (Predicate)
641 PredicateBlock(FBB, /*ReversePredicate=*/true);
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000642 Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000643 }
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000644 // Are there extra Tail predecessors?
645 bool ExtraPreds = Tail->pred_size() != 2;
646 if (ExtraPreds)
647 rewritePHIOperands();
648 else
649 replacePHIInstrs();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000650
651 // Fix up the CFG, temporarily leave Head without any successors.
652 Head->removeSuccessor(TBB);
Cong Houc1069892015-12-13 09:26:17 +0000653 Head->removeSuccessor(FBB, true);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000654 if (TBB != Tail)
Cong Houc1069892015-12-13 09:26:17 +0000655 TBB->removeSuccessor(Tail, true);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000656 if (FBB != Tail)
Cong Houc1069892015-12-13 09:26:17 +0000657 FBB->removeSuccessor(Tail, true);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000658
659 // Fix up Head's terminators.
660 // It should become a single branch or a fallthrough.
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000661 DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000662 TII->removeBranch(*Head);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000663
664 // Erase the now empty conditional blocks. It is likely that Head can fall
665 // through to Tail, and we can join the two blocks.
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000666 if (TBB != Tail) {
667 RemovedBlocks.push_back(TBB);
668 TBB->eraseFromParent();
669 }
670 if (FBB != Tail) {
671 RemovedBlocks.push_back(FBB);
672 FBB->eraseFromParent();
673 }
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000674
675 assert(Head->succ_empty() && "Additional head successors?");
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000676 if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000677 // Splice Tail onto the end of Head.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000678 LLVM_DEBUG(dbgs() << "Joining tail " << printMBBReference(*Tail)
679 << " into head " << printMBBReference(*Head) << '\n');
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000680 Head->splice(Head->end(), Tail,
681 Tail->begin(), Tail->end());
682 Head->transferSuccessorsAndUpdatePHIs(Tail);
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000683 RemovedBlocks.push_back(Tail);
684 Tail->eraseFromParent();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000685 } else {
686 // We need a branch to Tail, let code placement work it out later.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000687 LLVM_DEBUG(dbgs() << "Converting to unconditional branch.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000688 SmallVector<MachineOperand, 0> EmptyCond;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000689 TII->insertBranch(*Head, Tail, nullptr, EmptyCond, HeadDL);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000690 Head->addSuccessor(Tail);
691 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000692 LLVM_DEBUG(dbgs() << *Head);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000693}
694
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000695//===----------------------------------------------------------------------===//
696// EarlyIfConverter Pass
697//===----------------------------------------------------------------------===//
698
699namespace {
700class EarlyIfConverter : public MachineFunctionPass {
701 const TargetInstrInfo *TII;
702 const TargetRegisterInfo *TRI;
Pete Cooper11759452014-09-02 17:43:54 +0000703 MCSchedModel SchedModel;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000704 MachineRegisterInfo *MRI;
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000705 MachineDominatorTree *DomTree;
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000706 MachineLoopInfo *Loops;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000707 MachineTraceMetrics *Traces;
708 MachineTraceMetrics::Ensemble *MinInstr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000709 SSAIfConv IfConv;
710
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000711public:
712 static char ID;
713 EarlyIfConverter() : MachineFunctionPass(ID) {}
Craig Topper4584cd52014-03-07 09:26:03 +0000714 void getAnalysisUsage(AnalysisUsage &AU) const override;
715 bool runOnMachineFunction(MachineFunction &MF) override;
Mehdi Amini117296c2016-10-01 02:56:57 +0000716 StringRef getPassName() const override { return "Early If-Conversion"; }
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000717
718private:
719 bool tryConvertIf(MachineBasicBlock*);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000720 void invalidateTraces();
721 bool shouldConvertIf();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000722};
723} // end anonymous namespace
724
725char EarlyIfConverter::ID = 0;
726char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
727
Matthias Braun1527baa2017-05-25 21:26:32 +0000728INITIALIZE_PASS_BEGIN(EarlyIfConverter, DEBUG_TYPE,
729 "Early If Converter", false, false)
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000730INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000731INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000732INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
Matthias Braun1527baa2017-05-25 21:26:32 +0000733INITIALIZE_PASS_END(EarlyIfConverter, DEBUG_TYPE,
734 "Early If Converter", false, false)
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000735
736void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
737 AU.addRequired<MachineBranchProbabilityInfo>();
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000738 AU.addRequired<MachineDominatorTree>();
739 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000740 AU.addRequired<MachineLoopInfo>();
741 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000742 AU.addRequired<MachineTraceMetrics>();
743 AU.addPreserved<MachineTraceMetrics>();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000744 MachineFunctionPass::getAnalysisUsage(AU);
745}
746
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000747namespace {
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000748/// Update the dominator tree after if-conversion erased some blocks.
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000749void updateDomTree(MachineDominatorTree *DomTree, const SSAIfConv &IfConv,
750 ArrayRef<MachineBasicBlock *> Removed) {
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000751 // convertIf can remove TBB, FBB, and Tail can be merged into Head.
752 // TBB and FBB should not dominate any blocks.
753 // Tail children should be transferred to Head.
754 MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000755 for (auto B : Removed) {
756 MachineDomTreeNode *Node = DomTree->getNode(B);
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000757 assert(Node != HeadNode && "Cannot erase the head node");
758 while (Node->getNumChildren()) {
759 assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
760 DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode);
761 }
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000762 DomTree->eraseNode(B);
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000763 }
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000764}
765
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000766/// Update LoopInfo after if-conversion.
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000767void updateLoops(MachineLoopInfo *Loops,
768 ArrayRef<MachineBasicBlock *> Removed) {
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000769 if (!Loops)
770 return;
771 // If-conversion doesn't change loop structure, and it doesn't mess with back
772 // edges, so updating LoopInfo is simply removing the dead blocks.
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000773 for (auto B : Removed)
774 Loops->removeBlock(B);
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000775}
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000776} // namespace
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000777
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000778/// Invalidate MachineTraceMetrics before if-conversion.
779void EarlyIfConverter::invalidateTraces() {
Jakob Stoklund Olesena12a7d52012-07-30 20:57:50 +0000780 Traces->verifyAnalysis();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000781 Traces->invalidate(IfConv.Head);
782 Traces->invalidate(IfConv.Tail);
783 Traces->invalidate(IfConv.TBB);
784 Traces->invalidate(IfConv.FBB);
Jakob Stoklund Olesena12a7d52012-07-30 20:57:50 +0000785 Traces->verifyAnalysis();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000786}
787
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000788// Adjust cycles with downward saturation.
789static unsigned adjCycles(unsigned Cyc, int Delta) {
790 if (Delta < 0 && Cyc + Delta > Cyc)
791 return 0;
792 return Cyc + Delta;
793}
794
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000795/// Apply cost model and heuristics to the if-conversion in IfConv.
796/// Return true if the conversion is a good idea.
797///
798bool EarlyIfConverter::shouldConvertIf() {
Jakob Stoklund Olesenfa8a26f2012-08-08 18:24:23 +0000799 // Stress testing mode disables all cost considerations.
800 if (Stress)
801 return true;
802
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000803 if (!MinInstr)
804 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +0000805
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000806 MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
807 MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000808 LLVM_DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000809 unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
810 FBBTrace.getCriticalPath());
811
812 // Set a somewhat arbitrary limit on the critical path extension we accept.
Pete Cooper11759452014-09-02 17:43:54 +0000813 unsigned CritLimit = SchedModel.MispredictPenalty/2;
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000814
815 // If-conversion only makes sense when there is unexploited ILP. Compute the
816 // maximum-ILP resource length of the trace after if-conversion. Compare it
817 // to the shortest critical path.
818 SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
819 if (IfConv.TBB != IfConv.Tail)
820 ExtraBlocks.push_back(IfConv.TBB);
821 unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000822 LLVM_DEBUG(dbgs() << "Resource length " << ResLength
823 << ", minimal critical path " << MinCrit << '\n');
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000824 if (ResLength > MinCrit + CritLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000825 LLVM_DEBUG(dbgs() << "Not enough available ILP.\n");
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +0000826 return false;
827 }
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000828
829 // Assume that the depth of the first head terminator will also be the depth
830 // of the select instruction inserted, as determined by the flag dependency.
831 // TBB / FBB data dependencies may delay the select even more.
832 MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
833 unsigned BranchDepth =
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000834 HeadTrace.getInstrCycles(*IfConv.Head->getFirstTerminator()).Depth;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000835 LLVM_DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000836
837 // Look at all the tail phis, and compute the critical path extension caused
838 // by inserting select instructions.
839 MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
840 for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
841 SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000842 unsigned Slack = TailTrace.getInstrSlack(*PI.PHI);
843 unsigned MaxDepth = Slack + TailTrace.getInstrCycles(*PI.PHI).Depth;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000844 LLVM_DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000845
846 // The condition is pulled into the critical path.
847 unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
848 if (CondDepth > MaxDepth) {
849 unsigned Extra = CondDepth - MaxDepth;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000850 LLVM_DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000851 if (Extra > CritLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000852 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000853 return false;
854 }
855 }
856
857 // The TBB value is pulled into the critical path.
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000858 unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(*PI.PHI), PI.TCycles);
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000859 if (TDepth > MaxDepth) {
860 unsigned Extra = TDepth - MaxDepth;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000861 LLVM_DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000862 if (Extra > CritLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000863 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000864 return false;
865 }
866 }
867
868 // The FBB value is pulled into the critical path.
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000869 unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(*PI.PHI), PI.FCycles);
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000870 if (FDepth > MaxDepth) {
871 unsigned Extra = FDepth - MaxDepth;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000872 LLVM_DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000873 if (Extra > CritLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000874 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000875 return false;
876 }
877 }
878 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000879 return true;
880}
881
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000882/// Attempt repeated if-conversion on MBB, return true if successful.
883///
884bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
885 bool Changed = false;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000886 while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000887 // If-convert MBB and update analyses.
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000888 invalidateTraces();
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000889 SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
890 IfConv.convertIf(RemovedBlocks);
891 Changed = true;
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000892 updateDomTree(DomTree, IfConv, RemovedBlocks);
893 updateLoops(Loops, RemovedBlocks);
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000894 }
895 return Changed;
896}
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000897
898bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000899 LLVM_DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
900 << "********** Function: " << MF.getName() << '\n');
Matthias Braunf1caa282017-12-15 22:22:58 +0000901 if (skipFunction(MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +0000902 return false;
903
Eric Christopher6b0fcfe2014-05-21 23:40:26 +0000904 // Only run if conversion if the target wants it.
Eric Christopher3d4276f2015-01-27 07:31:29 +0000905 const TargetSubtargetInfo &STI = MF.getSubtarget();
906 if (!STI.enableEarlyIfConversion())
Eric Christopher9eff5178f2014-05-22 17:49:33 +0000907 return false;
Eric Christopher6b0fcfe2014-05-21 23:40:26 +0000908
Eric Christopher3d4276f2015-01-27 07:31:29 +0000909 TII = STI.getInstrInfo();
910 TRI = STI.getRegisterInfo();
911 SchedModel = STI.getSchedModel();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000912 MRI = &MF.getRegInfo();
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000913 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000914 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000915 Traces = &getAnalysis<MachineTraceMetrics>();
Craig Topperc0196b12014-04-14 00:51:57 +0000916 MinInstr = nullptr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000917
918 bool Changed = false;
919 IfConv.runOnMachineFunction(MF);
920
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000921 // Visit blocks in dominator tree post-order. The post-order enables nested
922 // if-conversion in a single pass. The tryConvertIf() function may erase
923 // blocks, but only blocks dominated by the head block. This makes it safe to
924 // update the dominator tree while the post-order iterator is still active.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000925 for (auto DomNode : post_order(DomTree))
926 if (tryConvertIf(DomNode->getBlock()))
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000927 Changed = true;
928
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000929 return Changed;
930}
Thomas Raouxbe699bf2019-08-20 15:54:59 +0000931
932//===----------------------------------------------------------------------===//
933// EarlyIfPredicator Pass
934//===----------------------------------------------------------------------===//
935
936namespace {
937class EarlyIfPredicator : public MachineFunctionPass {
938 const TargetInstrInfo *TII;
939 const TargetRegisterInfo *TRI;
940 TargetSchedModel SchedModel;
941 MachineRegisterInfo *MRI;
942 MachineDominatorTree *DomTree;
943 MachineLoopInfo *Loops;
944 SSAIfConv IfConv;
945
946public:
947 static char ID;
948 EarlyIfPredicator() : MachineFunctionPass(ID) {}
949 void getAnalysisUsage(AnalysisUsage &AU) const override;
950 bool runOnMachineFunction(MachineFunction &MF) override;
951 StringRef getPassName() const override { return "Early If-predicator"; }
952
953protected:
954 bool tryConvertIf(MachineBasicBlock *);
955 bool shouldConvertIf();
956};
957} // end anonymous namespace
958
959#undef DEBUG_TYPE
960#define DEBUG_TYPE "early-if-predicator"
961
962char EarlyIfPredicator::ID = 0;
963char &llvm::EarlyIfPredicatorID = EarlyIfPredicator::ID;
964
965INITIALIZE_PASS_BEGIN(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator",
966 false, false)
967INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
968INITIALIZE_PASS_END(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator", false,
969 false)
970
971void EarlyIfPredicator::getAnalysisUsage(AnalysisUsage &AU) const {
972 AU.addRequired<MachineDominatorTree>();
973 AU.addPreserved<MachineDominatorTree>();
974 AU.addRequired<MachineLoopInfo>();
975 AU.addPreserved<MachineLoopInfo>();
976 MachineFunctionPass::getAnalysisUsage(AU);
977}
978
979/// Apply the target heuristic to decide if the transformation is profitable.
980bool EarlyIfPredicator::shouldConvertIf() {
981 if (IfConv.isTriangle()) {
982 MachineBasicBlock &IfBlock =
983 (IfConv.TBB == IfConv.Tail) ? *IfConv.FBB : *IfConv.TBB;
984
985 unsigned ExtraPredCost = 0;
986 unsigned Cycles = 0;
987 for (MachineInstr &I : IfBlock) {
988 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
989 if (NumCycles > 1)
990 Cycles += NumCycles - 1;
991 ExtraPredCost += TII->getPredicationCost(I);
992 }
993
994 return TII->isProfitableToIfCvt(IfBlock, Cycles, ExtraPredCost,
995 BranchProbability::getUnknown());
996 }
997 unsigned TExtra = 0;
998 unsigned FExtra = 0;
999 unsigned TCycle = 0;
1000 unsigned FCycle = 0;
1001 for (MachineInstr &I : *IfConv.TBB) {
1002 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1003 if (NumCycles > 1)
1004 TCycle += NumCycles - 1;
1005 TExtra += TII->getPredicationCost(I);
1006 }
1007 for (MachineInstr &I : *IfConv.FBB) {
1008 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1009 if (NumCycles > 1)
1010 FCycle += NumCycles - 1;
1011 FExtra += TII->getPredicationCost(I);
1012 }
1013 return TII->isProfitableToIfCvt(*IfConv.TBB, TCycle, TExtra, *IfConv.FBB,
1014 FCycle, FExtra,
1015 BranchProbability::getUnknown());
1016}
1017
1018/// Attempt repeated if-conversion on MBB, return true if successful.
1019///
1020bool EarlyIfPredicator::tryConvertIf(MachineBasicBlock *MBB) {
1021 bool Changed = false;
1022 while (IfConv.canConvertIf(MBB, /*Predicate*/ true) && shouldConvertIf()) {
1023 // If-convert MBB and update analyses.
1024 SmallVector<MachineBasicBlock *, 4> RemovedBlocks;
1025 IfConv.convertIf(RemovedBlocks, /*Predicate*/ true);
1026 Changed = true;
1027 updateDomTree(DomTree, IfConv, RemovedBlocks);
1028 updateLoops(Loops, RemovedBlocks);
1029 }
1030 return Changed;
1031}
1032
1033bool EarlyIfPredicator::runOnMachineFunction(MachineFunction &MF) {
1034 LLVM_DEBUG(dbgs() << "********** EARLY IF-PREDICATOR **********\n"
1035 << "********** Function: " << MF.getName() << '\n');
1036 if (skipFunction(MF.getFunction()))
1037 return false;
1038
1039 const TargetSubtargetInfo &STI = MF.getSubtarget();
1040 TII = STI.getInstrInfo();
1041 TRI = STI.getRegisterInfo();
1042 MRI = &MF.getRegInfo();
1043 SchedModel.init(&STI);
1044 DomTree = &getAnalysis<MachineDominatorTree>();
1045 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
1046
1047 bool Changed = false;
1048 IfConv.runOnMachineFunction(MF);
1049
1050 // Visit blocks in dominator tree post-order. The post-order enables nested
1051 // if-conversion in a single pass. The tryConvertIf() function may erase
1052 // blocks, but only blocks dominated by the head block. This makes it safe to
1053 // update the dominator tree while the post-order iterator is still active.
1054 for (auto DomNode : post_order(DomTree))
1055 if (tryConvertIf(DomNode->getBlock()))
1056 Changed = true;
1057
1058 return Changed;
1059}