EarlyIfConversion.cpp 43 KB

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