IfConversion.cpp 83 KB

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