IfConversion.cpp 89 KB

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