EarlyIfConversion.cpp 41 KB

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