1 //===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
2 //
3 // 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
6 //
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 
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SparseSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/MachineTraceMetrics.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/TargetInstrInfo.h"
35 #include "llvm/CodeGen/TargetRegisterInfo.h"
36 #include "llvm/CodeGen/TargetSubtargetInfo.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "early-ifcvt"
45 
46 // Absolute maximum number of instructions allowed per speculated block.
47 // This bypasses all other heuristics, so it should be set fairly high.
48 static cl::opt<unsigned>
49 BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
50   cl::desc("Maximum number of instructions per speculated block."));
51 
52 // Stress testing mode - disable heuristics.
53 static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
54   cl::desc("Turn all knobs to 11"));
55 
56 STATISTIC(NumDiamondsSeen,  "Number of diamonds");
57 STATISTIC(NumDiamondsConv,  "Number of diamonds converted");
58 STATISTIC(NumTrianglesSeen, "Number of triangles");
59 STATISTIC(NumTrianglesConv, "Number of triangles converted");
60 
61 //===----------------------------------------------------------------------===//
62 //                                 SSAIfConv
63 //===----------------------------------------------------------------------===//
64 //
65 // The SSAIfConv class performs if-conversion on SSA form machine code after
66 // determining if it is possible. The class contains no heuristics; external
67 // code should be used to determine when if-conversion is a good idea.
68 //
69 // SSAIfConv can convert both triangles and diamonds:
70 //
71 //   Triangle: Head              Diamond: Head
72 //              | \                       /  \_
73 //              |  \                     /    |
74 //              |  [TF]BB              FBB    TBB
75 //              |  /                     \    /
76 //              | /                       \  /
77 //             Tail                       Tail
78 //
79 // Instructions in the conditional blocks TBB and/or FBB are spliced into the
80 // Head block, and phis in the Tail block are converted to select instructions.
81 //
82 namespace {
83 class SSAIfConv {
84   const TargetInstrInfo *TII;
85   const TargetRegisterInfo *TRI;
86   MachineRegisterInfo *MRI;
87 
88 public:
89   /// The block containing the conditional branch.
90   MachineBasicBlock *Head;
91 
92   /// The block containing phis after the if-then-else.
93   MachineBasicBlock *Tail;
94 
95   /// The 'true' conditional block as determined by analyzeBranch.
96   MachineBasicBlock *TBB;
97 
98   /// The 'false' conditional block as determined by analyzeBranch.
99   MachineBasicBlock *FBB;
100 
101   /// isTriangle - When there is no 'else' block, either TBB or FBB will be
102   /// equal to Tail.
103   bool isTriangle() const { return TBB == Tail || FBB == Tail; }
104 
105   /// Returns the Tail predecessor for the True side.
106   MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
107 
108   /// Returns the Tail predecessor for the  False side.
109   MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
110 
111   /// Information about each phi in the Tail block.
112   struct PHIInfo {
113     MachineInstr *PHI;
114     unsigned TReg, FReg;
115     // Latencies from Cond+Branch, TReg, and FReg to DstReg.
116     int CondCycles, TCycles, FCycles;
117 
118     PHIInfo(MachineInstr *phi)
119       : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
120   };
121 
122   SmallVector<PHIInfo, 8> PHIs;
123 
124 private:
125   /// The branch condition determined by analyzeBranch.
126   SmallVector<MachineOperand, 4> Cond;
127 
128   /// Instructions in Head that define values used by the conditional blocks.
129   /// The hoisted instructions must be inserted after these instructions.
130   SmallPtrSet<MachineInstr*, 8> InsertAfter;
131 
132   /// Register units clobbered by the conditional blocks.
133   BitVector ClobberedRegUnits;
134 
135   // Scratch pad for findInsertionPoint.
136   SparseSet<unsigned> LiveRegUnits;
137 
138   /// Insertion point in Head for speculatively executed instructions form TBB
139   /// and FBB.
140   MachineBasicBlock::iterator InsertionPoint;
141 
142   /// Return true if all non-terminator instructions in MBB can be safely
143   /// speculated.
144   bool canSpeculateInstrs(MachineBasicBlock *MBB);
145 
146   /// Return true if all non-terminator instructions in MBB can be safely
147   /// predicated.
148   bool canPredicateInstrs(MachineBasicBlock *MBB);
149 
150   /// Scan through instruction dependencies and update InsertAfter array.
151   /// Return false if any dependency is incompatible with if conversion.
152   bool InstrDependenciesAllowIfConv(MachineInstr *I);
153 
154   /// Predicate all instructions of the basic block with current condition
155   /// except for terminators. Reverse the condition if ReversePredicate is set.
156   void PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate);
157 
158   /// Find a valid insertion point in Head.
159   bool findInsertionPoint();
160 
161   /// Replace PHI instructions in Tail with selects.
162   void replacePHIInstrs();
163 
164   /// Insert selects and rewrite PHI operands to use them.
165   void rewritePHIOperands();
166 
167 public:
168   /// runOnMachineFunction - Initialize per-function data structures.
169   void runOnMachineFunction(MachineFunction &MF) {
170     TII = MF.getSubtarget().getInstrInfo();
171     TRI = MF.getSubtarget().getRegisterInfo();
172     MRI = &MF.getRegInfo();
173     LiveRegUnits.clear();
174     LiveRegUnits.setUniverse(TRI->getNumRegUnits());
175     ClobberedRegUnits.clear();
176     ClobberedRegUnits.resize(TRI->getNumRegUnits());
177   }
178 
179   /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
180   /// initialize the internal state, and return true.
181   /// If predicate is set try to predicate the block otherwise try to
182   /// speculatively execute it.
183   bool canConvertIf(MachineBasicBlock *MBB, bool Predicate = false);
184 
185   /// convertIf - If-convert the last block passed to canConvertIf(), assuming
186   /// it is possible. Add any erased blocks to RemovedBlocks.
187   void convertIf(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks,
188                  bool Predicate = false);
189 };
190 } // end anonymous namespace
191 
192 
193 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
194 /// be speculated. The terminators are not considered.
195 ///
196 /// If instructions use any values that are defined in the head basic block,
197 /// the defining instructions are added to InsertAfter.
198 ///
199 /// Any clobbered regunits are added to ClobberedRegUnits.
200 ///
201 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
202   // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
203   // get right.
204   if (!MBB->livein_empty()) {
205     LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
206     return false;
207   }
208 
209   unsigned InstrCount = 0;
210 
211   // Check all instructions, except the terminators. It is assumed that
212   // terminators never have side effects or define any used register values.
213   for (MachineBasicBlock::iterator I = MBB->begin(),
214        E = MBB->getFirstTerminator(); I != E; ++I) {
215     if (I->isDebugInstr())
216       continue;
217 
218     if (++InstrCount > BlockInstrLimit && !Stress) {
219       LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
220                         << BlockInstrLimit << " instructions.\n");
221       return false;
222     }
223 
224     // There shouldn't normally be any phis in a single-predecessor block.
225     if (I->isPHI()) {
226       LLVM_DEBUG(dbgs() << "Can't hoist: " << *I);
227       return false;
228     }
229 
230     // Don't speculate loads. Note that it may be possible and desirable to
231     // speculate GOT or constant pool loads that are guaranteed not to trap,
232     // but we don't support that for now.
233     if (I->mayLoad()) {
234       LLVM_DEBUG(dbgs() << "Won't speculate load: " << *I);
235       return false;
236     }
237 
238     // We never speculate stores, so an AA pointer isn't necessary.
239     bool DontMoveAcrossStore = true;
240     if (!I->isSafeToMove(nullptr, DontMoveAcrossStore)) {
241       LLVM_DEBUG(dbgs() << "Can't speculate: " << *I);
242       return false;
243     }
244 
245     // Check for any dependencies on Head instructions.
246     if (!InstrDependenciesAllowIfConv(&(*I)))
247       return false;
248   }
249   return true;
250 }
251 
252 /// Check that there is no dependencies preventing if conversion.
253 ///
254 /// If instruction uses any values that are defined in the head basic block,
255 /// the defining instructions are added to InsertAfter.
256 bool SSAIfConv::InstrDependenciesAllowIfConv(MachineInstr *I) {
257   for (const MachineOperand &MO : I->operands()) {
258     if (MO.isRegMask()) {
259       LLVM_DEBUG(dbgs() << "Won't speculate regmask: " << *I);
260       return false;
261     }
262     if (!MO.isReg())
263       continue;
264     Register Reg = MO.getReg();
265 
266     // Remember clobbered regunits.
267     if (MO.isDef() && Register::isPhysicalRegister(Reg))
268       for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
269         ClobberedRegUnits.set(*Units);
270 
271     if (!MO.readsReg() || !Register::isVirtualRegister(Reg))
272       continue;
273     MachineInstr *DefMI = MRI->getVRegDef(Reg);
274     if (!DefMI || DefMI->getParent() != Head)
275       continue;
276     if (InsertAfter.insert(DefMI).second)
277       LLVM_DEBUG(dbgs() << printMBBReference(*I->getParent()) << " depends on "
278                         << *DefMI);
279     if (DefMI->isTerminator()) {
280       LLVM_DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
281       return false;
282     }
283   }
284   return true;
285 }
286 
287 /// canPredicateInstrs - Returns true if all the instructions in MBB can safely
288 /// be predicates. The terminators are not considered.
289 ///
290 /// If instructions use any values that are defined in the head basic block,
291 /// the defining instructions are added to InsertAfter.
292 ///
293 /// Any clobbered regunits are added to ClobberedRegUnits.
294 ///
295 bool SSAIfConv::canPredicateInstrs(MachineBasicBlock *MBB) {
296   // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
297   // get right.
298   if (!MBB->livein_empty()) {
299     LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
300     return false;
301   }
302 
303   unsigned InstrCount = 0;
304 
305   // Check all instructions, except the terminators. It is assumed that
306   // terminators never have side effects or define any used register values.
307   for (MachineBasicBlock::iterator I = MBB->begin(),
308                                    E = MBB->getFirstTerminator();
309        I != E; ++I) {
310     if (I->isDebugInstr())
311       continue;
312 
313     if (++InstrCount > BlockInstrLimit && !Stress) {
314       LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
315                         << BlockInstrLimit << " instructions.\n");
316       return false;
317     }
318 
319     // There shouldn't normally be any phis in a single-predecessor block.
320     if (I->isPHI()) {
321       LLVM_DEBUG(dbgs() << "Can't predicate: " << *I);
322       return false;
323     }
324 
325     // Check that instruction is predicable and that it is not already
326     // predicated.
327     if (!TII->isPredicable(*I) || TII->isPredicated(*I)) {
328       return false;
329     }
330 
331     // Check for any dependencies on Head instructions.
332     if (!InstrDependenciesAllowIfConv(&(*I)))
333       return false;
334   }
335   return true;
336 }
337 
338 // Apply predicate to all instructions in the machine block.
339 void SSAIfConv::PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate) {
340   auto Condition = Cond;
341   if (ReversePredicate)
342     TII->reverseBranchCondition(Condition);
343   // Terminators don't need to be predicated as they will be removed.
344   for (MachineBasicBlock::iterator I = MBB->begin(),
345                                    E = MBB->getFirstTerminator();
346        I != E; ++I) {
347     if (I->isDebugInstr())
348       continue;
349     TII->PredicateInstruction(*I, Condition);
350   }
351 }
352 
353 /// Find an insertion point in Head for the speculated instructions. The
354 /// insertion point must be:
355 ///
356 /// 1. Before any terminators.
357 /// 2. After any instructions in InsertAfter.
358 /// 3. Not have any clobbered regunits live.
359 ///
360 /// This function sets InsertionPoint and returns true when successful, it
361 /// returns false if no valid insertion point could be found.
362 ///
363 bool SSAIfConv::findInsertionPoint() {
364   // Keep track of live regunits before the current position.
365   // Only track RegUnits that are also in ClobberedRegUnits.
366   LiveRegUnits.clear();
367   SmallVector<unsigned, 8> Reads;
368   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
369   MachineBasicBlock::iterator I = Head->end();
370   MachineBasicBlock::iterator B = Head->begin();
371   while (I != B) {
372     --I;
373     // Some of the conditional code depends in I.
374     if (InsertAfter.count(&*I)) {
375       LLVM_DEBUG(dbgs() << "Can't insert code after " << *I);
376       return false;
377     }
378 
379     // Update live regunits.
380     for (const MachineOperand &MO : I->operands()) {
381       // We're ignoring regmask operands. That is conservatively correct.
382       if (!MO.isReg())
383         continue;
384       Register Reg = MO.getReg();
385       if (!Register::isPhysicalRegister(Reg))
386         continue;
387       // I clobbers Reg, so it isn't live before I.
388       if (MO.isDef())
389         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
390           LiveRegUnits.erase(*Units);
391       // Unless I reads Reg.
392       if (MO.readsReg())
393         Reads.push_back(Reg);
394     }
395     // Anything read by I is live before I.
396     while (!Reads.empty())
397       for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
398            ++Units)
399         if (ClobberedRegUnits.test(*Units))
400           LiveRegUnits.insert(*Units);
401 
402     // We can't insert before a terminator.
403     if (I != FirstTerm && I->isTerminator())
404       continue;
405 
406     // Some of the clobbered registers are live before I, not a valid insertion
407     // point.
408     if (!LiveRegUnits.empty()) {
409       LLVM_DEBUG({
410         dbgs() << "Would clobber";
411         for (SparseSet<unsigned>::const_iterator
412              i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
413           dbgs() << ' ' << printRegUnit(*i, TRI);
414         dbgs() << " live before " << *I;
415       });
416       continue;
417     }
418 
419     // This is a valid insertion point.
420     InsertionPoint = I;
421     LLVM_DEBUG(dbgs() << "Can insert before " << *I);
422     return true;
423   }
424   LLVM_DEBUG(dbgs() << "No legal insertion point found.\n");
425   return false;
426 }
427 
428 
429 
430 /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
431 /// a potential candidate for if-conversion. Fill out the internal state.
432 ///
433 bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB, bool Predicate) {
434   Head = MBB;
435   TBB = FBB = Tail = nullptr;
436 
437   if (Head->succ_size() != 2)
438     return false;
439   MachineBasicBlock *Succ0 = Head->succ_begin()[0];
440   MachineBasicBlock *Succ1 = Head->succ_begin()[1];
441 
442   // Canonicalize so Succ0 has MBB as its single predecessor.
443   if (Succ0->pred_size() != 1)
444     std::swap(Succ0, Succ1);
445 
446   if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
447     return false;
448 
449   Tail = Succ0->succ_begin()[0];
450 
451   // This is not a triangle.
452   if (Tail != Succ1) {
453     // Check for a diamond. We won't deal with any critical edges.
454     if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
455         Succ1->succ_begin()[0] != Tail)
456       return false;
457     LLVM_DEBUG(dbgs() << "\nDiamond: " << printMBBReference(*Head) << " -> "
458                       << printMBBReference(*Succ0) << "/"
459                       << printMBBReference(*Succ1) << " -> "
460                       << printMBBReference(*Tail) << '\n');
461 
462     // Live-in physregs are tricky to get right when speculating code.
463     if (!Tail->livein_empty()) {
464       LLVM_DEBUG(dbgs() << "Tail has live-ins.\n");
465       return false;
466     }
467   } else {
468     LLVM_DEBUG(dbgs() << "\nTriangle: " << printMBBReference(*Head) << " -> "
469                       << printMBBReference(*Succ0) << " -> "
470                       << printMBBReference(*Tail) << '\n');
471   }
472 
473   // This is a triangle or a diamond.
474   // Skip if we cannot predicate and there are no phis skip as there must be
475   // side effects that can only be handled with predication.
476   if (!Predicate && (Tail->empty() || !Tail->front().isPHI())) {
477     LLVM_DEBUG(dbgs() << "No phis in tail.\n");
478     return false;
479   }
480 
481   // The branch we're looking to eliminate must be analyzable.
482   Cond.clear();
483   if (TII->analyzeBranch(*Head, TBB, FBB, Cond)) {
484     LLVM_DEBUG(dbgs() << "Branch not analyzable.\n");
485     return false;
486   }
487 
488   // This is weird, probably some sort of degenerate CFG.
489   if (!TBB) {
490     LLVM_DEBUG(dbgs() << "analyzeBranch didn't find conditional branch.\n");
491     return false;
492   }
493 
494   // Make sure the analyzed branch is conditional; one of the successors
495   // could be a landing pad. (Empty landing pads can be generated on Windows.)
496   if (Cond.empty()) {
497     LLVM_DEBUG(dbgs() << "analyzeBranch found an unconditional branch.\n");
498     return false;
499   }
500 
501   // analyzeBranch doesn't set FBB on a fall-through branch.
502   // Make sure it is always set.
503   FBB = TBB == Succ0 ? Succ1 : Succ0;
504 
505   // Any phis in the tail block must be convertible to selects.
506   PHIs.clear();
507   MachineBasicBlock *TPred = getTPred();
508   MachineBasicBlock *FPred = getFPred();
509   for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
510        I != E && I->isPHI(); ++I) {
511     PHIs.push_back(&*I);
512     PHIInfo &PI = PHIs.back();
513     // Find PHI operands corresponding to TPred and FPred.
514     for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
515       if (PI.PHI->getOperand(i+1).getMBB() == TPred)
516         PI.TReg = PI.PHI->getOperand(i).getReg();
517       if (PI.PHI->getOperand(i+1).getMBB() == FPred)
518         PI.FReg = PI.PHI->getOperand(i).getReg();
519     }
520     assert(Register::isVirtualRegister(PI.TReg) && "Bad PHI");
521     assert(Register::isVirtualRegister(PI.FReg) && "Bad PHI");
522 
523     // Get target information.
524     if (!TII->canInsertSelect(*Head, Cond, PI.PHI->getOperand(0).getReg(),
525                               PI.TReg, PI.FReg, PI.CondCycles, PI.TCycles,
526                               PI.FCycles)) {
527       LLVM_DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
528       return false;
529     }
530   }
531 
532   // Check that the conditional instructions can be speculated.
533   InsertAfter.clear();
534   ClobberedRegUnits.reset();
535   if (Predicate) {
536     if (TBB != Tail && !canPredicateInstrs(TBB))
537       return false;
538     if (FBB != Tail && !canPredicateInstrs(FBB))
539       return false;
540   } else {
541     if (TBB != Tail && !canSpeculateInstrs(TBB))
542       return false;
543     if (FBB != Tail && !canSpeculateInstrs(FBB))
544       return false;
545   }
546 
547   // Try to find a valid insertion point for the speculated instructions in the
548   // head basic block.
549   if (!findInsertionPoint())
550     return false;
551 
552   if (isTriangle())
553     ++NumTrianglesSeen;
554   else
555     ++NumDiamondsSeen;
556   return true;
557 }
558 
559 /// replacePHIInstrs - Completely replace PHI instructions with selects.
560 /// This is possible when the only Tail predecessors are the if-converted
561 /// blocks.
562 void SSAIfConv::replacePHIInstrs() {
563   assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
564   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
565   assert(FirstTerm != Head->end() && "No terminators");
566   DebugLoc HeadDL = FirstTerm->getDebugLoc();
567 
568   // Convert all PHIs to select instructions inserted before FirstTerm.
569   for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
570     PHIInfo &PI = PHIs[i];
571     LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
572     Register DstReg = PI.PHI->getOperand(0).getReg();
573     TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
574     LLVM_DEBUG(dbgs() << "          --> " << *std::prev(FirstTerm));
575     PI.PHI->eraseFromParent();
576     PI.PHI = nullptr;
577   }
578 }
579 
580 /// rewritePHIOperands - When there are additional Tail predecessors, insert
581 /// select instructions in Head and rewrite PHI operands to use the selects.
582 /// Keep the PHI instructions in Tail to handle the other predecessors.
583 void SSAIfConv::rewritePHIOperands() {
584   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
585   assert(FirstTerm != Head->end() && "No terminators");
586   DebugLoc HeadDL = FirstTerm->getDebugLoc();
587 
588   // Convert all PHIs to select instructions inserted before FirstTerm.
589   for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
590     PHIInfo &PI = PHIs[i];
591     unsigned DstReg = 0;
592 
593     LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
594     if (PI.TReg == PI.FReg) {
595       // We do not need the select instruction if both incoming values are
596       // equal.
597       DstReg = PI.TReg;
598     } else {
599       Register PHIDst = PI.PHI->getOperand(0).getReg();
600       DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
601       TII->insertSelect(*Head, FirstTerm, HeadDL,
602                          DstReg, Cond, PI.TReg, PI.FReg);
603       LLVM_DEBUG(dbgs() << "          --> " << *std::prev(FirstTerm));
604     }
605 
606     // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
607     for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
608       MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
609       if (MBB == getTPred()) {
610         PI.PHI->getOperand(i-1).setMBB(Head);
611         PI.PHI->getOperand(i-2).setReg(DstReg);
612       } else if (MBB == getFPred()) {
613         PI.PHI->RemoveOperand(i-1);
614         PI.PHI->RemoveOperand(i-2);
615       }
616     }
617     LLVM_DEBUG(dbgs() << "          --> " << *PI.PHI);
618   }
619 }
620 
621 /// convertIf - Execute the if conversion after canConvertIf has determined the
622 /// feasibility.
623 ///
624 /// Any basic blocks erased will be added to RemovedBlocks.
625 ///
626 void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks,
627                           bool Predicate) {
628   assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
629 
630   // Update statistics.
631   if (isTriangle())
632     ++NumTrianglesConv;
633   else
634     ++NumDiamondsConv;
635 
636   // Move all instructions into Head, except for the terminators.
637   if (TBB != Tail) {
638     if (Predicate)
639       PredicateBlock(TBB, /*ReversePredicate=*/false);
640     Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
641   }
642   if (FBB != Tail) {
643     if (Predicate)
644       PredicateBlock(FBB, /*ReversePredicate=*/true);
645     Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
646   }
647   // Are there extra Tail predecessors?
648   bool ExtraPreds = Tail->pred_size() != 2;
649   if (ExtraPreds)
650     rewritePHIOperands();
651   else
652     replacePHIInstrs();
653 
654   // Fix up the CFG, temporarily leave Head without any successors.
655   Head->removeSuccessor(TBB);
656   Head->removeSuccessor(FBB, true);
657   if (TBB != Tail)
658     TBB->removeSuccessor(Tail, true);
659   if (FBB != Tail)
660     FBB->removeSuccessor(Tail, true);
661 
662   // Fix up Head's terminators.
663   // It should become a single branch or a fallthrough.
664   DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
665   TII->removeBranch(*Head);
666 
667   // Erase the now empty conditional blocks. It is likely that Head can fall
668   // through to Tail, and we can join the two blocks.
669   if (TBB != Tail) {
670     RemovedBlocks.push_back(TBB);
671     TBB->eraseFromParent();
672   }
673   if (FBB != Tail) {
674     RemovedBlocks.push_back(FBB);
675     FBB->eraseFromParent();
676   }
677 
678   assert(Head->succ_empty() && "Additional head successors?");
679   if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
680     // Splice Tail onto the end of Head.
681     LLVM_DEBUG(dbgs() << "Joining tail " << printMBBReference(*Tail)
682                       << " into head " << printMBBReference(*Head) << '\n');
683     Head->splice(Head->end(), Tail,
684                      Tail->begin(), Tail->end());
685     Head->transferSuccessorsAndUpdatePHIs(Tail);
686     RemovedBlocks.push_back(Tail);
687     Tail->eraseFromParent();
688   } else {
689     // We need a branch to Tail, let code placement work it out later.
690     LLVM_DEBUG(dbgs() << "Converting to unconditional branch.\n");
691     SmallVector<MachineOperand, 0> EmptyCond;
692     TII->insertBranch(*Head, Tail, nullptr, EmptyCond, HeadDL);
693     Head->addSuccessor(Tail);
694   }
695   LLVM_DEBUG(dbgs() << *Head);
696 }
697 
698 //===----------------------------------------------------------------------===//
699 //                           EarlyIfConverter Pass
700 //===----------------------------------------------------------------------===//
701 
702 namespace {
703 class EarlyIfConverter : public MachineFunctionPass {
704   const TargetInstrInfo *TII;
705   const TargetRegisterInfo *TRI;
706   MCSchedModel SchedModel;
707   MachineRegisterInfo *MRI;
708   MachineDominatorTree *DomTree;
709   MachineLoopInfo *Loops;
710   MachineTraceMetrics *Traces;
711   MachineTraceMetrics::Ensemble *MinInstr;
712   SSAIfConv IfConv;
713 
714 public:
715   static char ID;
716   EarlyIfConverter() : MachineFunctionPass(ID) {}
717   void getAnalysisUsage(AnalysisUsage &AU) const override;
718   bool runOnMachineFunction(MachineFunction &MF) override;
719   StringRef getPassName() const override { return "Early If-Conversion"; }
720 
721 private:
722   bool tryConvertIf(MachineBasicBlock*);
723   void invalidateTraces();
724   bool shouldConvertIf();
725 };
726 } // end anonymous namespace
727 
728 char EarlyIfConverter::ID = 0;
729 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
730 
731 INITIALIZE_PASS_BEGIN(EarlyIfConverter, DEBUG_TYPE,
732                       "Early If Converter", false, false)
733 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
734 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
735 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
736 INITIALIZE_PASS_END(EarlyIfConverter, DEBUG_TYPE,
737                     "Early If Converter", false, false)
738 
739 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
740   AU.addRequired<MachineBranchProbabilityInfo>();
741   AU.addRequired<MachineDominatorTree>();
742   AU.addPreserved<MachineDominatorTree>();
743   AU.addRequired<MachineLoopInfo>();
744   AU.addPreserved<MachineLoopInfo>();
745   AU.addRequired<MachineTraceMetrics>();
746   AU.addPreserved<MachineTraceMetrics>();
747   MachineFunctionPass::getAnalysisUsage(AU);
748 }
749 
750 namespace {
751 /// Update the dominator tree after if-conversion erased some blocks.
752 void updateDomTree(MachineDominatorTree *DomTree, const SSAIfConv &IfConv,
753                    ArrayRef<MachineBasicBlock *> Removed) {
754   // convertIf can remove TBB, FBB, and Tail can be merged into Head.
755   // TBB and FBB should not dominate any blocks.
756   // Tail children should be transferred to Head.
757   MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
758   for (auto B : Removed) {
759     MachineDomTreeNode *Node = DomTree->getNode(B);
760     assert(Node != HeadNode && "Cannot erase the head node");
761     while (Node->getNumChildren()) {
762       assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
763       DomTree->changeImmediateDominator(Node->back(), HeadNode);
764     }
765     DomTree->eraseNode(B);
766   }
767 }
768 
769 /// Update LoopInfo after if-conversion.
770 void updateLoops(MachineLoopInfo *Loops,
771                  ArrayRef<MachineBasicBlock *> Removed) {
772   if (!Loops)
773     return;
774   // If-conversion doesn't change loop structure, and it doesn't mess with back
775   // edges, so updating LoopInfo is simply removing the dead blocks.
776   for (auto B : Removed)
777     Loops->removeBlock(B);
778 }
779 } // namespace
780 
781 /// Invalidate MachineTraceMetrics before if-conversion.
782 void EarlyIfConverter::invalidateTraces() {
783   Traces->verifyAnalysis();
784   Traces->invalidate(IfConv.Head);
785   Traces->invalidate(IfConv.Tail);
786   Traces->invalidate(IfConv.TBB);
787   Traces->invalidate(IfConv.FBB);
788   Traces->verifyAnalysis();
789 }
790 
791 // Adjust cycles with downward saturation.
792 static unsigned adjCycles(unsigned Cyc, int Delta) {
793   if (Delta < 0 && Cyc + Delta > Cyc)
794     return 0;
795   return Cyc + Delta;
796 }
797 
798 namespace {
799 /// Helper class to simplify emission of cycle counts into optimization remarks.
800 struct Cycles {
801   const char *Key;
802   unsigned Value;
803 };
804 template <typename Remark> Remark &operator<<(Remark &R, Cycles C) {
805   return R << ore::NV(C.Key, C.Value) << (C.Value == 1 ? " cycle" : " cycles");
806 }
807 } // anonymous namespace
808 
809 /// Apply cost model and heuristics to the if-conversion in IfConv.
810 /// Return true if the conversion is a good idea.
811 ///
812 bool EarlyIfConverter::shouldConvertIf() {
813   // Stress testing mode disables all cost considerations.
814   if (Stress)
815     return true;
816 
817   if (!MinInstr)
818     MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
819 
820   MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
821   MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
822   LLVM_DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
823   unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
824                               FBBTrace.getCriticalPath());
825 
826   // Set a somewhat arbitrary limit on the critical path extension we accept.
827   unsigned CritLimit = SchedModel.MispredictPenalty/2;
828 
829   MachineBasicBlock &MBB = *IfConv.Head;
830   MachineOptimizationRemarkEmitter MORE(*MBB.getParent(), nullptr);
831 
832   // If-conversion only makes sense when there is unexploited ILP. Compute the
833   // maximum-ILP resource length of the trace after if-conversion. Compare it
834   // to the shortest critical path.
835   SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
836   if (IfConv.TBB != IfConv.Tail)
837     ExtraBlocks.push_back(IfConv.TBB);
838   unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
839   LLVM_DEBUG(dbgs() << "Resource length " << ResLength
840                     << ", minimal critical path " << MinCrit << '\n');
841   if (ResLength > MinCrit + CritLimit) {
842     LLVM_DEBUG(dbgs() << "Not enough available ILP.\n");
843     MORE.emit([&]() {
844       MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
845                                         MBB.findDebugLoc(MBB.back()), &MBB);
846       R << "did not if-convert branch: the resulting critical path ("
847         << Cycles{"ResLength", ResLength}
848         << ") would extend the shorter leg's critical path ("
849         << Cycles{"MinCrit", MinCrit} << ") by more than the threshold of "
850         << Cycles{"CritLimit", CritLimit}
851         << ", which cannot be hidden by available ILP.";
852       return R;
853     });
854     return false;
855   }
856 
857   // Assume that the depth of the first head terminator will also be the depth
858   // of the select instruction inserted, as determined by the flag dependency.
859   // TBB / FBB data dependencies may delay the select even more.
860   MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
861   unsigned BranchDepth =
862       HeadTrace.getInstrCycles(*IfConv.Head->getFirstTerminator()).Depth;
863   LLVM_DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
864 
865   // Look at all the tail phis, and compute the critical path extension caused
866   // by inserting select instructions.
867   MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
868   struct CriticalPathInfo {
869     unsigned Extra; // Count of extra cycles that the component adds.
870     unsigned Depth; // Absolute depth of the component in cycles.
871   };
872   CriticalPathInfo Cond{};
873   CriticalPathInfo TBlock{};
874   CriticalPathInfo FBlock{};
875   bool ShouldConvert = true;
876   for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
877     SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
878     unsigned Slack = TailTrace.getInstrSlack(*PI.PHI);
879     unsigned MaxDepth = Slack + TailTrace.getInstrCycles(*PI.PHI).Depth;
880     LLVM_DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
881 
882     // The condition is pulled into the critical path.
883     unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
884     if (CondDepth > MaxDepth) {
885       unsigned Extra = CondDepth - MaxDepth;
886       LLVM_DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
887       if (Extra > Cond.Extra)
888         Cond = {Extra, CondDepth};
889       if (Extra > CritLimit) {
890         LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
891         ShouldConvert = false;
892       }
893     }
894 
895     // The TBB value is pulled into the critical path.
896     unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(*PI.PHI), PI.TCycles);
897     if (TDepth > MaxDepth) {
898       unsigned Extra = TDepth - MaxDepth;
899       LLVM_DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
900       if (Extra > TBlock.Extra)
901         TBlock = {Extra, TDepth};
902       if (Extra > CritLimit) {
903         LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
904         ShouldConvert = false;
905       }
906     }
907 
908     // The FBB value is pulled into the critical path.
909     unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(*PI.PHI), PI.FCycles);
910     if (FDepth > MaxDepth) {
911       unsigned Extra = FDepth - MaxDepth;
912       LLVM_DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
913       if (Extra > FBlock.Extra)
914         FBlock = {Extra, FDepth};
915       if (Extra > CritLimit) {
916         LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
917         ShouldConvert = false;
918       }
919     }
920   }
921 
922   // Organize by "short" and "long" legs, since the diagnostics get confusing
923   // when referring to the "true" and "false" sides of the branch, given that
924   // those don't always correlate with what the user wrote in source-terms.
925   const CriticalPathInfo Short = TBlock.Extra > FBlock.Extra ? FBlock : TBlock;
926   const CriticalPathInfo Long = TBlock.Extra > FBlock.Extra ? TBlock : FBlock;
927 
928   if (ShouldConvert) {
929     MORE.emit([&]() {
930       MachineOptimizationRemark R(DEBUG_TYPE, "IfConversion",
931                                   MBB.back().getDebugLoc(), &MBB);
932       R << "performing if-conversion on branch: the condition adds "
933         << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
934       if (Short.Extra > 0)
935         R << ", and the short leg adds another "
936           << Cycles{"ShortCycles", Short.Extra};
937       if (Long.Extra > 0)
938         R << ", and the long leg adds another "
939           << Cycles{"LongCycles", Long.Extra};
940       R << ", each staying under the threshold of "
941         << Cycles{"CritLimit", CritLimit} << ".";
942       return R;
943     });
944   } else {
945     MORE.emit([&]() {
946       MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
947                                         MBB.back().getDebugLoc(), &MBB);
948       R << "did not if-convert branch: the condition would add "
949         << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
950       if (Cond.Extra > CritLimit)
951         R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
952       if (Short.Extra > 0) {
953         R << ", and the short leg would add another "
954           << Cycles{"ShortCycles", Short.Extra};
955         if (Short.Extra > CritLimit)
956           R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
957       }
958       if (Long.Extra > 0) {
959         R << ", and the long leg would add another "
960           << Cycles{"LongCycles", Long.Extra};
961         if (Long.Extra > CritLimit)
962           R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
963       }
964       R << ".";
965       return R;
966     });
967   }
968 
969   return ShouldConvert;
970 }
971 
972 /// Attempt repeated if-conversion on MBB, return true if successful.
973 ///
974 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
975   bool Changed = false;
976   while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
977     // If-convert MBB and update analyses.
978     invalidateTraces();
979     SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
980     IfConv.convertIf(RemovedBlocks);
981     Changed = true;
982     updateDomTree(DomTree, IfConv, RemovedBlocks);
983     updateLoops(Loops, RemovedBlocks);
984   }
985   return Changed;
986 }
987 
988 bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
989   LLVM_DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
990                     << "********** Function: " << MF.getName() << '\n');
991   if (skipFunction(MF.getFunction()))
992     return false;
993 
994   // Only run if conversion if the target wants it.
995   const TargetSubtargetInfo &STI = MF.getSubtarget();
996   if (!STI.enableEarlyIfConversion())
997     return false;
998 
999   TII = STI.getInstrInfo();
1000   TRI = STI.getRegisterInfo();
1001   SchedModel = STI.getSchedModel();
1002   MRI = &MF.getRegInfo();
1003   DomTree = &getAnalysis<MachineDominatorTree>();
1004   Loops = getAnalysisIfAvailable<MachineLoopInfo>();
1005   Traces = &getAnalysis<MachineTraceMetrics>();
1006   MinInstr = nullptr;
1007 
1008   bool Changed = false;
1009   IfConv.runOnMachineFunction(MF);
1010 
1011   // Visit blocks in dominator tree post-order. The post-order enables nested
1012   // if-conversion in a single pass. The tryConvertIf() function may erase
1013   // blocks, but only blocks dominated by the head block. This makes it safe to
1014   // update the dominator tree while the post-order iterator is still active.
1015   for (auto DomNode : post_order(DomTree))
1016     if (tryConvertIf(DomNode->getBlock()))
1017       Changed = true;
1018 
1019   return Changed;
1020 }
1021 
1022 //===----------------------------------------------------------------------===//
1023 //                           EarlyIfPredicator Pass
1024 //===----------------------------------------------------------------------===//
1025 
1026 namespace {
1027 class EarlyIfPredicator : public MachineFunctionPass {
1028   const TargetInstrInfo *TII;
1029   const TargetRegisterInfo *TRI;
1030   TargetSchedModel SchedModel;
1031   MachineRegisterInfo *MRI;
1032   MachineDominatorTree *DomTree;
1033   MachineBranchProbabilityInfo *MBPI;
1034   MachineLoopInfo *Loops;
1035   SSAIfConv IfConv;
1036 
1037 public:
1038   static char ID;
1039   EarlyIfPredicator() : MachineFunctionPass(ID) {}
1040   void getAnalysisUsage(AnalysisUsage &AU) const override;
1041   bool runOnMachineFunction(MachineFunction &MF) override;
1042   StringRef getPassName() const override { return "Early If-predicator"; }
1043 
1044 protected:
1045   bool tryConvertIf(MachineBasicBlock *);
1046   bool shouldConvertIf();
1047 };
1048 } // end anonymous namespace
1049 
1050 #undef DEBUG_TYPE
1051 #define DEBUG_TYPE "early-if-predicator"
1052 
1053 char EarlyIfPredicator::ID = 0;
1054 char &llvm::EarlyIfPredicatorID = EarlyIfPredicator::ID;
1055 
1056 INITIALIZE_PASS_BEGIN(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator",
1057                       false, false)
1058 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1059 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1060 INITIALIZE_PASS_END(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator", false,
1061                     false)
1062 
1063 void EarlyIfPredicator::getAnalysisUsage(AnalysisUsage &AU) const {
1064   AU.addRequired<MachineBranchProbabilityInfo>();
1065   AU.addRequired<MachineDominatorTree>();
1066   AU.addPreserved<MachineDominatorTree>();
1067   AU.addRequired<MachineLoopInfo>();
1068   AU.addPreserved<MachineLoopInfo>();
1069   MachineFunctionPass::getAnalysisUsage(AU);
1070 }
1071 
1072 /// Apply the target heuristic to decide if the transformation is profitable.
1073 bool EarlyIfPredicator::shouldConvertIf() {
1074   auto TrueProbability = MBPI->getEdgeProbability(IfConv.Head, IfConv.TBB);
1075   if (IfConv.isTriangle()) {
1076     MachineBasicBlock &IfBlock =
1077         (IfConv.TBB == IfConv.Tail) ? *IfConv.FBB : *IfConv.TBB;
1078 
1079     unsigned ExtraPredCost = 0;
1080     unsigned Cycles = 0;
1081     for (MachineInstr &I : IfBlock) {
1082       unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1083       if (NumCycles > 1)
1084         Cycles += NumCycles - 1;
1085       ExtraPredCost += TII->getPredicationCost(I);
1086     }
1087 
1088     return TII->isProfitableToIfCvt(IfBlock, Cycles, ExtraPredCost,
1089                                     TrueProbability);
1090   }
1091   unsigned TExtra = 0;
1092   unsigned FExtra = 0;
1093   unsigned TCycle = 0;
1094   unsigned FCycle = 0;
1095   for (MachineInstr &I : *IfConv.TBB) {
1096     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1097     if (NumCycles > 1)
1098       TCycle += NumCycles - 1;
1099     TExtra += TII->getPredicationCost(I);
1100   }
1101   for (MachineInstr &I : *IfConv.FBB) {
1102     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1103     if (NumCycles > 1)
1104       FCycle += NumCycles - 1;
1105     FExtra += TII->getPredicationCost(I);
1106   }
1107   return TII->isProfitableToIfCvt(*IfConv.TBB, TCycle, TExtra, *IfConv.FBB,
1108                                   FCycle, FExtra, TrueProbability);
1109 }
1110 
1111 /// Attempt repeated if-conversion on MBB, return true if successful.
1112 ///
1113 bool EarlyIfPredicator::tryConvertIf(MachineBasicBlock *MBB) {
1114   bool Changed = false;
1115   while (IfConv.canConvertIf(MBB, /*Predicate*/ true) && shouldConvertIf()) {
1116     // If-convert MBB and update analyses.
1117     SmallVector<MachineBasicBlock *, 4> RemovedBlocks;
1118     IfConv.convertIf(RemovedBlocks, /*Predicate*/ true);
1119     Changed = true;
1120     updateDomTree(DomTree, IfConv, RemovedBlocks);
1121     updateLoops(Loops, RemovedBlocks);
1122   }
1123   return Changed;
1124 }
1125 
1126 bool EarlyIfPredicator::runOnMachineFunction(MachineFunction &MF) {
1127   LLVM_DEBUG(dbgs() << "********** EARLY IF-PREDICATOR **********\n"
1128                     << "********** Function: " << MF.getName() << '\n');
1129   if (skipFunction(MF.getFunction()))
1130     return false;
1131 
1132   const TargetSubtargetInfo &STI = MF.getSubtarget();
1133   TII = STI.getInstrInfo();
1134   TRI = STI.getRegisterInfo();
1135   MRI = &MF.getRegInfo();
1136   SchedModel.init(&STI);
1137   DomTree = &getAnalysis<MachineDominatorTree>();
1138   Loops = getAnalysisIfAvailable<MachineLoopInfo>();
1139   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1140 
1141   bool Changed = false;
1142   IfConv.runOnMachineFunction(MF);
1143 
1144   // Visit blocks in dominator tree post-order. The post-order enables nested
1145   // if-conversion in a single pass. The tryConvertIf() function may erase
1146   // blocks, but only blocks dominated by the head block. This makes it safe to
1147   // update the dominator tree while the post-order iterator is still active.
1148   for (auto DomNode : post_order(DomTree))
1149     if (tryConvertIf(DomNode->getBlock()))
1150       Changed = true;
1151 
1152   return Changed;
1153 }
1154