IfConversion.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727
  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.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/Passes.h"
  14. #include "BranchFolding.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallSet.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/CodeGen/LivePhysRegs.h"
  19. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  20. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  21. #include "llvm/CodeGen/MachineFunctionPass.h"
  22. #include "llvm/CodeGen/MachineInstrBuilder.h"
  23. #include "llvm/CodeGen/MachineModuleInfo.h"
  24. #include "llvm/CodeGen/MachineRegisterInfo.h"
  25. #include "llvm/CodeGen/TargetSchedule.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/Target/TargetInstrInfo.h"
  31. #include "llvm/Target/TargetLowering.h"
  32. #include "llvm/Target/TargetRegisterInfo.h"
  33. #include "llvm/Target/TargetSubtargetInfo.h"
  34. using namespace llvm;
  35. #define DEBUG_TYPE "ifcvt"
  36. // Hidden options for help debugging.
  37. static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
  38. static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
  39. static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
  40. static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
  41. cl::init(false), cl::Hidden);
  42. static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
  43. cl::init(false), cl::Hidden);
  44. static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
  45. cl::init(false), cl::Hidden);
  46. static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
  47. cl::init(false), cl::Hidden);
  48. static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
  49. cl::init(false), cl::Hidden);
  50. static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
  51. cl::init(false), cl::Hidden);
  52. static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
  53. cl::init(false), cl::Hidden);
  54. static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
  55. cl::init(true), cl::Hidden);
  56. STATISTIC(NumSimple, "Number of simple if-conversions performed");
  57. STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
  58. STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
  59. STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
  60. STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
  61. STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
  62. STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
  63. STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
  64. STATISTIC(NumDupBBs, "Number of duplicated blocks");
  65. STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
  66. namespace {
  67. class IfConverter : public MachineFunctionPass {
  68. enum IfcvtKind {
  69. ICNotClassfied, // BB data valid, but not classified.
  70. ICSimpleFalse, // Same as ICSimple, but on the false path.
  71. ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
  72. ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
  73. ICTriangleRev, // Same as ICTriangle, but true path rev condition.
  74. ICTriangleFalse, // Same as ICTriangle, but on the false path.
  75. ICTriangle, // BB is entry of a triangle sub-CFG.
  76. ICDiamond // BB is entry of a diamond sub-CFG.
  77. };
  78. /// BBInfo - One per MachineBasicBlock, this is used to cache the result
  79. /// if-conversion feasibility analysis. This includes results from
  80. /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
  81. /// classification, and common tail block of its successors (if it's a
  82. /// diamond shape), its size, whether it's predicable, and whether any
  83. /// instruction can clobber the 'would-be' predicate.
  84. ///
  85. /// IsDone - True if BB is not to be considered for ifcvt.
  86. /// IsBeingAnalyzed - True if BB is currently being analyzed.
  87. /// IsAnalyzed - True if BB has been analyzed (info is still valid).
  88. /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
  89. /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
  90. /// HasFallThrough - True if BB may fallthrough to the following BB.
  91. /// IsUnpredicable - True if BB is known to be unpredicable.
  92. /// ClobbersPred - True if BB could modify predicates (e.g. has
  93. /// cmp, call, etc.)
  94. /// NonPredSize - Number of non-predicated instructions.
  95. /// ExtraCost - Extra cost for multi-cycle instructions.
  96. /// ExtraCost2 - Some instructions are slower when predicated
  97. /// BB - Corresponding MachineBasicBlock.
  98. /// TrueBB / FalseBB- See AnalyzeBranch().
  99. /// BrCond - Conditions for end of block conditional branches.
  100. /// Predicate - Predicate used in the BB.
  101. struct BBInfo {
  102. bool IsDone : 1;
  103. bool IsBeingAnalyzed : 1;
  104. bool IsAnalyzed : 1;
  105. bool IsEnqueued : 1;
  106. bool IsBrAnalyzable : 1;
  107. bool HasFallThrough : 1;
  108. bool IsUnpredicable : 1;
  109. bool CannotBeCopied : 1;
  110. bool ClobbersPred : 1;
  111. unsigned NonPredSize;
  112. unsigned ExtraCost;
  113. unsigned ExtraCost2;
  114. MachineBasicBlock *BB;
  115. MachineBasicBlock *TrueBB;
  116. MachineBasicBlock *FalseBB;
  117. SmallVector<MachineOperand, 4> BrCond;
  118. SmallVector<MachineOperand, 4> Predicate;
  119. BBInfo() : IsDone(false), IsBeingAnalyzed(false),
  120. IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
  121. HasFallThrough(false), IsUnpredicable(false),
  122. CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
  123. ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
  124. FalseBB(nullptr) {}
  125. };
  126. /// IfcvtToken - Record information about pending if-conversions to attempt:
  127. /// BBI - Corresponding BBInfo.
  128. /// Kind - Type of block. See IfcvtKind.
  129. /// NeedSubsumption - True if the to-be-predicated BB has already been
  130. /// predicated.
  131. /// NumDups - Number of instructions that would be duplicated due
  132. /// to this if-conversion. (For diamonds, the number of
  133. /// identical instructions at the beginnings of both
  134. /// paths).
  135. /// NumDups2 - For diamonds, the number of identical instructions
  136. /// at the ends of both paths.
  137. struct IfcvtToken {
  138. BBInfo &BBI;
  139. IfcvtKind Kind;
  140. bool NeedSubsumption;
  141. unsigned NumDups;
  142. unsigned NumDups2;
  143. IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
  144. : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
  145. };
  146. /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
  147. /// basic block number.
  148. std::vector<BBInfo> BBAnalysis;
  149. TargetSchedModel SchedModel;
  150. const TargetLoweringBase *TLI;
  151. const TargetInstrInfo *TII;
  152. const TargetRegisterInfo *TRI;
  153. const MachineBlockFrequencyInfo *MBFI;
  154. const MachineBranchProbabilityInfo *MBPI;
  155. MachineRegisterInfo *MRI;
  156. LivePhysRegs Redefs;
  157. LivePhysRegs DontKill;
  158. bool PreRegAlloc;
  159. bool MadeChange;
  160. int FnNum;
  161. std::function<bool(const Function &)> PredicateFtor;
  162. public:
  163. static char ID;
  164. IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
  165. : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(Ftor) {
  166. initializeIfConverterPass(*PassRegistry::getPassRegistry());
  167. }
  168. void getAnalysisUsage(AnalysisUsage &AU) const override {
  169. AU.addRequired<MachineBlockFrequencyInfo>();
  170. AU.addRequired<MachineBranchProbabilityInfo>();
  171. MachineFunctionPass::getAnalysisUsage(AU);
  172. }
  173. bool runOnMachineFunction(MachineFunction &MF) override;
  174. private:
  175. bool ReverseBranchCondition(BBInfo &BBI);
  176. bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
  177. const BranchProbability &Prediction) const;
  178. bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
  179. bool FalseBranch, unsigned &Dups,
  180. const BranchProbability &Prediction) const;
  181. bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
  182. unsigned &Dups1, unsigned &Dups2) const;
  183. void ScanInstructions(BBInfo &BBI);
  184. void AnalyzeBlock(MachineBasicBlock *MBB, std::vector<IfcvtToken*> &Tokens);
  185. bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
  186. bool isTriangle = false, bool RevBranch = false);
  187. void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
  188. void InvalidatePreds(MachineBasicBlock *BB);
  189. void RemoveExtraEdges(BBInfo &BBI);
  190. bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
  191. bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
  192. bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
  193. unsigned NumDups1, unsigned NumDups2);
  194. void PredicateBlock(BBInfo &BBI,
  195. MachineBasicBlock::iterator E,
  196. SmallVectorImpl<MachineOperand> &Cond,
  197. SmallSet<unsigned, 4> *LaterRedefs = nullptr);
  198. void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
  199. SmallVectorImpl<MachineOperand> &Cond,
  200. bool IgnoreBr = false);
  201. void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
  202. bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
  203. unsigned Cycle, unsigned Extra,
  204. const BranchProbability &Prediction) const {
  205. return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
  206. Prediction);
  207. }
  208. bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
  209. unsigned TCycle, unsigned TExtra,
  210. MachineBasicBlock &FBB,
  211. unsigned FCycle, unsigned FExtra,
  212. const BranchProbability &Prediction) const {
  213. return TCycle > 0 && FCycle > 0 &&
  214. TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
  215. Prediction);
  216. }
  217. // blockAlwaysFallThrough - Block ends without a terminator.
  218. bool blockAlwaysFallThrough(BBInfo &BBI) const {
  219. return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
  220. }
  221. // IfcvtTokenCmp - Used to sort if-conversion candidates.
  222. static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
  223. int Incr1 = (C1->Kind == ICDiamond)
  224. ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
  225. int Incr2 = (C2->Kind == ICDiamond)
  226. ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
  227. if (Incr1 > Incr2)
  228. return true;
  229. else if (Incr1 == Incr2) {
  230. // Favors subsumption.
  231. if (!C1->NeedSubsumption && C2->NeedSubsumption)
  232. return true;
  233. else if (C1->NeedSubsumption == C2->NeedSubsumption) {
  234. // Favors diamond over triangle, etc.
  235. if ((unsigned)C1->Kind < (unsigned)C2->Kind)
  236. return true;
  237. else if (C1->Kind == C2->Kind)
  238. return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
  239. }
  240. }
  241. return false;
  242. }
  243. };
  244. char IfConverter::ID = 0;
  245. }
  246. char &llvm::IfConverterID = IfConverter::ID;
  247. INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
  248. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  249. INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
  250. bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
  251. if (PredicateFtor && !PredicateFtor(*MF.getFunction()))
  252. return false;
  253. const TargetSubtargetInfo &ST = MF.getSubtarget();
  254. TLI = ST.getTargetLowering();
  255. TII = ST.getInstrInfo();
  256. TRI = ST.getRegisterInfo();
  257. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  258. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  259. MRI = &MF.getRegInfo();
  260. SchedModel.init(ST.getSchedModel(), &ST, TII);
  261. if (!TII) return false;
  262. PreRegAlloc = MRI->isSSA();
  263. bool BFChange = false;
  264. if (!PreRegAlloc) {
  265. // Tail merge tend to expose more if-conversion opportunities.
  266. BranchFolder BF(true, false, *MBFI, *MBPI);
  267. BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
  268. getAnalysisIfAvailable<MachineModuleInfo>());
  269. }
  270. DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
  271. << MF.getName() << "\'");
  272. if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
  273. DEBUG(dbgs() << " skipped\n");
  274. return false;
  275. }
  276. DEBUG(dbgs() << "\n");
  277. MF.RenumberBlocks();
  278. BBAnalysis.resize(MF.getNumBlockIDs());
  279. std::vector<IfcvtToken*> Tokens;
  280. MadeChange = false;
  281. unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
  282. NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
  283. while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
  284. // Do an initial analysis for each basic block and find all the potential
  285. // candidates to perform if-conversion.
  286. bool Change = false;
  287. AnalyzeBlocks(MF, Tokens);
  288. while (!Tokens.empty()) {
  289. IfcvtToken *Token = Tokens.back();
  290. Tokens.pop_back();
  291. BBInfo &BBI = Token->BBI;
  292. IfcvtKind Kind = Token->Kind;
  293. unsigned NumDups = Token->NumDups;
  294. unsigned NumDups2 = Token->NumDups2;
  295. delete Token;
  296. // If the block has been evicted out of the queue or it has already been
  297. // marked dead (due to it being predicated), then skip it.
  298. if (BBI.IsDone)
  299. BBI.IsEnqueued = false;
  300. if (!BBI.IsEnqueued)
  301. continue;
  302. BBI.IsEnqueued = false;
  303. bool RetVal = false;
  304. switch (Kind) {
  305. default: llvm_unreachable("Unexpected!");
  306. case ICSimple:
  307. case ICSimpleFalse: {
  308. bool isFalse = Kind == ICSimpleFalse;
  309. if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
  310. DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
  311. " false" : "")
  312. << "): BB#" << BBI.BB->getNumber() << " ("
  313. << ((Kind == ICSimpleFalse)
  314. ? BBI.FalseBB->getNumber()
  315. : BBI.TrueBB->getNumber()) << ") ");
  316. RetVal = IfConvertSimple(BBI, Kind);
  317. DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  318. if (RetVal) {
  319. if (isFalse) ++NumSimpleFalse;
  320. else ++NumSimple;
  321. }
  322. break;
  323. }
  324. case ICTriangle:
  325. case ICTriangleRev:
  326. case ICTriangleFalse:
  327. case ICTriangleFRev: {
  328. bool isFalse = Kind == ICTriangleFalse;
  329. bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
  330. if (DisableTriangle && !isFalse && !isRev) break;
  331. if (DisableTriangleR && !isFalse && isRev) break;
  332. if (DisableTriangleF && isFalse && !isRev) break;
  333. if (DisableTriangleFR && isFalse && isRev) break;
  334. DEBUG(dbgs() << "Ifcvt (Triangle");
  335. if (isFalse)
  336. DEBUG(dbgs() << " false");
  337. if (isRev)
  338. DEBUG(dbgs() << " rev");
  339. DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
  340. << BBI.TrueBB->getNumber() << ",F:"
  341. << BBI.FalseBB->getNumber() << ") ");
  342. RetVal = IfConvertTriangle(BBI, Kind);
  343. DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  344. if (RetVal) {
  345. if (isFalse) {
  346. if (isRev) ++NumTriangleFRev;
  347. else ++NumTriangleFalse;
  348. } else {
  349. if (isRev) ++NumTriangleRev;
  350. else ++NumTriangle;
  351. }
  352. }
  353. break;
  354. }
  355. case ICDiamond: {
  356. if (DisableDiamond) break;
  357. DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
  358. << BBI.TrueBB->getNumber() << ",F:"
  359. << BBI.FalseBB->getNumber() << ") ");
  360. RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
  361. DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  362. if (RetVal) ++NumDiamonds;
  363. break;
  364. }
  365. }
  366. Change |= RetVal;
  367. NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
  368. NumTriangleFalse + NumTriangleFRev + NumDiamonds;
  369. if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
  370. break;
  371. }
  372. if (!Change)
  373. break;
  374. MadeChange |= Change;
  375. }
  376. // Delete tokens in case of early exit.
  377. while (!Tokens.empty()) {
  378. IfcvtToken *Token = Tokens.back();
  379. Tokens.pop_back();
  380. delete Token;
  381. }
  382. Tokens.clear();
  383. BBAnalysis.clear();
  384. if (MadeChange && IfCvtBranchFold) {
  385. BranchFolder BF(false, false, *MBFI, *MBPI);
  386. BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
  387. getAnalysisIfAvailable<MachineModuleInfo>());
  388. }
  389. MadeChange |= BFChange;
  390. return MadeChange;
  391. }
  392. /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
  393. /// its 'true' successor.
  394. static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
  395. MachineBasicBlock *TrueBB) {
  396. for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
  397. E = BB->succ_end(); SI != E; ++SI) {
  398. MachineBasicBlock *SuccBB = *SI;
  399. if (SuccBB != TrueBB)
  400. return SuccBB;
  401. }
  402. return nullptr;
  403. }
  404. /// ReverseBranchCondition - Reverse the condition of the end of the block
  405. /// branch. Swap block's 'true' and 'false' successors.
  406. bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
  407. DebugLoc dl; // FIXME: this is nowhere
  408. if (!TII->ReverseBranchCondition(BBI.BrCond)) {
  409. TII->RemoveBranch(*BBI.BB);
  410. TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
  411. std::swap(BBI.TrueBB, BBI.FalseBB);
  412. return true;
  413. }
  414. return false;
  415. }
  416. /// getNextBlock - Returns the next block in the function blocks ordering. If
  417. /// it is the end, returns NULL.
  418. static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
  419. MachineFunction::iterator I = BB;
  420. MachineFunction::iterator E = BB->getParent()->end();
  421. if (++I == E)
  422. return nullptr;
  423. return I;
  424. }
  425. /// ValidSimple - Returns true if the 'true' block (along with its
  426. /// predecessor) forms a valid simple shape for ifcvt. It also returns the
  427. /// number of instructions that the ifcvt would need to duplicate if performed
  428. /// in Dups.
  429. bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
  430. const BranchProbability &Prediction) const {
  431. Dups = 0;
  432. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
  433. return false;
  434. if (TrueBBI.IsBrAnalyzable)
  435. return false;
  436. if (TrueBBI.BB->pred_size() > 1) {
  437. if (TrueBBI.CannotBeCopied ||
  438. !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
  439. Prediction))
  440. return false;
  441. Dups = TrueBBI.NonPredSize;
  442. }
  443. return true;
  444. }
  445. /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
  446. /// with their common predecessor) forms a valid triangle shape for ifcvt.
  447. /// If 'FalseBranch' is true, it checks if 'true' block's false branch
  448. /// branches to the 'false' block rather than the other way around. It also
  449. /// returns the number of instructions that the ifcvt would need to duplicate
  450. /// if performed in 'Dups'.
  451. bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
  452. bool FalseBranch, unsigned &Dups,
  453. const BranchProbability &Prediction) const {
  454. Dups = 0;
  455. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
  456. return false;
  457. if (TrueBBI.BB->pred_size() > 1) {
  458. if (TrueBBI.CannotBeCopied)
  459. return false;
  460. unsigned Size = TrueBBI.NonPredSize;
  461. if (TrueBBI.IsBrAnalyzable) {
  462. if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
  463. // Ends with an unconditional branch. It will be removed.
  464. --Size;
  465. else {
  466. MachineBasicBlock *FExit = FalseBranch
  467. ? TrueBBI.TrueBB : TrueBBI.FalseBB;
  468. if (FExit)
  469. // Require a conditional branch
  470. ++Size;
  471. }
  472. }
  473. if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
  474. return false;
  475. Dups = Size;
  476. }
  477. MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
  478. if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
  479. MachineFunction::iterator I = TrueBBI.BB;
  480. if (++I == TrueBBI.BB->getParent()->end())
  481. return false;
  482. TExit = I;
  483. }
  484. return TExit && TExit == FalseBBI.BB;
  485. }
  486. /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
  487. /// with their common predecessor) forms a valid diamond shape for ifcvt.
  488. bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
  489. unsigned &Dups1, unsigned &Dups2) const {
  490. Dups1 = Dups2 = 0;
  491. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
  492. FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
  493. return false;
  494. MachineBasicBlock *TT = TrueBBI.TrueBB;
  495. MachineBasicBlock *FT = FalseBBI.TrueBB;
  496. if (!TT && blockAlwaysFallThrough(TrueBBI))
  497. TT = getNextBlock(TrueBBI.BB);
  498. if (!FT && blockAlwaysFallThrough(FalseBBI))
  499. FT = getNextBlock(FalseBBI.BB);
  500. if (TT != FT)
  501. return false;
  502. if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
  503. return false;
  504. if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
  505. return false;
  506. // FIXME: Allow true block to have an early exit?
  507. if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
  508. (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
  509. return false;
  510. // Count duplicate instructions at the beginning of the true and false blocks.
  511. MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
  512. MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
  513. MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
  514. MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
  515. while (TIB != TIE && FIB != FIE) {
  516. // Skip dbg_value instructions. These do not count.
  517. if (TIB->isDebugValue()) {
  518. while (TIB != TIE && TIB->isDebugValue())
  519. ++TIB;
  520. if (TIB == TIE)
  521. break;
  522. }
  523. if (FIB->isDebugValue()) {
  524. while (FIB != FIE && FIB->isDebugValue())
  525. ++FIB;
  526. if (FIB == FIE)
  527. break;
  528. }
  529. if (!TIB->isIdenticalTo(FIB))
  530. break;
  531. ++Dups1;
  532. ++TIB;
  533. ++FIB;
  534. }
  535. // Now, in preparation for counting duplicate instructions at the ends of the
  536. // blocks, move the end iterators up past any branch instructions.
  537. while (TIE != TIB) {
  538. --TIE;
  539. if (!TIE->isBranch())
  540. break;
  541. }
  542. while (FIE != FIB) {
  543. --FIE;
  544. if (!FIE->isBranch())
  545. break;
  546. }
  547. // If Dups1 includes all of a block, then don't count duplicate
  548. // instructions at the end of the blocks.
  549. if (TIB == TIE || FIB == FIE)
  550. return true;
  551. // Count duplicate instructions at the ends of the blocks.
  552. while (TIE != TIB && FIE != FIB) {
  553. // Skip dbg_value instructions. These do not count.
  554. if (TIE->isDebugValue()) {
  555. while (TIE != TIB && TIE->isDebugValue())
  556. --TIE;
  557. if (TIE == TIB)
  558. break;
  559. }
  560. if (FIE->isDebugValue()) {
  561. while (FIE != FIB && FIE->isDebugValue())
  562. --FIE;
  563. if (FIE == FIB)
  564. break;
  565. }
  566. if (!TIE->isIdenticalTo(FIE))
  567. break;
  568. ++Dups2;
  569. --TIE;
  570. --FIE;
  571. }
  572. return true;
  573. }
  574. /// ScanInstructions - Scan all the instructions in the block to determine if
  575. /// the block is predicable. In most cases, that means all the instructions
  576. /// in the block are isPredicable(). Also checks if the block contains any
  577. /// instruction which can clobber a predicate (e.g. condition code register).
  578. /// If so, the block is not predicable unless it's the last instruction.
  579. void IfConverter::ScanInstructions(BBInfo &BBI) {
  580. if (BBI.IsDone)
  581. return;
  582. bool AlreadyPredicated = !BBI.Predicate.empty();
  583. // First analyze the end of BB branches.
  584. BBI.TrueBB = BBI.FalseBB = nullptr;
  585. BBI.BrCond.clear();
  586. BBI.IsBrAnalyzable =
  587. !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
  588. BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
  589. if (BBI.BrCond.size()) {
  590. // No false branch. This BB must end with a conditional branch and a
  591. // fallthrough.
  592. if (!BBI.FalseBB)
  593. BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
  594. if (!BBI.FalseBB) {
  595. // Malformed bcc? True and false blocks are the same?
  596. BBI.IsUnpredicable = true;
  597. return;
  598. }
  599. }
  600. // Then scan all the instructions.
  601. BBI.NonPredSize = 0;
  602. BBI.ExtraCost = 0;
  603. BBI.ExtraCost2 = 0;
  604. BBI.ClobbersPred = false;
  605. for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
  606. I != E; ++I) {
  607. if (I->isDebugValue())
  608. continue;
  609. if (I->isNotDuplicable())
  610. BBI.CannotBeCopied = true;
  611. bool isPredicated = TII->isPredicated(I);
  612. bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
  613. // A conditional branch is not predicable, but it may be eliminated.
  614. if (isCondBr)
  615. continue;
  616. if (!isPredicated) {
  617. BBI.NonPredSize++;
  618. unsigned ExtraPredCost = TII->getPredicationCost(&*I);
  619. unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
  620. if (NumCycles > 1)
  621. BBI.ExtraCost += NumCycles-1;
  622. BBI.ExtraCost2 += ExtraPredCost;
  623. } else if (!AlreadyPredicated) {
  624. // FIXME: This instruction is already predicated before the
  625. // if-conversion pass. It's probably something like a conditional move.
  626. // Mark this block unpredicable for now.
  627. BBI.IsUnpredicable = true;
  628. return;
  629. }
  630. if (BBI.ClobbersPred && !isPredicated) {
  631. // Predicate modification instruction should end the block (except for
  632. // already predicated instructions and end of block branches).
  633. // Predicate may have been modified, the subsequent (currently)
  634. // unpredicated instructions cannot be correctly predicated.
  635. BBI.IsUnpredicable = true;
  636. return;
  637. }
  638. // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
  639. // still potentially predicable.
  640. std::vector<MachineOperand> PredDefs;
  641. if (TII->DefinesPredicate(I, PredDefs))
  642. BBI.ClobbersPred = true;
  643. if (!TII->isPredicable(I)) {
  644. BBI.IsUnpredicable = true;
  645. return;
  646. }
  647. }
  648. }
  649. /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
  650. /// predicated by the specified predicate.
  651. bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
  652. SmallVectorImpl<MachineOperand> &Pred,
  653. bool isTriangle, bool RevBranch) {
  654. // If the block is dead or unpredicable, then it cannot be predicated.
  655. if (BBI.IsDone || BBI.IsUnpredicable)
  656. return false;
  657. // If it is already predicated but we couldn't analyze its terminator, the
  658. // latter might fallthrough, but we can't determine where to.
  659. // Conservatively avoid if-converting again.
  660. if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
  661. return false;
  662. // If it is already predicated, check if the new predicate subsumes
  663. // its predicate.
  664. if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
  665. return false;
  666. if (BBI.BrCond.size()) {
  667. if (!isTriangle)
  668. return false;
  669. // Test predicate subsumption.
  670. SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
  671. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  672. if (RevBranch) {
  673. if (TII->ReverseBranchCondition(Cond))
  674. return false;
  675. }
  676. if (TII->ReverseBranchCondition(RevPred) ||
  677. !TII->SubsumesPredicate(Cond, RevPred))
  678. return false;
  679. }
  680. return true;
  681. }
  682. /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
  683. /// the specified block. Record its successors and whether it looks like an
  684. /// if-conversion candidate.
  685. void IfConverter::AnalyzeBlock(MachineBasicBlock *MBB,
  686. std::vector<IfcvtToken*> &Tokens) {
  687. struct BBState {
  688. BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
  689. MachineBasicBlock *MBB;
  690. /// This flag is true if MBB's successors have been analyzed.
  691. bool SuccsAnalyzed;
  692. };
  693. // Push MBB to the stack.
  694. SmallVector<BBState, 16> BBStack(1, MBB);
  695. while (!BBStack.empty()) {
  696. BBState &State = BBStack.back();
  697. MachineBasicBlock *BB = State.MBB;
  698. BBInfo &BBI = BBAnalysis[BB->getNumber()];
  699. if (!State.SuccsAnalyzed) {
  700. if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
  701. BBStack.pop_back();
  702. continue;
  703. }
  704. BBI.BB = BB;
  705. BBI.IsBeingAnalyzed = true;
  706. ScanInstructions(BBI);
  707. // Unanalyzable or ends with fallthrough or unconditional branch, or if is
  708. // not considered for ifcvt anymore.
  709. if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
  710. BBI.IsBeingAnalyzed = false;
  711. BBI.IsAnalyzed = true;
  712. BBStack.pop_back();
  713. continue;
  714. }
  715. // Do not ifcvt if either path is a back edge to the entry block.
  716. if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
  717. BBI.IsBeingAnalyzed = false;
  718. BBI.IsAnalyzed = true;
  719. BBStack.pop_back();
  720. continue;
  721. }
  722. // Do not ifcvt if true and false fallthrough blocks are the same.
  723. if (!BBI.FalseBB) {
  724. BBI.IsBeingAnalyzed = false;
  725. BBI.IsAnalyzed = true;
  726. BBStack.pop_back();
  727. continue;
  728. }
  729. // Push the False and True blocks to the stack.
  730. State.SuccsAnalyzed = true;
  731. BBStack.push_back(BBI.FalseBB);
  732. BBStack.push_back(BBI.TrueBB);
  733. continue;
  734. }
  735. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  736. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  737. if (TrueBBI.IsDone && FalseBBI.IsDone) {
  738. BBI.IsBeingAnalyzed = false;
  739. BBI.IsAnalyzed = true;
  740. BBStack.pop_back();
  741. continue;
  742. }
  743. SmallVector<MachineOperand, 4>
  744. RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
  745. bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
  746. unsigned Dups = 0;
  747. unsigned Dups2 = 0;
  748. bool TNeedSub = !TrueBBI.Predicate.empty();
  749. bool FNeedSub = !FalseBBI.Predicate.empty();
  750. bool Enqueued = false;
  751. BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
  752. if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
  753. MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
  754. TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
  755. *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
  756. FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
  757. Prediction) &&
  758. FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
  759. FeasibilityAnalysis(FalseBBI, RevCond)) {
  760. // Diamond:
  761. // EBB
  762. // / \_
  763. // | |
  764. // TBB FBB
  765. // \ /
  766. // TailBB
  767. // Note TailBB can be empty.
  768. Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
  769. Dups2));
  770. Enqueued = true;
  771. }
  772. if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
  773. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  774. TrueBBI.ExtraCost2, Prediction) &&
  775. FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
  776. // Triangle:
  777. // EBB
  778. // | \_
  779. // | |
  780. // | TBB
  781. // | /
  782. // FBB
  783. Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
  784. Enqueued = true;
  785. }
  786. if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
  787. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  788. TrueBBI.ExtraCost2, Prediction) &&
  789. FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
  790. Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
  791. Enqueued = true;
  792. }
  793. if (ValidSimple(TrueBBI, Dups, Prediction) &&
  794. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  795. TrueBBI.ExtraCost2, Prediction) &&
  796. FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
  797. // Simple (split, no rejoin):
  798. // EBB
  799. // | \_
  800. // | |
  801. // | TBB---> exit
  802. // |
  803. // FBB
  804. Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
  805. Enqueued = true;
  806. }
  807. if (CanRevCond) {
  808. // Try the other path...
  809. if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
  810. Prediction.getCompl()) &&
  811. MeetIfcvtSizeLimit(*FalseBBI.BB,
  812. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  813. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  814. FeasibilityAnalysis(FalseBBI, RevCond, true)) {
  815. Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
  816. Enqueued = true;
  817. }
  818. if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
  819. Prediction.getCompl()) &&
  820. MeetIfcvtSizeLimit(*FalseBBI.BB,
  821. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  822. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  823. FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
  824. Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
  825. Enqueued = true;
  826. }
  827. if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
  828. MeetIfcvtSizeLimit(*FalseBBI.BB,
  829. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  830. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  831. FeasibilityAnalysis(FalseBBI, RevCond)) {
  832. Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
  833. Enqueued = true;
  834. }
  835. }
  836. BBI.IsEnqueued = Enqueued;
  837. BBI.IsBeingAnalyzed = false;
  838. BBI.IsAnalyzed = true;
  839. BBStack.pop_back();
  840. }
  841. }
  842. /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
  843. /// candidates.
  844. void IfConverter::AnalyzeBlocks(MachineFunction &MF,
  845. std::vector<IfcvtToken*> &Tokens) {
  846. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
  847. MachineBasicBlock *BB = I;
  848. AnalyzeBlock(BB, Tokens);
  849. }
  850. // Sort to favor more complex ifcvt scheme.
  851. std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
  852. }
  853. /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
  854. /// that all the intervening blocks are empty (given BB can fall through to its
  855. /// next block).
  856. static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
  857. MachineFunction::iterator PI = BB;
  858. MachineFunction::iterator I = std::next(PI);
  859. MachineFunction::iterator TI = ToBB;
  860. MachineFunction::iterator E = BB->getParent()->end();
  861. while (I != TI) {
  862. // Check isSuccessor to avoid case where the next block is empty, but
  863. // it's not a successor.
  864. if (I == E || !I->empty() || !PI->isSuccessor(I))
  865. return false;
  866. PI = I++;
  867. }
  868. return true;
  869. }
  870. /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
  871. /// to determine if it can be if-converted. If predecessor is already enqueued,
  872. /// dequeue it!
  873. void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
  874. for (const auto &Predecessor : BB->predecessors()) {
  875. BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
  876. if (PBBI.IsDone || PBBI.BB == BB)
  877. continue;
  878. PBBI.IsAnalyzed = false;
  879. PBBI.IsEnqueued = false;
  880. }
  881. }
  882. /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
  883. ///
  884. static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
  885. const TargetInstrInfo *TII) {
  886. DebugLoc dl; // FIXME: this is nowhere
  887. SmallVector<MachineOperand, 0> NoCond;
  888. TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
  889. }
  890. /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
  891. /// successors.
  892. void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
  893. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  894. SmallVector<MachineOperand, 4> Cond;
  895. if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
  896. BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
  897. }
  898. /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
  899. /// values defined in MI which are not live/used by MI.
  900. static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) {
  901. SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
  902. Redefs.stepForward(*MI, Clobbers);
  903. // Now add the implicit uses for each of the clobbered values.
  904. for (auto Reg : Clobbers) {
  905. // FIXME: Const cast here is nasty, but better than making StepForward
  906. // take a mutable instruction instead of const.
  907. MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
  908. MachineInstr *OpMI = Op.getParent();
  909. MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
  910. if (Op.isRegMask()) {
  911. // First handle regmasks. They clobber any entries in the mask which
  912. // means that we need a def for those registers.
  913. MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
  914. // We also need to add an implicit def of this register for the later
  915. // use to read from.
  916. // For the register allocator to have allocated a register clobbered
  917. // by the call which is used later, it must be the case that
  918. // the call doesn't return.
  919. MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
  920. continue;
  921. }
  922. assert(Op.isReg() && "Register operand required");
  923. if (Op.isDead()) {
  924. // If we found a dead def, but it needs to be live, then remove the dead
  925. // flag.
  926. if (Redefs.contains(Op.getReg()))
  927. Op.setIsDead(false);
  928. }
  929. MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
  930. }
  931. }
  932. /**
  933. * Remove kill flags from operands with a registers in the @p DontKill set.
  934. */
  935. static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
  936. for (MIBundleOperands O(&MI); O.isValid(); ++O) {
  937. if (!O->isReg() || !O->isKill())
  938. continue;
  939. if (DontKill.contains(O->getReg()))
  940. O->setIsKill(false);
  941. }
  942. }
  943. /**
  944. * Walks a range of machine instructions and removes kill flags for registers
  945. * in the @p DontKill set.
  946. */
  947. static void RemoveKills(MachineBasicBlock::iterator I,
  948. MachineBasicBlock::iterator E,
  949. const LivePhysRegs &DontKill,
  950. const MCRegisterInfo &MCRI) {
  951. for ( ; I != E; ++I)
  952. RemoveKills(*I, DontKill);
  953. }
  954. /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
  955. ///
  956. bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
  957. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  958. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  959. BBInfo *CvtBBI = &TrueBBI;
  960. BBInfo *NextBBI = &FalseBBI;
  961. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  962. if (Kind == ICSimpleFalse)
  963. std::swap(CvtBBI, NextBBI);
  964. if (CvtBBI->IsDone ||
  965. (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
  966. // Something has changed. It's no longer safe to predicate this block.
  967. BBI.IsAnalyzed = false;
  968. CvtBBI->IsAnalyzed = false;
  969. return false;
  970. }
  971. if (CvtBBI->BB->hasAddressTaken())
  972. // Conservatively abort if-conversion if BB's address is taken.
  973. return false;
  974. if (Kind == ICSimpleFalse)
  975. if (TII->ReverseBranchCondition(Cond))
  976. llvm_unreachable("Unable to reverse branch condition!");
  977. // Initialize liveins to the first BB. These are potentiall redefined by
  978. // predicated instructions.
  979. Redefs.init(TRI);
  980. Redefs.addLiveIns(CvtBBI->BB);
  981. Redefs.addLiveIns(NextBBI->BB);
  982. // Compute a set of registers which must not be killed by instructions in
  983. // BB1: This is everything live-in to BB2.
  984. DontKill.init(TRI);
  985. DontKill.addLiveIns(NextBBI->BB);
  986. if (CvtBBI->BB->pred_size() > 1) {
  987. BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
  988. // Copy instructions in the true block, predicate them, and add them to
  989. // the entry block.
  990. CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
  991. // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
  992. // explicitly remove CvtBBI as a successor.
  993. BBI.BB->removeSuccessor(CvtBBI->BB);
  994. } else {
  995. RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
  996. PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
  997. // Merge converted block into entry block.
  998. BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
  999. MergeBlocks(BBI, *CvtBBI);
  1000. }
  1001. bool IterIfcvt = true;
  1002. if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
  1003. InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
  1004. BBI.HasFallThrough = false;
  1005. // Now ifcvt'd block will look like this:
  1006. // BB:
  1007. // ...
  1008. // t, f = cmp
  1009. // if t op
  1010. // b BBf
  1011. //
  1012. // We cannot further ifcvt this block because the unconditional branch
  1013. // will have to be predicated on the new condition, that will not be
  1014. // available if cmp executes.
  1015. IterIfcvt = false;
  1016. }
  1017. RemoveExtraEdges(BBI);
  1018. // Update block info. BB can be iteratively if-converted.
  1019. if (!IterIfcvt)
  1020. BBI.IsDone = true;
  1021. InvalidatePreds(BBI.BB);
  1022. CvtBBI->IsDone = true;
  1023. // FIXME: Must maintain LiveIns.
  1024. return true;
  1025. }
  1026. /// Scale down weights to fit into uint32_t. NewTrue is the new weight
  1027. /// for successor TrueBB, and NewFalse is the new weight for successor
  1028. /// FalseBB.
  1029. static void ScaleWeights(uint64_t NewTrue, uint64_t NewFalse,
  1030. MachineBasicBlock *MBB,
  1031. const MachineBasicBlock *TrueBB,
  1032. const MachineBasicBlock *FalseBB,
  1033. const MachineBranchProbabilityInfo *MBPI) {
  1034. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  1035. uint32_t Scale = (NewMax / UINT32_MAX) + 1;
  1036. for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
  1037. SE = MBB->succ_end();
  1038. SI != SE; ++SI) {
  1039. if (*SI == TrueBB)
  1040. MBB->setSuccWeight(SI, (uint32_t)(NewTrue / Scale));
  1041. else if (*SI == FalseBB)
  1042. MBB->setSuccWeight(SI, (uint32_t)(NewFalse / Scale));
  1043. else
  1044. MBB->setSuccWeight(SI, MBPI->getEdgeWeight(MBB, SI) / Scale);
  1045. }
  1046. }
  1047. /// IfConvertTriangle - If convert a triangle sub-CFG.
  1048. ///
  1049. bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
  1050. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1051. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1052. BBInfo *CvtBBI = &TrueBBI;
  1053. BBInfo *NextBBI = &FalseBBI;
  1054. DebugLoc dl; // FIXME: this is nowhere
  1055. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  1056. if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
  1057. std::swap(CvtBBI, NextBBI);
  1058. if (CvtBBI->IsDone ||
  1059. (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
  1060. // Something has changed. It's no longer safe to predicate this block.
  1061. BBI.IsAnalyzed = false;
  1062. CvtBBI->IsAnalyzed = false;
  1063. return false;
  1064. }
  1065. if (CvtBBI->BB->hasAddressTaken())
  1066. // Conservatively abort if-conversion if BB's address is taken.
  1067. return false;
  1068. if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
  1069. if (TII->ReverseBranchCondition(Cond))
  1070. llvm_unreachable("Unable to reverse branch condition!");
  1071. if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
  1072. if (ReverseBranchCondition(*CvtBBI)) {
  1073. // BB has been changed, modify its predecessors (except for this
  1074. // one) so they don't get ifcvt'ed based on bad intel.
  1075. for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
  1076. E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
  1077. MachineBasicBlock *PBB = *PI;
  1078. if (PBB == BBI.BB)
  1079. continue;
  1080. BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
  1081. if (PBBI.IsEnqueued) {
  1082. PBBI.IsAnalyzed = false;
  1083. PBBI.IsEnqueued = false;
  1084. }
  1085. }
  1086. }
  1087. }
  1088. // Initialize liveins to the first BB. These are potentially redefined by
  1089. // predicated instructions.
  1090. Redefs.init(TRI);
  1091. Redefs.addLiveIns(CvtBBI->BB);
  1092. Redefs.addLiveIns(NextBBI->BB);
  1093. DontKill.clear();
  1094. bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
  1095. uint64_t CvtNext = 0, CvtFalse = 0, BBNext = 0, BBCvt = 0, SumWeight = 0;
  1096. uint32_t WeightScale = 0;
  1097. if (HasEarlyExit) {
  1098. // Get weights before modifying CvtBBI->BB and BBI.BB.
  1099. CvtNext = MBPI->getEdgeWeight(CvtBBI->BB, NextBBI->BB);
  1100. CvtFalse = MBPI->getEdgeWeight(CvtBBI->BB, CvtBBI->FalseBB);
  1101. BBNext = MBPI->getEdgeWeight(BBI.BB, NextBBI->BB);
  1102. BBCvt = MBPI->getEdgeWeight(BBI.BB, CvtBBI->BB);
  1103. SumWeight = MBPI->getSumForBlock(CvtBBI->BB, WeightScale);
  1104. }
  1105. if (CvtBBI->BB->pred_size() > 1) {
  1106. BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
  1107. // Copy instructions in the true block, predicate them, and add them to
  1108. // the entry block.
  1109. CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
  1110. // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
  1111. // explicitly remove CvtBBI as a successor.
  1112. BBI.BB->removeSuccessor(CvtBBI->BB);
  1113. } else {
  1114. // Predicate the 'true' block after removing its branch.
  1115. CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
  1116. PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
  1117. // Now merge the entry of the triangle with the true block.
  1118. BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
  1119. MergeBlocks(BBI, *CvtBBI, false);
  1120. }
  1121. // If 'true' block has a 'false' successor, add an exit branch to it.
  1122. if (HasEarlyExit) {
  1123. SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
  1124. CvtBBI->BrCond.end());
  1125. if (TII->ReverseBranchCondition(RevCond))
  1126. llvm_unreachable("Unable to reverse branch condition!");
  1127. TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
  1128. BBI.BB->addSuccessor(CvtBBI->FalseBB);
  1129. // Update the edge weight for both CvtBBI->FalseBB and NextBBI.
  1130. // New_Weight(BBI.BB, NextBBI->BB) =
  1131. // Weight(BBI.BB, NextBBI->BB) * getSumForBlock(CvtBBI->BB) +
  1132. // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, NextBBI->BB)
  1133. // New_Weight(BBI.BB, CvtBBI->FalseBB) =
  1134. // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, CvtBBI->FalseBB)
  1135. uint64_t NewNext = BBNext * SumWeight + (BBCvt * CvtNext) / WeightScale;
  1136. uint64_t NewFalse = (BBCvt * CvtFalse) / WeightScale;
  1137. // We need to scale down all weights of BBI.BB to fit uint32_t.
  1138. // Here BBI.BB is connected to CvtBBI->FalseBB and will fall through to
  1139. // the next block.
  1140. ScaleWeights(NewNext, NewFalse, BBI.BB, getNextBlock(BBI.BB),
  1141. CvtBBI->FalseBB, MBPI);
  1142. }
  1143. // Merge in the 'false' block if the 'false' block has no other
  1144. // predecessors. Otherwise, add an unconditional branch to 'false'.
  1145. bool FalseBBDead = false;
  1146. bool IterIfcvt = true;
  1147. bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
  1148. if (!isFallThrough) {
  1149. // Only merge them if the true block does not fallthrough to the false
  1150. // block. By not merging them, we make it possible to iteratively
  1151. // ifcvt the blocks.
  1152. if (!HasEarlyExit &&
  1153. NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
  1154. !NextBBI->BB->hasAddressTaken()) {
  1155. MergeBlocks(BBI, *NextBBI);
  1156. FalseBBDead = true;
  1157. } else {
  1158. InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
  1159. BBI.HasFallThrough = false;
  1160. }
  1161. // Mixed predicated and unpredicated code. This cannot be iteratively
  1162. // predicated.
  1163. IterIfcvt = false;
  1164. }
  1165. RemoveExtraEdges(BBI);
  1166. // Update block info. BB can be iteratively if-converted.
  1167. if (!IterIfcvt)
  1168. BBI.IsDone = true;
  1169. InvalidatePreds(BBI.BB);
  1170. CvtBBI->IsDone = true;
  1171. if (FalseBBDead)
  1172. NextBBI->IsDone = true;
  1173. // FIXME: Must maintain LiveIns.
  1174. return true;
  1175. }
  1176. /// IfConvertDiamond - If convert a diamond sub-CFG.
  1177. ///
  1178. bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
  1179. unsigned NumDups1, unsigned NumDups2) {
  1180. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1181. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1182. MachineBasicBlock *TailBB = TrueBBI.TrueBB;
  1183. // True block must fall through or end with an unanalyzable terminator.
  1184. if (!TailBB) {
  1185. if (blockAlwaysFallThrough(TrueBBI))
  1186. TailBB = FalseBBI.TrueBB;
  1187. assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
  1188. }
  1189. if (TrueBBI.IsDone || FalseBBI.IsDone ||
  1190. TrueBBI.BB->pred_size() > 1 ||
  1191. FalseBBI.BB->pred_size() > 1) {
  1192. // Something has changed. It's no longer safe to predicate these blocks.
  1193. BBI.IsAnalyzed = false;
  1194. TrueBBI.IsAnalyzed = false;
  1195. FalseBBI.IsAnalyzed = false;
  1196. return false;
  1197. }
  1198. if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
  1199. // Conservatively abort if-conversion if either BB has its address taken.
  1200. return false;
  1201. // Put the predicated instructions from the 'true' block before the
  1202. // instructions from the 'false' block, unless the true block would clobber
  1203. // the predicate, in which case, do the opposite.
  1204. BBInfo *BBI1 = &TrueBBI;
  1205. BBInfo *BBI2 = &FalseBBI;
  1206. SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
  1207. if (TII->ReverseBranchCondition(RevCond))
  1208. llvm_unreachable("Unable to reverse branch condition!");
  1209. SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
  1210. SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
  1211. // Figure out the more profitable ordering.
  1212. bool DoSwap = false;
  1213. if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
  1214. DoSwap = true;
  1215. else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
  1216. if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
  1217. DoSwap = true;
  1218. }
  1219. if (DoSwap) {
  1220. std::swap(BBI1, BBI2);
  1221. std::swap(Cond1, Cond2);
  1222. }
  1223. // Remove the conditional branch from entry to the blocks.
  1224. BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
  1225. // Initialize liveins to the first BB. These are potentially redefined by
  1226. // predicated instructions.
  1227. Redefs.init(TRI);
  1228. Redefs.addLiveIns(BBI1->BB);
  1229. // Remove the duplicated instructions at the beginnings of both paths.
  1230. // Skip dbg_value instructions
  1231. MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
  1232. MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
  1233. BBI1->NonPredSize -= NumDups1;
  1234. BBI2->NonPredSize -= NumDups1;
  1235. // Skip past the dups on each side separately since there may be
  1236. // differing dbg_value entries.
  1237. for (unsigned i = 0; i < NumDups1; ++DI1) {
  1238. if (!DI1->isDebugValue())
  1239. ++i;
  1240. }
  1241. while (NumDups1 != 0) {
  1242. ++DI2;
  1243. if (!DI2->isDebugValue())
  1244. --NumDups1;
  1245. }
  1246. // Compute a set of registers which must not be killed by instructions in BB1:
  1247. // This is everything used+live in BB2 after the duplicated instructions. We
  1248. // can compute this set by simulating liveness backwards from the end of BB2.
  1249. DontKill.init(TRI);
  1250. for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
  1251. E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
  1252. DontKill.stepBackward(*I);
  1253. }
  1254. for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
  1255. ++I) {
  1256. SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
  1257. Redefs.stepForward(*I, IgnoredClobbers);
  1258. }
  1259. BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
  1260. BBI2->BB->erase(BBI2->BB->begin(), DI2);
  1261. // Remove branch from 'true' block and remove duplicated instructions.
  1262. BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
  1263. DI1 = BBI1->BB->end();
  1264. for (unsigned i = 0; i != NumDups2; ) {
  1265. // NumDups2 only counted non-dbg_value instructions, so this won't
  1266. // run off the head of the list.
  1267. assert (DI1 != BBI1->BB->begin());
  1268. --DI1;
  1269. // skip dbg_value instructions
  1270. if (!DI1->isDebugValue())
  1271. ++i;
  1272. }
  1273. BBI1->BB->erase(DI1, BBI1->BB->end());
  1274. // Kill flags in the true block for registers living into the false block
  1275. // must be removed.
  1276. RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
  1277. // Remove 'false' block branch and find the last instruction to predicate.
  1278. BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
  1279. DI2 = BBI2->BB->end();
  1280. while (NumDups2 != 0) {
  1281. // NumDups2 only counted non-dbg_value instructions, so this won't
  1282. // run off the head of the list.
  1283. assert (DI2 != BBI2->BB->begin());
  1284. --DI2;
  1285. // skip dbg_value instructions
  1286. if (!DI2->isDebugValue())
  1287. --NumDups2;
  1288. }
  1289. // Remember which registers would later be defined by the false block.
  1290. // This allows us not to predicate instructions in the true block that would
  1291. // later be re-defined. That is, rather than
  1292. // subeq r0, r1, #1
  1293. // addne r0, r1, #1
  1294. // generate:
  1295. // sub r0, r1, #1
  1296. // addne r0, r1, #1
  1297. SmallSet<unsigned, 4> RedefsByFalse;
  1298. SmallSet<unsigned, 4> ExtUses;
  1299. if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
  1300. for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
  1301. if (FI->isDebugValue())
  1302. continue;
  1303. SmallVector<unsigned, 4> Defs;
  1304. for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
  1305. const MachineOperand &MO = FI->getOperand(i);
  1306. if (!MO.isReg())
  1307. continue;
  1308. unsigned Reg = MO.getReg();
  1309. if (!Reg)
  1310. continue;
  1311. if (MO.isDef()) {
  1312. Defs.push_back(Reg);
  1313. } else if (!RedefsByFalse.count(Reg)) {
  1314. // These are defined before ctrl flow reach the 'false' instructions.
  1315. // They cannot be modified by the 'true' instructions.
  1316. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  1317. SubRegs.isValid(); ++SubRegs)
  1318. ExtUses.insert(*SubRegs);
  1319. }
  1320. }
  1321. for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
  1322. unsigned Reg = Defs[i];
  1323. if (!ExtUses.count(Reg)) {
  1324. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  1325. SubRegs.isValid(); ++SubRegs)
  1326. RedefsByFalse.insert(*SubRegs);
  1327. }
  1328. }
  1329. }
  1330. }
  1331. // Predicate the 'true' block.
  1332. PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
  1333. // Predicate the 'false' block.
  1334. PredicateBlock(*BBI2, DI2, *Cond2);
  1335. // Merge the true block into the entry of the diamond.
  1336. MergeBlocks(BBI, *BBI1, TailBB == nullptr);
  1337. MergeBlocks(BBI, *BBI2, TailBB == nullptr);
  1338. // If the if-converted block falls through or unconditionally branches into
  1339. // the tail block, and the tail block does not have other predecessors, then
  1340. // fold the tail block in as well. Otherwise, unless it falls through to the
  1341. // tail, add a unconditional branch to it.
  1342. if (TailBB) {
  1343. BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
  1344. bool CanMergeTail = !TailBBI.HasFallThrough &&
  1345. !TailBBI.BB->hasAddressTaken();
  1346. // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
  1347. // check if there are any other predecessors besides those.
  1348. unsigned NumPreds = TailBB->pred_size();
  1349. if (NumPreds > 1)
  1350. CanMergeTail = false;
  1351. else if (NumPreds == 1 && CanMergeTail) {
  1352. MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
  1353. if (*PI != BBI1->BB && *PI != BBI2->BB)
  1354. CanMergeTail = false;
  1355. }
  1356. if (CanMergeTail) {
  1357. MergeBlocks(BBI, TailBBI);
  1358. TailBBI.IsDone = true;
  1359. } else {
  1360. BBI.BB->addSuccessor(TailBB);
  1361. InsertUncondBranch(BBI.BB, TailBB, TII);
  1362. BBI.HasFallThrough = false;
  1363. }
  1364. }
  1365. // RemoveExtraEdges won't work if the block has an unanalyzable branch,
  1366. // which can happen here if TailBB is unanalyzable and is merged, so
  1367. // explicitly remove BBI1 and BBI2 as successors.
  1368. BBI.BB->removeSuccessor(BBI1->BB);
  1369. BBI.BB->removeSuccessor(BBI2->BB);
  1370. RemoveExtraEdges(BBI);
  1371. // Update block info.
  1372. BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
  1373. InvalidatePreds(BBI.BB);
  1374. // FIXME: Must maintain LiveIns.
  1375. return true;
  1376. }
  1377. static bool MaySpeculate(const MachineInstr *MI,
  1378. SmallSet<unsigned, 4> &LaterRedefs) {
  1379. bool SawStore = true;
  1380. if (!MI->isSafeToMove(nullptr, SawStore))
  1381. return false;
  1382. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  1383. const MachineOperand &MO = MI->getOperand(i);
  1384. if (!MO.isReg())
  1385. continue;
  1386. unsigned Reg = MO.getReg();
  1387. if (!Reg)
  1388. continue;
  1389. if (MO.isDef() && !LaterRedefs.count(Reg))
  1390. return false;
  1391. }
  1392. return true;
  1393. }
  1394. /// PredicateBlock - Predicate instructions from the start of the block to the
  1395. /// specified end with the specified condition.
  1396. void IfConverter::PredicateBlock(BBInfo &BBI,
  1397. MachineBasicBlock::iterator E,
  1398. SmallVectorImpl<MachineOperand> &Cond,
  1399. SmallSet<unsigned, 4> *LaterRedefs) {
  1400. bool AnyUnpred = false;
  1401. bool MaySpec = LaterRedefs != nullptr;
  1402. for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
  1403. if (I->isDebugValue() || TII->isPredicated(I))
  1404. continue;
  1405. // It may be possible not to predicate an instruction if it's the 'true'
  1406. // side of a diamond and the 'false' side may re-define the instruction's
  1407. // defs.
  1408. if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
  1409. AnyUnpred = true;
  1410. continue;
  1411. }
  1412. // If any instruction is predicated, then every instruction after it must
  1413. // be predicated.
  1414. MaySpec = false;
  1415. if (!TII->PredicateInstruction(I, Cond)) {
  1416. #ifndef NDEBUG
  1417. dbgs() << "Unable to predicate " << *I << "!\n";
  1418. #endif
  1419. llvm_unreachable(nullptr);
  1420. }
  1421. // If the predicated instruction now redefines a register as the result of
  1422. // if-conversion, add an implicit kill.
  1423. UpdatePredRedefs(I, Redefs);
  1424. }
  1425. BBI.Predicate.append(Cond.begin(), Cond.end());
  1426. BBI.IsAnalyzed = false;
  1427. BBI.NonPredSize = 0;
  1428. ++NumIfConvBBs;
  1429. if (AnyUnpred)
  1430. ++NumUnpred;
  1431. }
  1432. /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
  1433. /// the destination block. Skip end of block branches if IgnoreBr is true.
  1434. void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
  1435. SmallVectorImpl<MachineOperand> &Cond,
  1436. bool IgnoreBr) {
  1437. MachineFunction &MF = *ToBBI.BB->getParent();
  1438. for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
  1439. E = FromBBI.BB->end(); I != E; ++I) {
  1440. // Do not copy the end of the block branches.
  1441. if (IgnoreBr && I->isBranch())
  1442. break;
  1443. MachineInstr *MI = MF.CloneMachineInstr(I);
  1444. ToBBI.BB->insert(ToBBI.BB->end(), MI);
  1445. ToBBI.NonPredSize++;
  1446. unsigned ExtraPredCost = TII->getPredicationCost(&*I);
  1447. unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
  1448. if (NumCycles > 1)
  1449. ToBBI.ExtraCost += NumCycles-1;
  1450. ToBBI.ExtraCost2 += ExtraPredCost;
  1451. if (!TII->isPredicated(I) && !MI->isDebugValue()) {
  1452. if (!TII->PredicateInstruction(MI, Cond)) {
  1453. #ifndef NDEBUG
  1454. dbgs() << "Unable to predicate " << *I << "!\n";
  1455. #endif
  1456. llvm_unreachable(nullptr);
  1457. }
  1458. }
  1459. // If the predicated instruction now redefines a register as the result of
  1460. // if-conversion, add an implicit kill.
  1461. UpdatePredRedefs(MI, Redefs);
  1462. // Some kill flags may not be correct anymore.
  1463. if (!DontKill.empty())
  1464. RemoveKills(*MI, DontKill);
  1465. }
  1466. if (!IgnoreBr) {
  1467. std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
  1468. FromBBI.BB->succ_end());
  1469. MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
  1470. MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
  1471. for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
  1472. MachineBasicBlock *Succ = Succs[i];
  1473. // Fallthrough edge can't be transferred.
  1474. if (Succ == FallThrough)
  1475. continue;
  1476. ToBBI.BB->addSuccessor(Succ);
  1477. }
  1478. }
  1479. ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
  1480. ToBBI.Predicate.append(Cond.begin(), Cond.end());
  1481. ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
  1482. ToBBI.IsAnalyzed = false;
  1483. ++NumDupBBs;
  1484. }
  1485. /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
  1486. /// This will leave FromBB as an empty block, so remove all of its
  1487. /// successor edges except for the fall-through edge. If AddEdges is true,
  1488. /// i.e., when FromBBI's branch is being moved, add those successor edges to
  1489. /// ToBBI.
  1490. void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
  1491. assert(!FromBBI.BB->hasAddressTaken() &&
  1492. "Removing a BB whose address is taken!");
  1493. ToBBI.BB->splice(ToBBI.BB->end(),
  1494. FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
  1495. std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
  1496. FromBBI.BB->succ_end());
  1497. MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
  1498. MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
  1499. for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
  1500. MachineBasicBlock *Succ = Succs[i];
  1501. // Fallthrough edge can't be transferred.
  1502. if (Succ == FallThrough)
  1503. continue;
  1504. FromBBI.BB->removeSuccessor(Succ);
  1505. if (AddEdges && !ToBBI.BB->isSuccessor(Succ))
  1506. ToBBI.BB->addSuccessor(Succ);
  1507. }
  1508. // Now FromBBI always falls through to the next block!
  1509. if (NBB && !FromBBI.BB->isSuccessor(NBB))
  1510. FromBBI.BB->addSuccessor(NBB);
  1511. ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
  1512. FromBBI.Predicate.clear();
  1513. ToBBI.NonPredSize += FromBBI.NonPredSize;
  1514. ToBBI.ExtraCost += FromBBI.ExtraCost;
  1515. ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
  1516. FromBBI.NonPredSize = 0;
  1517. FromBBI.ExtraCost = 0;
  1518. FromBBI.ExtraCost2 = 0;
  1519. ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
  1520. ToBBI.HasFallThrough = FromBBI.HasFallThrough;
  1521. ToBBI.IsAnalyzed = false;
  1522. FromBBI.IsAnalyzed = false;
  1523. }
  1524. FunctionPass *
  1525. llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
  1526. return new IfConverter(Ftor);
  1527. }