IfConversion.cpp 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238
  1. //===- IfConversion.cpp - Machine code if conversion pass -----------------===//
  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. // This file implements the machine instruction level if-conversion pass, which
  10. // tries to convert conditional branches into predicated instructions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "BranchFolding.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/ScopeExit.h"
  16. #include "llvm/ADT/SmallSet.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/SparseSet.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/ADT/iterator_range.h"
  21. #include "llvm/CodeGen/LivePhysRegs.h"
  22. #include "llvm/CodeGen/MachineBasicBlock.h"
  23. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  24. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  25. #include "llvm/CodeGen/MachineFunction.h"
  26. #include "llvm/CodeGen/MachineFunctionPass.h"
  27. #include "llvm/CodeGen/MachineInstr.h"
  28. #include "llvm/CodeGen/MachineInstrBuilder.h"
  29. #include "llvm/CodeGen/MachineModuleInfo.h"
  30. #include "llvm/CodeGen/MachineOperand.h"
  31. #include "llvm/CodeGen/MachineRegisterInfo.h"
  32. #include "llvm/CodeGen/TargetInstrInfo.h"
  33. #include "llvm/CodeGen/TargetLowering.h"
  34. #include "llvm/CodeGen/TargetRegisterInfo.h"
  35. #include "llvm/CodeGen/TargetSchedule.h"
  36. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  37. #include "llvm/IR/DebugLoc.h"
  38. #include "llvm/MC/MCRegisterInfo.h"
  39. #include "llvm/Pass.h"
  40. #include "llvm/Support/BranchProbability.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/Debug.h"
  43. #include "llvm/Support/ErrorHandling.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include <algorithm>
  46. #include <cassert>
  47. #include <functional>
  48. #include <iterator>
  49. #include <memory>
  50. #include <utility>
  51. #include <vector>
  52. using namespace llvm;
  53. #define DEBUG_TYPE "if-converter"
  54. // Hidden options for help debugging.
  55. static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
  56. static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
  57. static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
  58. static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
  59. cl::init(false), cl::Hidden);
  60. static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
  61. cl::init(false), cl::Hidden);
  62. static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
  63. cl::init(false), cl::Hidden);
  64. static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
  65. cl::init(false), cl::Hidden);
  66. static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
  67. cl::init(false), cl::Hidden);
  68. static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
  69. cl::init(false), cl::Hidden);
  70. static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
  71. cl::init(false), cl::Hidden);
  72. static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
  73. cl::init(false), cl::Hidden);
  74. static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
  75. cl::init(true), cl::Hidden);
  76. STATISTIC(NumSimple, "Number of simple if-conversions performed");
  77. STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
  78. STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
  79. STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
  80. STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
  81. STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
  82. STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
  83. STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
  84. STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
  85. STATISTIC(NumDupBBs, "Number of duplicated blocks");
  86. STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
  87. namespace {
  88. class IfConverter : public MachineFunctionPass {
  89. enum IfcvtKind {
  90. ICNotClassfied, // BB data valid, but not classified.
  91. ICSimpleFalse, // Same as ICSimple, but on the false path.
  92. ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
  93. ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
  94. ICTriangleRev, // Same as ICTriangle, but true path rev condition.
  95. ICTriangleFalse, // Same as ICTriangle, but on the false path.
  96. ICTriangle, // BB is entry of a triangle sub-CFG.
  97. ICDiamond, // BB is entry of a diamond sub-CFG.
  98. ICForkedDiamond // BB is entry of an almost diamond sub-CFG, with a
  99. // common tail that can be shared.
  100. };
  101. /// One per MachineBasicBlock, this is used to cache the result
  102. /// if-conversion feasibility analysis. This includes results from
  103. /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
  104. /// classification, and common tail block of its successors (if it's a
  105. /// diamond shape), its size, whether it's predicable, and whether any
  106. /// instruction can clobber the 'would-be' predicate.
  107. ///
  108. /// IsDone - True if BB is not to be considered for ifcvt.
  109. /// IsBeingAnalyzed - True if BB is currently being analyzed.
  110. /// IsAnalyzed - True if BB has been analyzed (info is still valid).
  111. /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
  112. /// IsBrAnalyzable - True if analyzeBranch() returns false.
  113. /// HasFallThrough - True if BB may fallthrough to the following BB.
  114. /// IsUnpredicable - True if BB is known to be unpredicable.
  115. /// ClobbersPred - True if BB could modify predicates (e.g. has
  116. /// cmp, call, etc.)
  117. /// NonPredSize - Number of non-predicated instructions.
  118. /// ExtraCost - Extra cost for multi-cycle instructions.
  119. /// ExtraCost2 - Some instructions are slower when predicated
  120. /// BB - Corresponding MachineBasicBlock.
  121. /// TrueBB / FalseBB- See analyzeBranch().
  122. /// BrCond - Conditions for end of block conditional branches.
  123. /// Predicate - Predicate used in the BB.
  124. struct BBInfo {
  125. bool IsDone : 1;
  126. bool IsBeingAnalyzed : 1;
  127. bool IsAnalyzed : 1;
  128. bool IsEnqueued : 1;
  129. bool IsBrAnalyzable : 1;
  130. bool IsBrReversible : 1;
  131. bool HasFallThrough : 1;
  132. bool IsUnpredicable : 1;
  133. bool CannotBeCopied : 1;
  134. bool ClobbersPred : 1;
  135. unsigned NonPredSize = 0;
  136. unsigned ExtraCost = 0;
  137. unsigned ExtraCost2 = 0;
  138. MachineBasicBlock *BB = nullptr;
  139. MachineBasicBlock *TrueBB = nullptr;
  140. MachineBasicBlock *FalseBB = nullptr;
  141. SmallVector<MachineOperand, 4> BrCond;
  142. SmallVector<MachineOperand, 4> Predicate;
  143. BBInfo() : IsDone(false), IsBeingAnalyzed(false),
  144. IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
  145. IsBrReversible(false), HasFallThrough(false),
  146. IsUnpredicable(false), CannotBeCopied(false),
  147. ClobbersPred(false) {}
  148. };
  149. /// Record information about pending if-conversions to attempt:
  150. /// BBI - Corresponding BBInfo.
  151. /// Kind - Type of block. See IfcvtKind.
  152. /// NeedSubsumption - True if the to-be-predicated BB has already been
  153. /// predicated.
  154. /// NumDups - Number of instructions that would be duplicated due
  155. /// to this if-conversion. (For diamonds, the number of
  156. /// identical instructions at the beginnings of both
  157. /// paths).
  158. /// NumDups2 - For diamonds, the number of identical instructions
  159. /// at the ends of both paths.
  160. struct IfcvtToken {
  161. BBInfo &BBI;
  162. IfcvtKind Kind;
  163. unsigned NumDups;
  164. unsigned NumDups2;
  165. bool NeedSubsumption : 1;
  166. bool TClobbersPred : 1;
  167. bool FClobbersPred : 1;
  168. IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
  169. bool tc = false, bool fc = false)
  170. : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
  171. TClobbersPred(tc), FClobbersPred(fc) {}
  172. };
  173. /// Results of if-conversion feasibility analysis indexed by basic block
  174. /// number.
  175. std::vector<BBInfo> BBAnalysis;
  176. TargetSchedModel SchedModel;
  177. const TargetLoweringBase *TLI;
  178. const TargetInstrInfo *TII;
  179. const TargetRegisterInfo *TRI;
  180. const MachineBranchProbabilityInfo *MBPI;
  181. MachineRegisterInfo *MRI;
  182. LivePhysRegs Redefs;
  183. bool PreRegAlloc;
  184. bool MadeChange;
  185. int FnNum = -1;
  186. std::function<bool(const MachineFunction &)> PredicateFtor;
  187. public:
  188. static char ID;
  189. IfConverter(std::function<bool(const MachineFunction &)> Ftor = nullptr)
  190. : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
  191. initializeIfConverterPass(*PassRegistry::getPassRegistry());
  192. }
  193. void getAnalysisUsage(AnalysisUsage &AU) const override {
  194. AU.addRequired<MachineBlockFrequencyInfo>();
  195. AU.addRequired<MachineBranchProbabilityInfo>();
  196. MachineFunctionPass::getAnalysisUsage(AU);
  197. }
  198. bool runOnMachineFunction(MachineFunction &MF) override;
  199. MachineFunctionProperties getRequiredProperties() const override {
  200. return MachineFunctionProperties().set(
  201. MachineFunctionProperties::Property::NoVRegs);
  202. }
  203. private:
  204. bool reverseBranchCondition(BBInfo &BBI) const;
  205. bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
  206. BranchProbability Prediction) const;
  207. bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
  208. bool FalseBranch, unsigned &Dups,
  209. BranchProbability Prediction) const;
  210. bool CountDuplicatedInstructions(
  211. MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
  212. MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
  213. unsigned &Dups1, unsigned &Dups2,
  214. MachineBasicBlock &TBB, MachineBasicBlock &FBB,
  215. bool SkipUnconditionalBranches) const;
  216. bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
  217. unsigned &Dups1, unsigned &Dups2,
  218. BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
  219. bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
  220. unsigned &Dups1, unsigned &Dups2,
  221. BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
  222. void AnalyzeBranches(BBInfo &BBI);
  223. void ScanInstructions(BBInfo &BBI,
  224. MachineBasicBlock::iterator &Begin,
  225. MachineBasicBlock::iterator &End,
  226. bool BranchUnpredicable = false) const;
  227. bool RescanInstructions(
  228. MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
  229. MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
  230. BBInfo &TrueBBI, BBInfo &FalseBBI) const;
  231. void AnalyzeBlock(MachineBasicBlock &MBB,
  232. std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
  233. bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Pred,
  234. bool isTriangle = false, bool RevBranch = false,
  235. bool hasCommonTail = false);
  236. void AnalyzeBlocks(MachineFunction &MF,
  237. std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
  238. void InvalidatePreds(MachineBasicBlock &MBB);
  239. bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
  240. bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
  241. bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
  242. unsigned NumDups1, unsigned NumDups2,
  243. bool TClobbersPred, bool FClobbersPred,
  244. bool RemoveBranch, bool MergeAddEdges);
  245. bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
  246. unsigned NumDups1, unsigned NumDups2,
  247. bool TClobbers, bool FClobbers);
  248. bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
  249. unsigned NumDups1, unsigned NumDups2,
  250. bool TClobbers, bool FClobbers);
  251. void PredicateBlock(BBInfo &BBI,
  252. MachineBasicBlock::iterator E,
  253. SmallVectorImpl<MachineOperand> &Cond,
  254. SmallSet<MCPhysReg, 4> *LaterRedefs = nullptr);
  255. void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
  256. SmallVectorImpl<MachineOperand> &Cond,
  257. bool IgnoreBr = false);
  258. void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
  259. bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
  260. unsigned Cycle, unsigned Extra,
  261. BranchProbability Prediction) const {
  262. return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
  263. Prediction);
  264. }
  265. bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
  266. unsigned TCycle, unsigned TExtra,
  267. MachineBasicBlock &FBB,
  268. unsigned FCycle, unsigned FExtra,
  269. BranchProbability Prediction) const {
  270. return TCycle > 0 && FCycle > 0 &&
  271. TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
  272. Prediction);
  273. }
  274. /// Returns true if Block ends without a terminator.
  275. bool blockAlwaysFallThrough(BBInfo &BBI) const {
  276. return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
  277. }
  278. /// Used to sort if-conversion candidates.
  279. static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
  280. const std::unique_ptr<IfcvtToken> &C2) {
  281. int Incr1 = (C1->Kind == ICDiamond)
  282. ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
  283. int Incr2 = (C2->Kind == ICDiamond)
  284. ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
  285. if (Incr1 > Incr2)
  286. return true;
  287. else if (Incr1 == Incr2) {
  288. // Favors subsumption.
  289. if (!C1->NeedSubsumption && C2->NeedSubsumption)
  290. return true;
  291. else if (C1->NeedSubsumption == C2->NeedSubsumption) {
  292. // Favors diamond over triangle, etc.
  293. if ((unsigned)C1->Kind < (unsigned)C2->Kind)
  294. return true;
  295. else if (C1->Kind == C2->Kind)
  296. return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
  297. }
  298. }
  299. return false;
  300. }
  301. };
  302. } // end anonymous namespace
  303. char IfConverter::ID = 0;
  304. char &llvm::IfConverterID = IfConverter::ID;
  305. INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
  306. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  307. INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
  308. bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
  309. if (skipFunction(MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
  310. return false;
  311. const TargetSubtargetInfo &ST = MF.getSubtarget();
  312. TLI = ST.getTargetLowering();
  313. TII = ST.getInstrInfo();
  314. TRI = ST.getRegisterInfo();
  315. BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
  316. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  317. MRI = &MF.getRegInfo();
  318. SchedModel.init(&ST);
  319. if (!TII) return false;
  320. PreRegAlloc = MRI->isSSA();
  321. bool BFChange = false;
  322. if (!PreRegAlloc) {
  323. // Tail merge tend to expose more if-conversion opportunities.
  324. BranchFolder BF(true, false, MBFI, *MBPI);
  325. BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
  326. getAnalysisIfAvailable<MachineModuleInfo>());
  327. }
  328. LLVM_DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
  329. << MF.getName() << "\'");
  330. if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
  331. LLVM_DEBUG(dbgs() << " skipped\n");
  332. return false;
  333. }
  334. LLVM_DEBUG(dbgs() << "\n");
  335. MF.RenumberBlocks();
  336. BBAnalysis.resize(MF.getNumBlockIDs());
  337. std::vector<std::unique_ptr<IfcvtToken>> Tokens;
  338. MadeChange = false;
  339. unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
  340. NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
  341. while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
  342. // Do an initial analysis for each basic block and find all the potential
  343. // candidates to perform if-conversion.
  344. bool Change = false;
  345. AnalyzeBlocks(MF, Tokens);
  346. while (!Tokens.empty()) {
  347. std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
  348. Tokens.pop_back();
  349. BBInfo &BBI = Token->BBI;
  350. IfcvtKind Kind = Token->Kind;
  351. unsigned NumDups = Token->NumDups;
  352. unsigned NumDups2 = Token->NumDups2;
  353. // If the block has been evicted out of the queue or it has already been
  354. // marked dead (due to it being predicated), then skip it.
  355. if (BBI.IsDone)
  356. BBI.IsEnqueued = false;
  357. if (!BBI.IsEnqueued)
  358. continue;
  359. BBI.IsEnqueued = false;
  360. bool RetVal = false;
  361. switch (Kind) {
  362. default: llvm_unreachable("Unexpected!");
  363. case ICSimple:
  364. case ICSimpleFalse: {
  365. bool isFalse = Kind == ICSimpleFalse;
  366. if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
  367. LLVM_DEBUG(dbgs() << "Ifcvt (Simple"
  368. << (Kind == ICSimpleFalse ? " false" : "")
  369. << "): " << printMBBReference(*BBI.BB) << " ("
  370. << ((Kind == ICSimpleFalse) ? BBI.FalseBB->getNumber()
  371. : BBI.TrueBB->getNumber())
  372. << ") ");
  373. RetVal = IfConvertSimple(BBI, Kind);
  374. LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  375. if (RetVal) {
  376. if (isFalse) ++NumSimpleFalse;
  377. else ++NumSimple;
  378. }
  379. break;
  380. }
  381. case ICTriangle:
  382. case ICTriangleRev:
  383. case ICTriangleFalse:
  384. case ICTriangleFRev: {
  385. bool isFalse = Kind == ICTriangleFalse;
  386. bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
  387. if (DisableTriangle && !isFalse && !isRev) break;
  388. if (DisableTriangleR && !isFalse && isRev) break;
  389. if (DisableTriangleF && isFalse && !isRev) break;
  390. if (DisableTriangleFR && isFalse && isRev) break;
  391. LLVM_DEBUG(dbgs() << "Ifcvt (Triangle");
  392. if (isFalse)
  393. LLVM_DEBUG(dbgs() << " false");
  394. if (isRev)
  395. LLVM_DEBUG(dbgs() << " rev");
  396. LLVM_DEBUG(dbgs() << "): " << printMBBReference(*BBI.BB)
  397. << " (T:" << BBI.TrueBB->getNumber()
  398. << ",F:" << BBI.FalseBB->getNumber() << ") ");
  399. RetVal = IfConvertTriangle(BBI, Kind);
  400. LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  401. if (RetVal) {
  402. if (isFalse) {
  403. if (isRev) ++NumTriangleFRev;
  404. else ++NumTriangleFalse;
  405. } else {
  406. if (isRev) ++NumTriangleRev;
  407. else ++NumTriangle;
  408. }
  409. }
  410. break;
  411. }
  412. case ICDiamond:
  413. if (DisableDiamond) break;
  414. LLVM_DEBUG(dbgs() << "Ifcvt (Diamond): " << printMBBReference(*BBI.BB)
  415. << " (T:" << BBI.TrueBB->getNumber()
  416. << ",F:" << BBI.FalseBB->getNumber() << ") ");
  417. RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
  418. Token->TClobbersPred,
  419. Token->FClobbersPred);
  420. LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  421. if (RetVal) ++NumDiamonds;
  422. break;
  423. case ICForkedDiamond:
  424. if (DisableForkedDiamond) break;
  425. LLVM_DEBUG(dbgs() << "Ifcvt (Forked Diamond): "
  426. << printMBBReference(*BBI.BB)
  427. << " (T:" << BBI.TrueBB->getNumber()
  428. << ",F:" << BBI.FalseBB->getNumber() << ") ");
  429. RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
  430. Token->TClobbersPred,
  431. Token->FClobbersPred);
  432. LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  433. if (RetVal) ++NumForkedDiamonds;
  434. break;
  435. }
  436. if (RetVal && MRI->tracksLiveness())
  437. recomputeLivenessFlags(*BBI.BB);
  438. Change |= RetVal;
  439. NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
  440. NumTriangleFalse + NumTriangleFRev + NumDiamonds;
  441. if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
  442. break;
  443. }
  444. if (!Change)
  445. break;
  446. MadeChange |= Change;
  447. }
  448. Tokens.clear();
  449. BBAnalysis.clear();
  450. if (MadeChange && IfCvtBranchFold) {
  451. BranchFolder BF(false, false, MBFI, *MBPI);
  452. BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
  453. getAnalysisIfAvailable<MachineModuleInfo>());
  454. }
  455. MadeChange |= BFChange;
  456. return MadeChange;
  457. }
  458. /// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
  459. static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
  460. MachineBasicBlock *TrueBB) {
  461. for (MachineBasicBlock *SuccBB : BB->successors()) {
  462. if (SuccBB != TrueBB)
  463. return SuccBB;
  464. }
  465. return nullptr;
  466. }
  467. /// Reverse the condition of the end of the block branch. Swap block's 'true'
  468. /// and 'false' successors.
  469. bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
  470. DebugLoc dl; // FIXME: this is nowhere
  471. if (!TII->reverseBranchCondition(BBI.BrCond)) {
  472. TII->removeBranch(*BBI.BB);
  473. TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
  474. std::swap(BBI.TrueBB, BBI.FalseBB);
  475. return true;
  476. }
  477. return false;
  478. }
  479. /// Returns the next block in the function blocks ordering. If it is the end,
  480. /// returns NULL.
  481. static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
  482. MachineFunction::iterator I = MBB.getIterator();
  483. MachineFunction::iterator E = MBB.getParent()->end();
  484. if (++I == E)
  485. return nullptr;
  486. return &*I;
  487. }
  488. /// Returns true if the 'true' block (along with its predecessor) forms a valid
  489. /// simple shape for ifcvt. It also returns the number of instructions that the
  490. /// ifcvt would need to duplicate if performed in Dups.
  491. bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
  492. BranchProbability Prediction) const {
  493. Dups = 0;
  494. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
  495. return false;
  496. if (TrueBBI.IsBrAnalyzable)
  497. return false;
  498. if (TrueBBI.BB->pred_size() > 1) {
  499. if (TrueBBI.CannotBeCopied ||
  500. !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
  501. Prediction))
  502. return false;
  503. Dups = TrueBBI.NonPredSize;
  504. }
  505. return true;
  506. }
  507. /// Returns true if the 'true' and 'false' blocks (along with their common
  508. /// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
  509. /// true, it checks if 'true' block's false branch branches to the 'false' block
  510. /// rather than the other way around. It also returns the number of instructions
  511. /// that the ifcvt would need to duplicate if performed in 'Dups'.
  512. bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
  513. bool FalseBranch, unsigned &Dups,
  514. BranchProbability Prediction) const {
  515. Dups = 0;
  516. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
  517. return false;
  518. if (TrueBBI.BB->pred_size() > 1) {
  519. if (TrueBBI.CannotBeCopied)
  520. return false;
  521. unsigned Size = TrueBBI.NonPredSize;
  522. if (TrueBBI.IsBrAnalyzable) {
  523. if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
  524. // Ends with an unconditional branch. It will be removed.
  525. --Size;
  526. else {
  527. MachineBasicBlock *FExit = FalseBranch
  528. ? TrueBBI.TrueBB : TrueBBI.FalseBB;
  529. if (FExit)
  530. // Require a conditional branch
  531. ++Size;
  532. }
  533. }
  534. if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
  535. return false;
  536. Dups = Size;
  537. }
  538. MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
  539. if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
  540. MachineFunction::iterator I = TrueBBI.BB->getIterator();
  541. if (++I == TrueBBI.BB->getParent()->end())
  542. return false;
  543. TExit = &*I;
  544. }
  545. return TExit && TExit == FalseBBI.BB;
  546. }
  547. /// Count duplicated instructions and move the iterators to show where they
  548. /// are.
  549. /// @param TIB True Iterator Begin
  550. /// @param FIB False Iterator Begin
  551. /// These two iterators initially point to the first instruction of the two
  552. /// blocks, and finally point to the first non-shared instruction.
  553. /// @param TIE True Iterator End
  554. /// @param FIE False Iterator End
  555. /// These two iterators initially point to End() for the two blocks() and
  556. /// finally point to the first shared instruction in the tail.
  557. /// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
  558. /// two blocks.
  559. /// @param Dups1 count of duplicated instructions at the beginning of the 2
  560. /// blocks.
  561. /// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
  562. /// @param SkipUnconditionalBranches if true, Don't make sure that
  563. /// unconditional branches at the end of the blocks are the same. True is
  564. /// passed when the blocks are analyzable to allow for fallthrough to be
  565. /// handled.
  566. /// @return false if the shared portion prevents if conversion.
  567. bool IfConverter::CountDuplicatedInstructions(
  568. MachineBasicBlock::iterator &TIB,
  569. MachineBasicBlock::iterator &FIB,
  570. MachineBasicBlock::iterator &TIE,
  571. MachineBasicBlock::iterator &FIE,
  572. unsigned &Dups1, unsigned &Dups2,
  573. MachineBasicBlock &TBB, MachineBasicBlock &FBB,
  574. bool SkipUnconditionalBranches) const {
  575. while (TIB != TIE && FIB != FIE) {
  576. // Skip dbg_value instructions. These do not count.
  577. TIB = skipDebugInstructionsForward(TIB, TIE);
  578. FIB = skipDebugInstructionsForward(FIB, FIE);
  579. if (TIB == TIE || FIB == FIE)
  580. break;
  581. if (!TIB->isIdenticalTo(*FIB))
  582. break;
  583. // A pred-clobbering instruction in the shared portion prevents
  584. // if-conversion.
  585. std::vector<MachineOperand> PredDefs;
  586. if (TII->DefinesPredicate(*TIB, PredDefs))
  587. return false;
  588. // If we get all the way to the branch instructions, don't count them.
  589. if (!TIB->isBranch())
  590. ++Dups1;
  591. ++TIB;
  592. ++FIB;
  593. }
  594. // Check for already containing all of the block.
  595. if (TIB == TIE || FIB == FIE)
  596. return true;
  597. // Now, in preparation for counting duplicate instructions at the ends of the
  598. // blocks, switch to reverse_iterators. Note that getReverse() returns an
  599. // iterator that points to the same instruction, unlike std::reverse_iterator.
  600. // We have to do our own shifting so that we get the same range.
  601. MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
  602. MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
  603. const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
  604. const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
  605. if (!TBB.succ_empty() || !FBB.succ_empty()) {
  606. if (SkipUnconditionalBranches) {
  607. while (RTIE != RTIB && RTIE->isUnconditionalBranch())
  608. ++RTIE;
  609. while (RFIE != RFIB && RFIE->isUnconditionalBranch())
  610. ++RFIE;
  611. }
  612. }
  613. // Count duplicate instructions at the ends of the blocks.
  614. while (RTIE != RTIB && RFIE != RFIB) {
  615. // Skip dbg_value instructions. These do not count.
  616. // Note that these are reverse iterators going forward.
  617. RTIE = skipDebugInstructionsForward(RTIE, RTIB);
  618. RFIE = skipDebugInstructionsForward(RFIE, RFIB);
  619. if (RTIE == RTIB || RFIE == RFIB)
  620. break;
  621. if (!RTIE->isIdenticalTo(*RFIE))
  622. break;
  623. // We have to verify that any branch instructions are the same, and then we
  624. // don't count them toward the # of duplicate instructions.
  625. if (!RTIE->isBranch())
  626. ++Dups2;
  627. ++RTIE;
  628. ++RFIE;
  629. }
  630. TIE = std::next(RTIE.getReverse());
  631. FIE = std::next(RFIE.getReverse());
  632. return true;
  633. }
  634. /// RescanInstructions - Run ScanInstructions on a pair of blocks.
  635. /// @param TIB - True Iterator Begin, points to first non-shared instruction
  636. /// @param FIB - False Iterator Begin, points to first non-shared instruction
  637. /// @param TIE - True Iterator End, points past last non-shared instruction
  638. /// @param FIE - False Iterator End, points past last non-shared instruction
  639. /// @param TrueBBI - BBInfo to update for the true block.
  640. /// @param FalseBBI - BBInfo to update for the false block.
  641. /// @returns - false if either block cannot be predicated or if both blocks end
  642. /// with a predicate-clobbering instruction.
  643. bool IfConverter::RescanInstructions(
  644. MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
  645. MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
  646. BBInfo &TrueBBI, BBInfo &FalseBBI) const {
  647. bool BranchUnpredicable = true;
  648. TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
  649. ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
  650. if (TrueBBI.IsUnpredicable)
  651. return false;
  652. ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
  653. if (FalseBBI.IsUnpredicable)
  654. return false;
  655. if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
  656. return false;
  657. return true;
  658. }
  659. #ifndef NDEBUG
  660. static void verifySameBranchInstructions(
  661. MachineBasicBlock *MBB1,
  662. MachineBasicBlock *MBB2) {
  663. const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
  664. const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
  665. MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
  666. MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
  667. while (E1 != B1 && E2 != B2) {
  668. skipDebugInstructionsForward(E1, B1);
  669. skipDebugInstructionsForward(E2, B2);
  670. if (E1 == B1 && E2 == B2)
  671. break;
  672. if (E1 == B1) {
  673. assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
  674. break;
  675. }
  676. if (E2 == B2) {
  677. assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
  678. break;
  679. }
  680. if (E1->isBranch() || E2->isBranch())
  681. assert(E1->isIdenticalTo(*E2) &&
  682. "Branch mis-match, branch instructions don't match.");
  683. else
  684. break;
  685. ++E1;
  686. ++E2;
  687. }
  688. }
  689. #endif
  690. /// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
  691. /// with their common predecessor) form a diamond if a common tail block is
  692. /// extracted.
  693. /// While not strictly a diamond, this pattern would form a diamond if
  694. /// tail-merging had merged the shared tails.
  695. /// EBB
  696. /// _/ \_
  697. /// | |
  698. /// TBB FBB
  699. /// / \ / \
  700. /// FalseBB TrueBB FalseBB
  701. /// Currently only handles analyzable branches.
  702. /// Specifically excludes actual diamonds to avoid overlap.
  703. bool IfConverter::ValidForkedDiamond(
  704. BBInfo &TrueBBI, BBInfo &FalseBBI,
  705. unsigned &Dups1, unsigned &Dups2,
  706. BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
  707. Dups1 = Dups2 = 0;
  708. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
  709. FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
  710. return false;
  711. if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
  712. return false;
  713. // Don't IfConvert blocks that can't be folded into their predecessor.
  714. if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
  715. return false;
  716. // This function is specifically looking for conditional tails, as
  717. // unconditional tails are already handled by the standard diamond case.
  718. if (TrueBBI.BrCond.size() == 0 ||
  719. FalseBBI.BrCond.size() == 0)
  720. return false;
  721. MachineBasicBlock *TT = TrueBBI.TrueBB;
  722. MachineBasicBlock *TF = TrueBBI.FalseBB;
  723. MachineBasicBlock *FT = FalseBBI.TrueBB;
  724. MachineBasicBlock *FF = FalseBBI.FalseBB;
  725. if (!TT)
  726. TT = getNextBlock(*TrueBBI.BB);
  727. if (!TF)
  728. TF = getNextBlock(*TrueBBI.BB);
  729. if (!FT)
  730. FT = getNextBlock(*FalseBBI.BB);
  731. if (!FF)
  732. FF = getNextBlock(*FalseBBI.BB);
  733. if (!TT || !TF)
  734. return false;
  735. // Check successors. If they don't match, bail.
  736. if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
  737. return false;
  738. bool FalseReversed = false;
  739. if (TF == FT && TT == FF) {
  740. // If the branches are opposing, but we can't reverse, don't do it.
  741. if (!FalseBBI.IsBrReversible)
  742. return false;
  743. FalseReversed = true;
  744. reverseBranchCondition(FalseBBI);
  745. }
  746. auto UnReverseOnExit = make_scope_exit([&]() {
  747. if (FalseReversed)
  748. reverseBranchCondition(FalseBBI);
  749. });
  750. // Count duplicate instructions at the beginning of the true and false blocks.
  751. MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
  752. MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
  753. MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
  754. MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
  755. if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
  756. *TrueBBI.BB, *FalseBBI.BB,
  757. /* SkipUnconditionalBranches */ true))
  758. return false;
  759. TrueBBICalc.BB = TrueBBI.BB;
  760. FalseBBICalc.BB = FalseBBI.BB;
  761. if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
  762. return false;
  763. // The size is used to decide whether to if-convert, and the shared portions
  764. // are subtracted off. Because of the subtraction, we just use the size that
  765. // was calculated by the original ScanInstructions, as it is correct.
  766. TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
  767. FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
  768. return true;
  769. }
  770. /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
  771. /// with their common predecessor) forms a valid diamond shape for ifcvt.
  772. bool IfConverter::ValidDiamond(
  773. BBInfo &TrueBBI, BBInfo &FalseBBI,
  774. unsigned &Dups1, unsigned &Dups2,
  775. BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
  776. Dups1 = Dups2 = 0;
  777. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
  778. FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
  779. return false;
  780. MachineBasicBlock *TT = TrueBBI.TrueBB;
  781. MachineBasicBlock *FT = FalseBBI.TrueBB;
  782. if (!TT && blockAlwaysFallThrough(TrueBBI))
  783. TT = getNextBlock(*TrueBBI.BB);
  784. if (!FT && blockAlwaysFallThrough(FalseBBI))
  785. FT = getNextBlock(*FalseBBI.BB);
  786. if (TT != FT)
  787. return false;
  788. if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
  789. return false;
  790. if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
  791. return false;
  792. // FIXME: Allow true block to have an early exit?
  793. if (TrueBBI.FalseBB || FalseBBI.FalseBB)
  794. return false;
  795. // Count duplicate instructions at the beginning and end of the true and
  796. // false blocks.
  797. // Skip unconditional branches only if we are considering an analyzable
  798. // diamond. Otherwise the branches must be the same.
  799. bool SkipUnconditionalBranches =
  800. TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
  801. MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
  802. MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
  803. MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
  804. MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
  805. if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
  806. *TrueBBI.BB, *FalseBBI.BB,
  807. SkipUnconditionalBranches))
  808. return false;
  809. TrueBBICalc.BB = TrueBBI.BB;
  810. FalseBBICalc.BB = FalseBBI.BB;
  811. if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
  812. return false;
  813. // The size is used to decide whether to if-convert, and the shared portions
  814. // are subtracted off. Because of the subtraction, we just use the size that
  815. // was calculated by the original ScanInstructions, as it is correct.
  816. TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
  817. FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
  818. return true;
  819. }
  820. /// AnalyzeBranches - Look at the branches at the end of a block to determine if
  821. /// the block is predicable.
  822. void IfConverter::AnalyzeBranches(BBInfo &BBI) {
  823. if (BBI.IsDone)
  824. return;
  825. BBI.TrueBB = BBI.FalseBB = nullptr;
  826. BBI.BrCond.clear();
  827. BBI.IsBrAnalyzable =
  828. !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
  829. if (!BBI.IsBrAnalyzable) {
  830. BBI.TrueBB = nullptr;
  831. BBI.FalseBB = nullptr;
  832. BBI.BrCond.clear();
  833. }
  834. SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
  835. BBI.IsBrReversible = (RevCond.size() == 0) ||
  836. !TII->reverseBranchCondition(RevCond);
  837. BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
  838. if (BBI.BrCond.size()) {
  839. // No false branch. This BB must end with a conditional branch and a
  840. // fallthrough.
  841. if (!BBI.FalseBB)
  842. BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
  843. if (!BBI.FalseBB) {
  844. // Malformed bcc? True and false blocks are the same?
  845. BBI.IsUnpredicable = true;
  846. }
  847. }
  848. }
  849. /// ScanInstructions - Scan all the instructions in the block to determine if
  850. /// the block is predicable. In most cases, that means all the instructions
  851. /// in the block are isPredicable(). Also checks if the block contains any
  852. /// instruction which can clobber a predicate (e.g. condition code register).
  853. /// If so, the block is not predicable unless it's the last instruction.
  854. void IfConverter::ScanInstructions(BBInfo &BBI,
  855. MachineBasicBlock::iterator &Begin,
  856. MachineBasicBlock::iterator &End,
  857. bool BranchUnpredicable) const {
  858. if (BBI.IsDone || BBI.IsUnpredicable)
  859. return;
  860. bool AlreadyPredicated = !BBI.Predicate.empty();
  861. BBI.NonPredSize = 0;
  862. BBI.ExtraCost = 0;
  863. BBI.ExtraCost2 = 0;
  864. BBI.ClobbersPred = false;
  865. for (MachineInstr &MI : make_range(Begin, End)) {
  866. if (MI.isDebugInstr())
  867. continue;
  868. // It's unsafe to duplicate convergent instructions in this context, so set
  869. // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
  870. // following CFG, which is subject to our "simple" transformation.
  871. //
  872. // BB0 // if (c1) goto BB1; else goto BB2;
  873. // / \
  874. // BB1 |
  875. // | BB2 // if (c2) goto TBB; else goto FBB;
  876. // | / |
  877. // | / |
  878. // TBB |
  879. // | |
  880. // | FBB
  881. // |
  882. // exit
  883. //
  884. // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
  885. // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
  886. // TBB contains a convergent instruction. This is safe iff doing so does
  887. // not add a control-flow dependency to the convergent instruction -- i.e.,
  888. // it's safe iff the set of control flows that leads us to the convergent
  889. // instruction does not get smaller after the transformation.
  890. //
  891. // Originally we executed TBB if c1 || c2. After the transformation, there
  892. // are two copies of TBB's instructions. We get to the first if c1, and we
  893. // get to the second if !c1 && c2.
  894. //
  895. // There are clearly fewer ways to satisfy the condition "c1" than
  896. // "c1 || c2". Since we've shrunk the set of control flows which lead to
  897. // our convergent instruction, the transformation is unsafe.
  898. if (MI.isNotDuplicable() || MI.isConvergent())
  899. BBI.CannotBeCopied = true;
  900. bool isPredicated = TII->isPredicated(MI);
  901. bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
  902. if (BranchUnpredicable && MI.isBranch()) {
  903. BBI.IsUnpredicable = true;
  904. return;
  905. }
  906. // A conditional branch is not predicable, but it may be eliminated.
  907. if (isCondBr)
  908. continue;
  909. if (!isPredicated) {
  910. BBI.NonPredSize++;
  911. unsigned ExtraPredCost = TII->getPredicationCost(MI);
  912. unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
  913. if (NumCycles > 1)
  914. BBI.ExtraCost += NumCycles-1;
  915. BBI.ExtraCost2 += ExtraPredCost;
  916. } else if (!AlreadyPredicated) {
  917. // FIXME: This instruction is already predicated before the
  918. // if-conversion pass. It's probably something like a conditional move.
  919. // Mark this block unpredicable for now.
  920. BBI.IsUnpredicable = true;
  921. return;
  922. }
  923. if (BBI.ClobbersPred && !isPredicated) {
  924. // Predicate modification instruction should end the block (except for
  925. // already predicated instructions and end of block branches).
  926. // Predicate may have been modified, the subsequent (currently)
  927. // unpredicated instructions cannot be correctly predicated.
  928. BBI.IsUnpredicable = true;
  929. return;
  930. }
  931. // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
  932. // still potentially predicable.
  933. std::vector<MachineOperand> PredDefs;
  934. if (TII->DefinesPredicate(MI, PredDefs))
  935. BBI.ClobbersPred = true;
  936. if (!TII->isPredicable(MI)) {
  937. BBI.IsUnpredicable = true;
  938. return;
  939. }
  940. }
  941. }
  942. /// Determine if the block is a suitable candidate to be predicated by the
  943. /// specified predicate.
  944. /// @param BBI BBInfo for the block to check
  945. /// @param Pred Predicate array for the branch that leads to BBI
  946. /// @param isTriangle true if the Analysis is for a triangle
  947. /// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
  948. /// case
  949. /// @param hasCommonTail true if BBI shares a tail with a sibling block that
  950. /// contains any instruction that would make the block unpredicable.
  951. bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
  952. SmallVectorImpl<MachineOperand> &Pred,
  953. bool isTriangle, bool RevBranch,
  954. bool hasCommonTail) {
  955. // If the block is dead or unpredicable, then it cannot be predicated.
  956. // Two blocks may share a common unpredicable tail, but this doesn't prevent
  957. // them from being if-converted. The non-shared portion is assumed to have
  958. // been checked
  959. if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
  960. return false;
  961. // If it is already predicated but we couldn't analyze its terminator, the
  962. // latter might fallthrough, but we can't determine where to.
  963. // Conservatively avoid if-converting again.
  964. if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
  965. return false;
  966. // If it is already predicated, check if the new predicate subsumes
  967. // its predicate.
  968. if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
  969. return false;
  970. if (!hasCommonTail && BBI.BrCond.size()) {
  971. if (!isTriangle)
  972. return false;
  973. // Test predicate subsumption.
  974. SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
  975. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  976. if (RevBranch) {
  977. if (TII->reverseBranchCondition(Cond))
  978. return false;
  979. }
  980. if (TII->reverseBranchCondition(RevPred) ||
  981. !TII->SubsumesPredicate(Cond, RevPred))
  982. return false;
  983. }
  984. return true;
  985. }
  986. /// Analyze the structure of the sub-CFG starting from the specified block.
  987. /// Record its successors and whether it looks like an if-conversion candidate.
  988. void IfConverter::AnalyzeBlock(
  989. MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
  990. struct BBState {
  991. BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
  992. MachineBasicBlock *MBB;
  993. /// This flag is true if MBB's successors have been analyzed.
  994. bool SuccsAnalyzed;
  995. };
  996. // Push MBB to the stack.
  997. SmallVector<BBState, 16> BBStack(1, MBB);
  998. while (!BBStack.empty()) {
  999. BBState &State = BBStack.back();
  1000. MachineBasicBlock *BB = State.MBB;
  1001. BBInfo &BBI = BBAnalysis[BB->getNumber()];
  1002. if (!State.SuccsAnalyzed) {
  1003. if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
  1004. BBStack.pop_back();
  1005. continue;
  1006. }
  1007. BBI.BB = BB;
  1008. BBI.IsBeingAnalyzed = true;
  1009. AnalyzeBranches(BBI);
  1010. MachineBasicBlock::iterator Begin = BBI.BB->begin();
  1011. MachineBasicBlock::iterator End = BBI.BB->end();
  1012. ScanInstructions(BBI, Begin, End);
  1013. // Unanalyzable or ends with fallthrough or unconditional branch, or if is
  1014. // not considered for ifcvt anymore.
  1015. if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
  1016. BBI.IsBeingAnalyzed = false;
  1017. BBI.IsAnalyzed = true;
  1018. BBStack.pop_back();
  1019. continue;
  1020. }
  1021. // Do not ifcvt if either path is a back edge to the entry block.
  1022. if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
  1023. BBI.IsBeingAnalyzed = false;
  1024. BBI.IsAnalyzed = true;
  1025. BBStack.pop_back();
  1026. continue;
  1027. }
  1028. // Do not ifcvt if true and false fallthrough blocks are the same.
  1029. if (!BBI.FalseBB) {
  1030. BBI.IsBeingAnalyzed = false;
  1031. BBI.IsAnalyzed = true;
  1032. BBStack.pop_back();
  1033. continue;
  1034. }
  1035. // Push the False and True blocks to the stack.
  1036. State.SuccsAnalyzed = true;
  1037. BBStack.push_back(*BBI.FalseBB);
  1038. BBStack.push_back(*BBI.TrueBB);
  1039. continue;
  1040. }
  1041. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1042. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1043. if (TrueBBI.IsDone && FalseBBI.IsDone) {
  1044. BBI.IsBeingAnalyzed = false;
  1045. BBI.IsAnalyzed = true;
  1046. BBStack.pop_back();
  1047. continue;
  1048. }
  1049. SmallVector<MachineOperand, 4>
  1050. RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
  1051. bool CanRevCond = !TII->reverseBranchCondition(RevCond);
  1052. unsigned Dups = 0;
  1053. unsigned Dups2 = 0;
  1054. bool TNeedSub = !TrueBBI.Predicate.empty();
  1055. bool FNeedSub = !FalseBBI.Predicate.empty();
  1056. bool Enqueued = false;
  1057. BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
  1058. if (CanRevCond) {
  1059. BBInfo TrueBBICalc, FalseBBICalc;
  1060. auto feasibleDiamond = [&]() {
  1061. bool MeetsSize = MeetIfcvtSizeLimit(
  1062. *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
  1063. TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
  1064. *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
  1065. FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
  1066. Prediction);
  1067. bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
  1068. /* IsTriangle */ false, /* RevCond */ false,
  1069. /* hasCommonTail */ true);
  1070. bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
  1071. /* IsTriangle */ false, /* RevCond */ false,
  1072. /* hasCommonTail */ true);
  1073. return MeetsSize && TrueFeasible && FalseFeasible;
  1074. };
  1075. if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
  1076. TrueBBICalc, FalseBBICalc)) {
  1077. if (feasibleDiamond()) {
  1078. // Diamond:
  1079. // EBB
  1080. // / \_
  1081. // | |
  1082. // TBB FBB
  1083. // \ /
  1084. // TailBB
  1085. // Note TailBB can be empty.
  1086. Tokens.push_back(std::make_unique<IfcvtToken>(
  1087. BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
  1088. (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
  1089. Enqueued = true;
  1090. }
  1091. } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
  1092. TrueBBICalc, FalseBBICalc)) {
  1093. if (feasibleDiamond()) {
  1094. // ForkedDiamond:
  1095. // if TBB and FBB have a common tail that includes their conditional
  1096. // branch instructions, then we can If Convert this pattern.
  1097. // EBB
  1098. // _/ \_
  1099. // | |
  1100. // TBB FBB
  1101. // / \ / \
  1102. // FalseBB TrueBB FalseBB
  1103. //
  1104. Tokens.push_back(std::make_unique<IfcvtToken>(
  1105. BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
  1106. (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
  1107. Enqueued = true;
  1108. }
  1109. }
  1110. }
  1111. if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
  1112. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  1113. TrueBBI.ExtraCost2, Prediction) &&
  1114. FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
  1115. // Triangle:
  1116. // EBB
  1117. // | \_
  1118. // | |
  1119. // | TBB
  1120. // | /
  1121. // FBB
  1122. Tokens.push_back(
  1123. std::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
  1124. Enqueued = true;
  1125. }
  1126. if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
  1127. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  1128. TrueBBI.ExtraCost2, Prediction) &&
  1129. FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
  1130. Tokens.push_back(
  1131. std::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
  1132. Enqueued = true;
  1133. }
  1134. if (ValidSimple(TrueBBI, Dups, Prediction) &&
  1135. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  1136. TrueBBI.ExtraCost2, Prediction) &&
  1137. FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
  1138. // Simple (split, no rejoin):
  1139. // EBB
  1140. // | \_
  1141. // | |
  1142. // | TBB---> exit
  1143. // |
  1144. // FBB
  1145. Tokens.push_back(
  1146. std::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
  1147. Enqueued = true;
  1148. }
  1149. if (CanRevCond) {
  1150. // Try the other path...
  1151. if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
  1152. Prediction.getCompl()) &&
  1153. MeetIfcvtSizeLimit(*FalseBBI.BB,
  1154. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  1155. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  1156. FeasibilityAnalysis(FalseBBI, RevCond, true)) {
  1157. Tokens.push_back(std::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
  1158. FNeedSub, Dups));
  1159. Enqueued = true;
  1160. }
  1161. if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
  1162. Prediction.getCompl()) &&
  1163. MeetIfcvtSizeLimit(*FalseBBI.BB,
  1164. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  1165. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  1166. FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
  1167. Tokens.push_back(
  1168. std::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
  1169. Enqueued = true;
  1170. }
  1171. if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
  1172. MeetIfcvtSizeLimit(*FalseBBI.BB,
  1173. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  1174. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  1175. FeasibilityAnalysis(FalseBBI, RevCond)) {
  1176. Tokens.push_back(
  1177. std::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
  1178. Enqueued = true;
  1179. }
  1180. }
  1181. BBI.IsEnqueued = Enqueued;
  1182. BBI.IsBeingAnalyzed = false;
  1183. BBI.IsAnalyzed = true;
  1184. BBStack.pop_back();
  1185. }
  1186. }
  1187. /// Analyze all blocks and find entries for all if-conversion candidates.
  1188. void IfConverter::AnalyzeBlocks(
  1189. MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
  1190. for (MachineBasicBlock &MBB : MF)
  1191. AnalyzeBlock(MBB, Tokens);
  1192. // Sort to favor more complex ifcvt scheme.
  1193. llvm::stable_sort(Tokens, IfcvtTokenCmp);
  1194. }
  1195. /// Returns true either if ToMBB is the next block after MBB or that all the
  1196. /// intervening blocks are empty (given MBB can fall through to its next block).
  1197. static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
  1198. MachineFunction::iterator PI = MBB.getIterator();
  1199. MachineFunction::iterator I = std::next(PI);
  1200. MachineFunction::iterator TI = ToMBB.getIterator();
  1201. MachineFunction::iterator E = MBB.getParent()->end();
  1202. while (I != TI) {
  1203. // Check isSuccessor to avoid case where the next block is empty, but
  1204. // it's not a successor.
  1205. if (I == E || !I->empty() || !PI->isSuccessor(&*I))
  1206. return false;
  1207. PI = I++;
  1208. }
  1209. // Finally see if the last I is indeed a successor to PI.
  1210. return PI->isSuccessor(&*I);
  1211. }
  1212. /// Invalidate predecessor BB info so it would be re-analyzed to determine if it
  1213. /// can be if-converted. If predecessor is already enqueued, dequeue it!
  1214. void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
  1215. for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
  1216. BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
  1217. if (PBBI.IsDone || PBBI.BB == &MBB)
  1218. continue;
  1219. PBBI.IsAnalyzed = false;
  1220. PBBI.IsEnqueued = false;
  1221. }
  1222. }
  1223. /// Inserts an unconditional branch from \p MBB to \p ToMBB.
  1224. static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
  1225. const TargetInstrInfo *TII) {
  1226. DebugLoc dl; // FIXME: this is nowhere
  1227. SmallVector<MachineOperand, 0> NoCond;
  1228. TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
  1229. }
  1230. /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
  1231. /// values defined in MI which are also live/used by MI.
  1232. static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
  1233. const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
  1234. // Before stepping forward past MI, remember which regs were live
  1235. // before MI. This is needed to set the Undef flag only when reg is
  1236. // dead.
  1237. SparseSet<MCPhysReg, identity<MCPhysReg>> LiveBeforeMI;
  1238. LiveBeforeMI.setUniverse(TRI->getNumRegs());
  1239. for (unsigned Reg : Redefs)
  1240. LiveBeforeMI.insert(Reg);
  1241. SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Clobbers;
  1242. Redefs.stepForward(MI, Clobbers);
  1243. // Now add the implicit uses for each of the clobbered values.
  1244. for (auto Clobber : Clobbers) {
  1245. // FIXME: Const cast here is nasty, but better than making StepForward
  1246. // take a mutable instruction instead of const.
  1247. unsigned Reg = Clobber.first;
  1248. MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
  1249. MachineInstr *OpMI = Op.getParent();
  1250. MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
  1251. if (Op.isRegMask()) {
  1252. // First handle regmasks. They clobber any entries in the mask which
  1253. // means that we need a def for those registers.
  1254. if (LiveBeforeMI.count(Reg))
  1255. MIB.addReg(Reg, RegState::Implicit);
  1256. // We also need to add an implicit def of this register for the later
  1257. // use to read from.
  1258. // For the register allocator to have allocated a register clobbered
  1259. // by the call which is used later, it must be the case that
  1260. // the call doesn't return.
  1261. MIB.addReg(Reg, RegState::Implicit | RegState::Define);
  1262. continue;
  1263. }
  1264. if (LiveBeforeMI.count(Reg))
  1265. MIB.addReg(Reg, RegState::Implicit);
  1266. else {
  1267. bool HasLiveSubReg = false;
  1268. for (MCSubRegIterator S(Reg, TRI); S.isValid(); ++S) {
  1269. if (!LiveBeforeMI.count(*S))
  1270. continue;
  1271. HasLiveSubReg = true;
  1272. break;
  1273. }
  1274. if (HasLiveSubReg)
  1275. MIB.addReg(Reg, RegState::Implicit);
  1276. }
  1277. }
  1278. }
  1279. /// If convert a simple (split, no rejoin) sub-CFG.
  1280. bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
  1281. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1282. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1283. BBInfo *CvtBBI = &TrueBBI;
  1284. BBInfo *NextBBI = &FalseBBI;
  1285. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  1286. if (Kind == ICSimpleFalse)
  1287. std::swap(CvtBBI, NextBBI);
  1288. MachineBasicBlock &CvtMBB = *CvtBBI->BB;
  1289. MachineBasicBlock &NextMBB = *NextBBI->BB;
  1290. if (CvtBBI->IsDone ||
  1291. (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
  1292. // Something has changed. It's no longer safe to predicate this block.
  1293. BBI.IsAnalyzed = false;
  1294. CvtBBI->IsAnalyzed = false;
  1295. return false;
  1296. }
  1297. if (CvtMBB.hasAddressTaken())
  1298. // Conservatively abort if-conversion if BB's address is taken.
  1299. return false;
  1300. if (Kind == ICSimpleFalse)
  1301. if (TII->reverseBranchCondition(Cond))
  1302. llvm_unreachable("Unable to reverse branch condition!");
  1303. Redefs.init(*TRI);
  1304. if (MRI->tracksLiveness()) {
  1305. // Initialize liveins to the first BB. These are potentially redefined by
  1306. // predicated instructions.
  1307. Redefs.addLiveIns(CvtMBB);
  1308. Redefs.addLiveIns(NextMBB);
  1309. }
  1310. // Remove the branches from the entry so we can add the contents of the true
  1311. // block to it.
  1312. BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
  1313. if (CvtMBB.pred_size() > 1) {
  1314. // Copy instructions in the true block, predicate them, and add them to
  1315. // the entry block.
  1316. CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
  1317. // Keep the CFG updated.
  1318. BBI.BB->removeSuccessor(&CvtMBB, true);
  1319. } else {
  1320. // Predicate the instructions in the true block.
  1321. PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
  1322. // Merge converted block into entry block. The BB to Cvt edge is removed
  1323. // by MergeBlocks.
  1324. MergeBlocks(BBI, *CvtBBI);
  1325. }
  1326. bool IterIfcvt = true;
  1327. if (!canFallThroughTo(*BBI.BB, NextMBB)) {
  1328. InsertUncondBranch(*BBI.BB, NextMBB, TII);
  1329. BBI.HasFallThrough = false;
  1330. // Now ifcvt'd block will look like this:
  1331. // BB:
  1332. // ...
  1333. // t, f = cmp
  1334. // if t op
  1335. // b BBf
  1336. //
  1337. // We cannot further ifcvt this block because the unconditional branch
  1338. // will have to be predicated on the new condition, that will not be
  1339. // available if cmp executes.
  1340. IterIfcvt = false;
  1341. }
  1342. // Update block info. BB can be iteratively if-converted.
  1343. if (!IterIfcvt)
  1344. BBI.IsDone = true;
  1345. InvalidatePreds(*BBI.BB);
  1346. CvtBBI->IsDone = true;
  1347. // FIXME: Must maintain LiveIns.
  1348. return true;
  1349. }
  1350. /// If convert a triangle sub-CFG.
  1351. bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
  1352. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1353. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1354. BBInfo *CvtBBI = &TrueBBI;
  1355. BBInfo *NextBBI = &FalseBBI;
  1356. DebugLoc dl; // FIXME: this is nowhere
  1357. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  1358. if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
  1359. std::swap(CvtBBI, NextBBI);
  1360. MachineBasicBlock &CvtMBB = *CvtBBI->BB;
  1361. MachineBasicBlock &NextMBB = *NextBBI->BB;
  1362. if (CvtBBI->IsDone ||
  1363. (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
  1364. // Something has changed. It's no longer safe to predicate this block.
  1365. BBI.IsAnalyzed = false;
  1366. CvtBBI->IsAnalyzed = false;
  1367. return false;
  1368. }
  1369. if (CvtMBB.hasAddressTaken())
  1370. // Conservatively abort if-conversion if BB's address is taken.
  1371. return false;
  1372. if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
  1373. if (TII->reverseBranchCondition(Cond))
  1374. llvm_unreachable("Unable to reverse branch condition!");
  1375. if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
  1376. if (reverseBranchCondition(*CvtBBI)) {
  1377. // BB has been changed, modify its predecessors (except for this
  1378. // one) so they don't get ifcvt'ed based on bad intel.
  1379. for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
  1380. if (PBB == BBI.BB)
  1381. continue;
  1382. BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
  1383. if (PBBI.IsEnqueued) {
  1384. PBBI.IsAnalyzed = false;
  1385. PBBI.IsEnqueued = false;
  1386. }
  1387. }
  1388. }
  1389. }
  1390. // Initialize liveins to the first BB. These are potentially redefined by
  1391. // predicated instructions.
  1392. Redefs.init(*TRI);
  1393. if (MRI->tracksLiveness()) {
  1394. Redefs.addLiveIns(CvtMBB);
  1395. Redefs.addLiveIns(NextMBB);
  1396. }
  1397. bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
  1398. BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
  1399. if (HasEarlyExit) {
  1400. // Get probabilities before modifying CvtMBB and BBI.BB.
  1401. CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
  1402. CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
  1403. BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
  1404. BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
  1405. }
  1406. // Remove the branches from the entry so we can add the contents of the true
  1407. // block to it.
  1408. BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
  1409. if (CvtMBB.pred_size() > 1) {
  1410. // Copy instructions in the true block, predicate them, and add them to
  1411. // the entry block.
  1412. CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
  1413. } else {
  1414. // Predicate the 'true' block after removing its branch.
  1415. CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
  1416. PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
  1417. // Now merge the entry of the triangle with the true block.
  1418. MergeBlocks(BBI, *CvtBBI, false);
  1419. }
  1420. // Keep the CFG updated.
  1421. BBI.BB->removeSuccessor(&CvtMBB, true);
  1422. // If 'true' block has a 'false' successor, add an exit branch to it.
  1423. if (HasEarlyExit) {
  1424. SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
  1425. CvtBBI->BrCond.end());
  1426. if (TII->reverseBranchCondition(RevCond))
  1427. llvm_unreachable("Unable to reverse branch condition!");
  1428. // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
  1429. // NewNext = New_Prob(BBI.BB, NextMBB) =
  1430. // Prob(BBI.BB, NextMBB) +
  1431. // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
  1432. // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
  1433. // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
  1434. auto NewTrueBB = getNextBlock(*BBI.BB);
  1435. auto NewNext = BBNext + BBCvt * CvtNext;
  1436. auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
  1437. if (NewTrueBBIter != BBI.BB->succ_end())
  1438. BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
  1439. auto NewFalse = BBCvt * CvtFalse;
  1440. TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
  1441. BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
  1442. }
  1443. // Merge in the 'false' block if the 'false' block has no other
  1444. // predecessors. Otherwise, add an unconditional branch to 'false'.
  1445. bool FalseBBDead = false;
  1446. bool IterIfcvt = true;
  1447. bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
  1448. if (!isFallThrough) {
  1449. // Only merge them if the true block does not fallthrough to the false
  1450. // block. By not merging them, we make it possible to iteratively
  1451. // ifcvt the blocks.
  1452. if (!HasEarlyExit &&
  1453. NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
  1454. !NextMBB.hasAddressTaken()) {
  1455. MergeBlocks(BBI, *NextBBI);
  1456. FalseBBDead = true;
  1457. } else {
  1458. InsertUncondBranch(*BBI.BB, NextMBB, TII);
  1459. BBI.HasFallThrough = false;
  1460. }
  1461. // Mixed predicated and unpredicated code. This cannot be iteratively
  1462. // predicated.
  1463. IterIfcvt = false;
  1464. }
  1465. // Update block info. BB can be iteratively if-converted.
  1466. if (!IterIfcvt)
  1467. BBI.IsDone = true;
  1468. InvalidatePreds(*BBI.BB);
  1469. CvtBBI->IsDone = true;
  1470. if (FalseBBDead)
  1471. NextBBI->IsDone = true;
  1472. // FIXME: Must maintain LiveIns.
  1473. return true;
  1474. }
  1475. /// Common code shared between diamond conversions.
  1476. /// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
  1477. /// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
  1478. /// and FalseBBI
  1479. /// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
  1480. /// and \p FalseBBI
  1481. /// \p RemoveBranch - Remove the common branch of the two blocks before
  1482. /// predicating. Only false for unanalyzable fallthrough
  1483. /// cases. The caller will replace the branch if necessary.
  1484. /// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
  1485. /// unanalyzable fallthrough
  1486. bool IfConverter::IfConvertDiamondCommon(
  1487. BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
  1488. unsigned NumDups1, unsigned NumDups2,
  1489. bool TClobbersPred, bool FClobbersPred,
  1490. bool RemoveBranch, bool MergeAddEdges) {
  1491. if (TrueBBI.IsDone || FalseBBI.IsDone ||
  1492. TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
  1493. // Something has changed. It's no longer safe to predicate these blocks.
  1494. BBI.IsAnalyzed = false;
  1495. TrueBBI.IsAnalyzed = false;
  1496. FalseBBI.IsAnalyzed = false;
  1497. return false;
  1498. }
  1499. if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
  1500. // Conservatively abort if-conversion if either BB has its address taken.
  1501. return false;
  1502. // Put the predicated instructions from the 'true' block before the
  1503. // instructions from the 'false' block, unless the true block would clobber
  1504. // the predicate, in which case, do the opposite.
  1505. BBInfo *BBI1 = &TrueBBI;
  1506. BBInfo *BBI2 = &FalseBBI;
  1507. SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
  1508. if (TII->reverseBranchCondition(RevCond))
  1509. llvm_unreachable("Unable to reverse branch condition!");
  1510. SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
  1511. SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
  1512. // Figure out the more profitable ordering.
  1513. bool DoSwap = false;
  1514. if (TClobbersPred && !FClobbersPred)
  1515. DoSwap = true;
  1516. else if (!TClobbersPred && !FClobbersPred) {
  1517. if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
  1518. DoSwap = true;
  1519. } else if (TClobbersPred && FClobbersPred)
  1520. llvm_unreachable("Predicate info cannot be clobbered by both sides.");
  1521. if (DoSwap) {
  1522. std::swap(BBI1, BBI2);
  1523. std::swap(Cond1, Cond2);
  1524. }
  1525. // Remove the conditional branch from entry to the blocks.
  1526. BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
  1527. MachineBasicBlock &MBB1 = *BBI1->BB;
  1528. MachineBasicBlock &MBB2 = *BBI2->BB;
  1529. // Initialize the Redefs:
  1530. // - BB2 live-in regs need implicit uses before being redefined by BB1
  1531. // instructions.
  1532. // - BB1 live-out regs need implicit uses before being redefined by BB2
  1533. // instructions. We start with BB1 live-ins so we have the live-out regs
  1534. // after tracking the BB1 instructions.
  1535. Redefs.init(*TRI);
  1536. if (MRI->tracksLiveness()) {
  1537. Redefs.addLiveIns(MBB1);
  1538. Redefs.addLiveIns(MBB2);
  1539. }
  1540. // Remove the duplicated instructions at the beginnings of both paths.
  1541. // Skip dbg_value instructions.
  1542. MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
  1543. MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
  1544. BBI1->NonPredSize -= NumDups1;
  1545. BBI2->NonPredSize -= NumDups1;
  1546. // Skip past the dups on each side separately since there may be
  1547. // differing dbg_value entries. NumDups1 can include a "return"
  1548. // instruction, if it's not marked as "branch".
  1549. for (unsigned i = 0; i < NumDups1; ++DI1) {
  1550. if (DI1 == MBB1.end())
  1551. break;
  1552. if (!DI1->isDebugInstr())
  1553. ++i;
  1554. }
  1555. while (NumDups1 != 0) {
  1556. ++DI2;
  1557. if (DI2 == MBB2.end())
  1558. break;
  1559. if (!DI2->isDebugInstr())
  1560. --NumDups1;
  1561. }
  1562. if (MRI->tracksLiveness()) {
  1563. for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
  1564. SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Dummy;
  1565. Redefs.stepForward(MI, Dummy);
  1566. }
  1567. }
  1568. BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
  1569. MBB2.erase(MBB2.begin(), DI2);
  1570. // The branches have been checked to match, so it is safe to remove the
  1571. // branch in BB1 and rely on the copy in BB2. The complication is that
  1572. // the blocks may end with a return instruction, which may or may not
  1573. // be marked as "branch". If it's not, then it could be included in
  1574. // "dups1", leaving the blocks potentially empty after moving the common
  1575. // duplicates.
  1576. #ifndef NDEBUG
  1577. // Unanalyzable branches must match exactly. Check that now.
  1578. if (!BBI1->IsBrAnalyzable)
  1579. verifySameBranchInstructions(&MBB1, &MBB2);
  1580. #endif
  1581. // Remove duplicated instructions from the tail of MBB1: any branch
  1582. // instructions, and the common instructions counted by NumDups2.
  1583. DI1 = MBB1.end();
  1584. while (DI1 != MBB1.begin()) {
  1585. MachineBasicBlock::iterator Prev = std::prev(DI1);
  1586. if (!Prev->isBranch() && !Prev->isDebugInstr())
  1587. break;
  1588. DI1 = Prev;
  1589. }
  1590. for (unsigned i = 0; i != NumDups2; ) {
  1591. // NumDups2 only counted non-dbg_value instructions, so this won't
  1592. // run off the head of the list.
  1593. assert(DI1 != MBB1.begin());
  1594. --DI1;
  1595. // skip dbg_value instructions
  1596. if (!DI1->isDebugInstr())
  1597. ++i;
  1598. }
  1599. MBB1.erase(DI1, MBB1.end());
  1600. DI2 = BBI2->BB->end();
  1601. // The branches have been checked to match. Skip over the branch in the false
  1602. // block so that we don't try to predicate it.
  1603. if (RemoveBranch)
  1604. BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
  1605. else {
  1606. // Make DI2 point to the end of the range where the common "tail"
  1607. // instructions could be found.
  1608. while (DI2 != MBB2.begin()) {
  1609. MachineBasicBlock::iterator Prev = std::prev(DI2);
  1610. if (!Prev->isBranch() && !Prev->isDebugInstr())
  1611. break;
  1612. DI2 = Prev;
  1613. }
  1614. }
  1615. while (NumDups2 != 0) {
  1616. // NumDups2 only counted non-dbg_value instructions, so this won't
  1617. // run off the head of the list.
  1618. assert(DI2 != MBB2.begin());
  1619. --DI2;
  1620. // skip dbg_value instructions
  1621. if (!DI2->isDebugInstr())
  1622. --NumDups2;
  1623. }
  1624. // Remember which registers would later be defined by the false block.
  1625. // This allows us not to predicate instructions in the true block that would
  1626. // later be re-defined. That is, rather than
  1627. // subeq r0, r1, #1
  1628. // addne r0, r1, #1
  1629. // generate:
  1630. // sub r0, r1, #1
  1631. // addne r0, r1, #1
  1632. SmallSet<MCPhysReg, 4> RedefsByFalse;
  1633. SmallSet<MCPhysReg, 4> ExtUses;
  1634. if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
  1635. for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
  1636. if (FI.isDebugInstr())
  1637. continue;
  1638. SmallVector<MCPhysReg, 4> Defs;
  1639. for (const MachineOperand &MO : FI.operands()) {
  1640. if (!MO.isReg())
  1641. continue;
  1642. Register Reg = MO.getReg();
  1643. if (!Reg)
  1644. continue;
  1645. if (MO.isDef()) {
  1646. Defs.push_back(Reg);
  1647. } else if (!RedefsByFalse.count(Reg)) {
  1648. // These are defined before ctrl flow reach the 'false' instructions.
  1649. // They cannot be modified by the 'true' instructions.
  1650. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  1651. SubRegs.isValid(); ++SubRegs)
  1652. ExtUses.insert(*SubRegs);
  1653. }
  1654. }
  1655. for (MCPhysReg Reg : Defs) {
  1656. if (!ExtUses.count(Reg)) {
  1657. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  1658. SubRegs.isValid(); ++SubRegs)
  1659. RedefsByFalse.insert(*SubRegs);
  1660. }
  1661. }
  1662. }
  1663. }
  1664. // Predicate the 'true' block.
  1665. PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
  1666. // After predicating BBI1, if there is a predicated terminator in BBI1 and
  1667. // a non-predicated in BBI2, then we don't want to predicate the one from
  1668. // BBI2. The reason is that if we merged these blocks, we would end up with
  1669. // two predicated terminators in the same block.
  1670. // Also, if the branches in MBB1 and MBB2 were non-analyzable, then don't
  1671. // predicate them either. They were checked to be identical, and so the
  1672. // same branch would happen regardless of which path was taken.
  1673. if (!MBB2.empty() && (DI2 == MBB2.end())) {
  1674. MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
  1675. MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
  1676. bool BB1Predicated = BBI1T != MBB1.end() && TII->isPredicated(*BBI1T);
  1677. bool BB2NonPredicated = BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T);
  1678. if (BB2NonPredicated && (BB1Predicated || !BBI2->IsBrAnalyzable))
  1679. --DI2;
  1680. }
  1681. // Predicate the 'false' block.
  1682. PredicateBlock(*BBI2, DI2, *Cond2);
  1683. // Merge the true block into the entry of the diamond.
  1684. MergeBlocks(BBI, *BBI1, MergeAddEdges);
  1685. MergeBlocks(BBI, *BBI2, MergeAddEdges);
  1686. return true;
  1687. }
  1688. /// If convert an almost-diamond sub-CFG where the true
  1689. /// and false blocks share a common tail.
  1690. bool IfConverter::IfConvertForkedDiamond(
  1691. BBInfo &BBI, IfcvtKind Kind,
  1692. unsigned NumDups1, unsigned NumDups2,
  1693. bool TClobbersPred, bool FClobbersPred) {
  1694. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1695. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1696. // Save the debug location for later.
  1697. DebugLoc dl;
  1698. MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
  1699. if (TIE != TrueBBI.BB->end())
  1700. dl = TIE->getDebugLoc();
  1701. // Removing branches from both blocks is safe, because we have already
  1702. // determined that both blocks have the same branch instructions. The branch
  1703. // will be added back at the end, unpredicated.
  1704. if (!IfConvertDiamondCommon(
  1705. BBI, TrueBBI, FalseBBI,
  1706. NumDups1, NumDups2,
  1707. TClobbersPred, FClobbersPred,
  1708. /* RemoveBranch */ true, /* MergeAddEdges */ true))
  1709. return false;
  1710. // Add back the branch.
  1711. // Debug location saved above when removing the branch from BBI2
  1712. TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
  1713. TrueBBI.BrCond, dl);
  1714. // Update block info.
  1715. BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
  1716. InvalidatePreds(*BBI.BB);
  1717. // FIXME: Must maintain LiveIns.
  1718. return true;
  1719. }
  1720. /// If convert a diamond sub-CFG.
  1721. bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
  1722. unsigned NumDups1, unsigned NumDups2,
  1723. bool TClobbersPred, bool FClobbersPred) {
  1724. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1725. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1726. MachineBasicBlock *TailBB = TrueBBI.TrueBB;
  1727. // True block must fall through or end with an unanalyzable terminator.
  1728. if (!TailBB) {
  1729. if (blockAlwaysFallThrough(TrueBBI))
  1730. TailBB = FalseBBI.TrueBB;
  1731. assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
  1732. }
  1733. if (!IfConvertDiamondCommon(
  1734. BBI, TrueBBI, FalseBBI,
  1735. NumDups1, NumDups2,
  1736. TClobbersPred, FClobbersPred,
  1737. /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
  1738. /* MergeAddEdges */ TailBB == nullptr))
  1739. return false;
  1740. // If the if-converted block falls through or unconditionally branches into
  1741. // the tail block, and the tail block does not have other predecessors, then
  1742. // fold the tail block in as well. Otherwise, unless it falls through to the
  1743. // tail, add a unconditional branch to it.
  1744. if (TailBB) {
  1745. // We need to remove the edges to the true and false blocks manually since
  1746. // we didn't let IfConvertDiamondCommon update the CFG.
  1747. BBI.BB->removeSuccessor(TrueBBI.BB);
  1748. BBI.BB->removeSuccessor(FalseBBI.BB, true);
  1749. BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
  1750. bool CanMergeTail = !TailBBI.HasFallThrough &&
  1751. !TailBBI.BB->hasAddressTaken();
  1752. // The if-converted block can still have a predicated terminator
  1753. // (e.g. a predicated return). If that is the case, we cannot merge
  1754. // it with the tail block.
  1755. MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
  1756. if (TI != BBI.BB->end() && TII->isPredicated(*TI))
  1757. CanMergeTail = false;
  1758. // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
  1759. // check if there are any other predecessors besides those.
  1760. unsigned NumPreds = TailBB->pred_size();
  1761. if (NumPreds > 1)
  1762. CanMergeTail = false;
  1763. else if (NumPreds == 1 && CanMergeTail) {
  1764. MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
  1765. if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
  1766. CanMergeTail = false;
  1767. }
  1768. if (CanMergeTail) {
  1769. MergeBlocks(BBI, TailBBI);
  1770. TailBBI.IsDone = true;
  1771. } else {
  1772. BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
  1773. InsertUncondBranch(*BBI.BB, *TailBB, TII);
  1774. BBI.HasFallThrough = false;
  1775. }
  1776. }
  1777. // Update block info.
  1778. BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
  1779. InvalidatePreds(*BBI.BB);
  1780. // FIXME: Must maintain LiveIns.
  1781. return true;
  1782. }
  1783. static bool MaySpeculate(const MachineInstr &MI,
  1784. SmallSet<MCPhysReg, 4> &LaterRedefs) {
  1785. bool SawStore = true;
  1786. if (!MI.isSafeToMove(nullptr, SawStore))
  1787. return false;
  1788. for (const MachineOperand &MO : MI.operands()) {
  1789. if (!MO.isReg())
  1790. continue;
  1791. Register Reg = MO.getReg();
  1792. if (!Reg)
  1793. continue;
  1794. if (MO.isDef() && !LaterRedefs.count(Reg))
  1795. return false;
  1796. }
  1797. return true;
  1798. }
  1799. /// Predicate instructions from the start of the block to the specified end with
  1800. /// the specified condition.
  1801. void IfConverter::PredicateBlock(BBInfo &BBI,
  1802. MachineBasicBlock::iterator E,
  1803. SmallVectorImpl<MachineOperand> &Cond,
  1804. SmallSet<MCPhysReg, 4> *LaterRedefs) {
  1805. bool AnyUnpred = false;
  1806. bool MaySpec = LaterRedefs != nullptr;
  1807. for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
  1808. if (I.isDebugInstr() || TII->isPredicated(I))
  1809. continue;
  1810. // It may be possible not to predicate an instruction if it's the 'true'
  1811. // side of a diamond and the 'false' side may re-define the instruction's
  1812. // defs.
  1813. if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
  1814. AnyUnpred = true;
  1815. continue;
  1816. }
  1817. // If any instruction is predicated, then every instruction after it must
  1818. // be predicated.
  1819. MaySpec = false;
  1820. if (!TII->PredicateInstruction(I, Cond)) {
  1821. #ifndef NDEBUG
  1822. dbgs() << "Unable to predicate " << I << "!\n";
  1823. #endif
  1824. llvm_unreachable(nullptr);
  1825. }
  1826. // If the predicated instruction now redefines a register as the result of
  1827. // if-conversion, add an implicit kill.
  1828. UpdatePredRedefs(I, Redefs);
  1829. }
  1830. BBI.Predicate.append(Cond.begin(), Cond.end());
  1831. BBI.IsAnalyzed = false;
  1832. BBI.NonPredSize = 0;
  1833. ++NumIfConvBBs;
  1834. if (AnyUnpred)
  1835. ++NumUnpred;
  1836. }
  1837. /// Copy and predicate instructions from source BB to the destination block.
  1838. /// Skip end of block branches if IgnoreBr is true.
  1839. void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
  1840. SmallVectorImpl<MachineOperand> &Cond,
  1841. bool IgnoreBr) {
  1842. MachineFunction &MF = *ToBBI.BB->getParent();
  1843. MachineBasicBlock &FromMBB = *FromBBI.BB;
  1844. for (MachineInstr &I : FromMBB) {
  1845. // Do not copy the end of the block branches.
  1846. if (IgnoreBr && I.isBranch())
  1847. break;
  1848. MachineInstr *MI = MF.CloneMachineInstr(&I);
  1849. ToBBI.BB->insert(ToBBI.BB->end(), MI);
  1850. ToBBI.NonPredSize++;
  1851. unsigned ExtraPredCost = TII->getPredicationCost(I);
  1852. unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
  1853. if (NumCycles > 1)
  1854. ToBBI.ExtraCost += NumCycles-1;
  1855. ToBBI.ExtraCost2 += ExtraPredCost;
  1856. if (!TII->isPredicated(I) && !MI->isDebugInstr()) {
  1857. if (!TII->PredicateInstruction(*MI, Cond)) {
  1858. #ifndef NDEBUG
  1859. dbgs() << "Unable to predicate " << I << "!\n";
  1860. #endif
  1861. llvm_unreachable(nullptr);
  1862. }
  1863. }
  1864. // If the predicated instruction now redefines a register as the result of
  1865. // if-conversion, add an implicit kill.
  1866. UpdatePredRedefs(*MI, Redefs);
  1867. }
  1868. if (!IgnoreBr) {
  1869. std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
  1870. FromMBB.succ_end());
  1871. MachineBasicBlock *NBB = getNextBlock(FromMBB);
  1872. MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
  1873. for (MachineBasicBlock *Succ : Succs) {
  1874. // Fallthrough edge can't be transferred.
  1875. if (Succ == FallThrough)
  1876. continue;
  1877. ToBBI.BB->addSuccessor(Succ);
  1878. }
  1879. }
  1880. ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
  1881. ToBBI.Predicate.append(Cond.begin(), Cond.end());
  1882. ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
  1883. ToBBI.IsAnalyzed = false;
  1884. ++NumDupBBs;
  1885. }
  1886. /// Move all instructions from FromBB to the end of ToBB. This will leave
  1887. /// FromBB as an empty block, so remove all of its successor edges except for
  1888. /// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
  1889. /// being moved, add those successor edges to ToBBI and remove the old edge
  1890. /// from ToBBI to FromBBI.
  1891. void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
  1892. MachineBasicBlock &FromMBB = *FromBBI.BB;
  1893. assert(!FromMBB.hasAddressTaken() &&
  1894. "Removing a BB whose address is taken!");
  1895. // In case FromMBB contains terminators (e.g. return instruction),
  1896. // first move the non-terminator instructions, then the terminators.
  1897. MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
  1898. MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
  1899. ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
  1900. // If FromBB has non-predicated terminator we should copy it at the end.
  1901. if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
  1902. ToTI = ToBBI.BB->end();
  1903. ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
  1904. // Force normalizing the successors' probabilities of ToBBI.BB to convert all
  1905. // unknown probabilities into known ones.
  1906. // FIXME: This usage is too tricky and in the future we would like to
  1907. // eliminate all unknown probabilities in MBB.
  1908. if (ToBBI.IsBrAnalyzable)
  1909. ToBBI.BB->normalizeSuccProbs();
  1910. SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
  1911. FromMBB.succ_end());
  1912. MachineBasicBlock *NBB = getNextBlock(FromMBB);
  1913. MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
  1914. // The edge probability from ToBBI.BB to FromMBB, which is only needed when
  1915. // AddEdges is true and FromMBB is a successor of ToBBI.BB.
  1916. auto To2FromProb = BranchProbability::getZero();
  1917. if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
  1918. // Remove the old edge but remember the edge probability so we can calculate
  1919. // the correct weights on the new edges being added further down.
  1920. To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
  1921. ToBBI.BB->removeSuccessor(&FromMBB);
  1922. }
  1923. for (MachineBasicBlock *Succ : FromSuccs) {
  1924. // Fallthrough edge can't be transferred.
  1925. if (Succ == FallThrough)
  1926. continue;
  1927. auto NewProb = BranchProbability::getZero();
  1928. if (AddEdges) {
  1929. // Calculate the edge probability for the edge from ToBBI.BB to Succ,
  1930. // which is a portion of the edge probability from FromMBB to Succ. The
  1931. // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
  1932. // FromBBI is a successor of ToBBI.BB. See comment below for exception).
  1933. NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
  1934. // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
  1935. // only happens when if-converting a diamond CFG and FromMBB is the
  1936. // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
  1937. // could just use the probabilities on FromMBB's out-edges when adding
  1938. // new successors.
  1939. if (!To2FromProb.isZero())
  1940. NewProb *= To2FromProb;
  1941. }
  1942. FromMBB.removeSuccessor(Succ);
  1943. if (AddEdges) {
  1944. // If the edge from ToBBI.BB to Succ already exists, update the
  1945. // probability of this edge by adding NewProb to it. An example is shown
  1946. // below, in which A is ToBBI.BB and B is FromMBB. In this case we
  1947. // don't have to set C as A's successor as it already is. We only need to
  1948. // update the edge probability on A->C. Note that B will not be
  1949. // immediately removed from A's successors. It is possible that B->D is
  1950. // not removed either if D is a fallthrough of B. Later the edge A->D
  1951. // (generated here) and B->D will be combined into one edge. To maintain
  1952. // correct edge probability of this combined edge, we need to set the edge
  1953. // probability of A->B to zero, which is already done above. The edge
  1954. // probability on A->D is calculated by scaling the original probability
  1955. // on A->B by the probability of B->D.
  1956. //
  1957. // Before ifcvt: After ifcvt (assume B->D is kept):
  1958. //
  1959. // A A
  1960. // /| /|\
  1961. // / B / B|
  1962. // | /| | ||
  1963. // |/ | | |/
  1964. // C D C D
  1965. //
  1966. if (ToBBI.BB->isSuccessor(Succ))
  1967. ToBBI.BB->setSuccProbability(
  1968. find(ToBBI.BB->successors(), Succ),
  1969. MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
  1970. else
  1971. ToBBI.BB->addSuccessor(Succ, NewProb);
  1972. }
  1973. }
  1974. // Move the now empty FromMBB out of the way to the end of the function so
  1975. // it doesn't interfere with fallthrough checks done by canFallThroughTo().
  1976. MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
  1977. if (Last != &FromMBB)
  1978. FromMBB.moveAfter(Last);
  1979. // Normalize the probabilities of ToBBI.BB's successors with all adjustment
  1980. // we've done above.
  1981. if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
  1982. ToBBI.BB->normalizeSuccProbs();
  1983. ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
  1984. FromBBI.Predicate.clear();
  1985. ToBBI.NonPredSize += FromBBI.NonPredSize;
  1986. ToBBI.ExtraCost += FromBBI.ExtraCost;
  1987. ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
  1988. FromBBI.NonPredSize = 0;
  1989. FromBBI.ExtraCost = 0;
  1990. FromBBI.ExtraCost2 = 0;
  1991. ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
  1992. ToBBI.HasFallThrough = FromBBI.HasFallThrough;
  1993. ToBBI.IsAnalyzed = false;
  1994. FromBBI.IsAnalyzed = false;
  1995. }
  1996. FunctionPass *
  1997. llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
  1998. return new IfConverter(std::move(Ftor));
  1999. }