blob: b99e570a446149d55f484807b8ede8d6293ea5c8 [file] [log] [blame]
Evan Chengf5e53a52007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the machine instruction level if-conversion pass.
11//
12//===----------------------------------------------------------------------===//
13
Evan Chengf5e53a52007-05-16 02:00:57 +000014#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "BranchFolding.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallSet.h"
18#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000019#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000020#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000021#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000023#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000026#include "llvm/CodeGen/TargetSchedule.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000027#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000028#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000029#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000034#include "llvm/Target/TargetSubtargetInfo.h"
35
Evan Chengf5e53a52007-05-16 02:00:57 +000036using namespace llvm;
37
Chandler Carruth1b9dde02014-04-22 02:02:50 +000038#define DEBUG_TYPE "ifcvt"
39
Chris Lattner769c86b2008-01-07 05:40:58 +000040// Hidden options for help debugging.
41static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
42static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
43static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000044static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000045 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000046static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000047 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000048static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000049 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000050static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000051 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000052static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000053 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000054static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000055 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000056static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000057 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000058static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
59 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000060
Evan Cheng2117d1f2007-06-09 01:03:43 +000061STATISTIC(NumSimple, "Number of simple if-conversions performed");
62STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
63STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000064STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000065STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
66STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
67STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
68STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000069STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000070STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000071
72namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000073 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000074 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000075 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000076 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000077 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
78 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000079 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000080 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000081 ICTriangle, // BB is entry of a triangle sub-CFG.
Evan Cheng4dd31a72007-06-11 22:26:22 +000082 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Chengf5e53a52007-05-16 02:00:57 +000083 };
84
85 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
86 /// if-conversion feasibility analysis. This includes results from
87 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000088 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000089 /// diamond shape), its size, whether it's predicable, and whether any
90 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000091 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +000092 /// IsDone - True if BB is not to be considered for ifcvt.
93 /// IsBeingAnalyzed - True if BB is currently being analyzed.
94 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
95 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
96 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
97 /// HasFallThrough - True if BB may fallthrough to the following BB.
98 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +000099 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000100 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000101 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000102 /// ExtraCost - Extra cost for multi-cycle instructions.
103 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000104 /// BB - Corresponding MachineBasicBlock.
105 /// TrueBB / FalseBB- See AnalyzeBranch().
106 /// BrCond - Conditions for end of block conditional branches.
107 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000108 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000109 bool IsDone : 1;
110 bool IsBeingAnalyzed : 1;
111 bool IsAnalyzed : 1;
112 bool IsEnqueued : 1;
113 bool IsBrAnalyzable : 1;
114 bool HasFallThrough : 1;
115 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000116 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000117 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000118 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000119 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000120 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000121 MachineBasicBlock *BB;
122 MachineBasicBlock *TrueBB;
123 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000124 SmallVector<MachineOperand, 4> BrCond;
125 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000126 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000127 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
128 HasFallThrough(false), IsUnpredicable(false),
Evan Cheng23402fc2007-06-15 21:18:05 +0000129 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Craig Topperc0196b12014-04-14 00:51:57 +0000130 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
131 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000132 };
133
Bob Wilson59475732010-06-15 18:19:27 +0000134 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000135 /// BBI - Corresponding BBInfo.
136 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000137 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000138 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000139 /// NumDups - Number of instructions that would be duplicated due
140 /// to this if-conversion. (For diamonds, the number of
141 /// identical instructions at the beginnings of both
142 /// paths).
143 /// NumDups2 - For diamonds, the number of identical instructions
144 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000145 struct IfcvtToken {
146 BBInfo &BBI;
147 IfcvtKind Kind;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000148 bool NeedSubsumption;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000149 unsigned NumDups;
150 unsigned NumDups2;
151 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson2371f4f2009-05-13 23:25:24 +0000152 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000153 };
154
155 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
156 /// basic block number.
157 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000158 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000159
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000160 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000161 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000162 const TargetRegisterInfo *TRI;
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000163 const MachineBlockFrequencyInfo *MBFI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000164 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000165 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000166
Juergen Ributzka310034e2013-12-14 06:52:56 +0000167 LivePhysRegs Redefs;
168 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000169
Evan Chengc5adcca2012-06-08 21:53:50 +0000170 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000171 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000172 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000173 std::function<bool(const Function &)> PredicateFtor;
174
Evan Chengf5e53a52007-05-16 02:00:57 +0000175 public:
176 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000177 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
178 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(Ftor) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000179 initializeIfConverterPass(*PassRegistry::getPassRegistry());
180 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000181
Craig Topper4584cd52014-03-07 09:26:03 +0000182 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000183 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000184 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000185 MachineFunctionPass::getAnalysisUsage(AU);
186 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000187
Craig Topper4584cd52014-03-07 09:26:03 +0000188 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000189
190 private:
Evan Cheng312b7232007-06-04 06:47:22 +0000191 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersonf31f33e2010-10-01 22:45:50 +0000192 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000193 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000194 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000195 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000196 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000197 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
198 unsigned &Dups1, unsigned &Dups2) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000199 void ScanInstructions(BBInfo &BBI);
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000200 void AnalyzeBlock(MachineBasicBlock *MBB, std::vector<IfcvtToken*> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000201 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng7783f822007-06-08 09:36:04 +0000202 bool isTriangle = false, bool RevBranch = false);
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000203 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000204 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000205 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000206 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
207 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000208 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
209 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000210 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000211 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000212 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000213 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000214 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000215 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000216 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000217 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000218
Evan Chengdebf9c52010-11-03 00:45:17 +0000219 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
220 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000221 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000222 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000223 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000224 }
225
Evan Chengdebf9c52010-11-03 00:45:17 +0000226 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
227 unsigned TCycle, unsigned TExtra,
228 MachineBasicBlock &FBB,
229 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000230 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000231 return TCycle > 0 && FCycle > 0 &&
232 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000233 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000234 }
235
Evan Chengbe9859e2007-06-07 02:12:15 +0000236 // blockAlwaysFallThrough - Block ends without a terminator.
237 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000238 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000239 }
240
Evan Cheng3a51c852007-06-16 09:34:52 +0000241 // IfcvtTokenCmp - Used to sort if-conversion candidates.
242 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000243 int Incr1 = (C1->Kind == ICDiamond)
244 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
245 int Incr2 = (C2->Kind == ICDiamond)
246 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
247 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000248 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000249 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000250 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000251 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000252 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000253 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000254 // Favors diamond over triangle, etc.
255 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
256 return true;
257 else if (C1->Kind == C2->Kind)
258 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
259 }
260 }
261 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000262 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000263 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000264
Evan Chengf5e53a52007-05-16 02:00:57 +0000265 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000266}
Evan Chengf5e53a52007-05-16 02:00:57 +0000267
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000268char &llvm::IfConverterID = IfConverter::ID;
269
Owen Anderson8ac477f2010-10-12 19:48:12 +0000270INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000271INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000272INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000273
Evan Chengf5e53a52007-05-16 02:00:57 +0000274bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Akira Hatanaka4a616192015-06-08 18:50:43 +0000275 if (PredicateFtor && !PredicateFtor(*MF.getFunction()))
276 return false;
277
Eric Christopher3d4276f2015-01-27 07:31:29 +0000278 const TargetSubtargetInfo &ST = MF.getSubtarget();
279 TLI = ST.getTargetLowering();
280 TII = ST.getInstrInfo();
281 TRI = ST.getRegisterInfo();
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000282 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000283 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000284 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000285 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000286
Evan Chengf5e53a52007-05-16 02:00:57 +0000287 if (!TII) return false;
288
Evan Chengc5adcca2012-06-08 21:53:50 +0000289 PreRegAlloc = MRI->isSSA();
290
291 bool BFChange = false;
292 if (!PreRegAlloc) {
293 // Tail merge tend to expose more if-conversion opportunities.
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000294 BranchFolder BF(true, false, *MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000295 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000296 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000297 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000298
David Greene72e47cd2010-01-04 22:02:01 +0000299 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000300 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000301
302 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000303 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000304 return false;
305 }
David Greene72e47cd2010-01-04 22:02:01 +0000306 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000307
Evan Chengf5e53a52007-05-16 02:00:57 +0000308 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000309 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000310
Evan Cheng3a51c852007-06-16 09:34:52 +0000311 std::vector<IfcvtToken*> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000312 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000313 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
314 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
315 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000316 // Do an initial analysis for each basic block and find all the potential
317 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000318 bool Change = false;
319 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000320 while (!Tokens.empty()) {
321 IfcvtToken *Token = Tokens.back();
322 Tokens.pop_back();
323 BBInfo &BBI = Token->BBI;
324 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000325 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000326 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000327
328 delete Token;
Evan Cheng312b7232007-06-04 06:47:22 +0000329
Evan Cheng4dd31a72007-06-11 22:26:22 +0000330 // If the block has been evicted out of the queue or it has already been
331 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000332 if (BBI.IsDone)
333 BBI.IsEnqueued = false;
334 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000335 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000336
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000337 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000338
Evan Cheng312b7232007-06-04 06:47:22 +0000339 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000340 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000341 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000342 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000343 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000344 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000345 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000346 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
347 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000348 << "): BB#" << BBI.BB->getNumber() << " ("
349 << ((Kind == ICSimpleFalse)
350 ? BBI.FalseBB->getNumber()
351 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000352 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000353 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000354 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000355 if (isFalse) ++NumSimpleFalse;
356 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000357 }
Evan Cheng312b7232007-06-04 06:47:22 +0000358 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000359 }
Evan Chengd0e66912007-05-23 07:23:16 +0000360 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000361 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000362 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000363 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000364 bool isFalse = Kind == ICTriangleFalse;
365 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000366 if (DisableTriangle && !isFalse && !isRev) break;
367 if (DisableTriangleR && !isFalse && isRev) break;
368 if (DisableTriangleF && isFalse && !isRev) break;
369 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000370 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000371 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000372 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000373 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000374 DEBUG(dbgs() << " rev");
375 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000376 << BBI.TrueBB->getNumber() << ",F:"
377 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000378 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000379 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000380 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000381 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000382 if (isRev) ++NumTriangleFRev;
383 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000384 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000385 if (isRev) ++NumTriangleRev;
386 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000387 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000388 }
Evan Chengd0e66912007-05-23 07:23:16 +0000389 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000390 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000391 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000392 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000393 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000394 << BBI.TrueBB->getNumber() << ",F:"
395 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000396 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000397 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000398 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000399 break;
400 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000401 }
402
Evan Cheng312b7232007-06-04 06:47:22 +0000403 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000404
Evan Cheng92fb5452007-06-15 07:36:12 +0000405 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
406 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
407 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000408 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000409 }
Evan Chengd0e66912007-05-23 07:23:16 +0000410
Evan Chengd0e66912007-05-23 07:23:16 +0000411 if (!Change)
412 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000413 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000414 }
Evan Cheng478b8052007-05-18 01:55:58 +0000415
Evan Cheng3a51c852007-06-16 09:34:52 +0000416 // Delete tokens in case of early exit.
417 while (!Tokens.empty()) {
418 IfcvtToken *Token = Tokens.back();
419 Tokens.pop_back();
420 delete Token;
421 }
422
423 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000424 BBAnalysis.clear();
425
Evan Chengcf9e8a92010-06-18 22:17:13 +0000426 if (MadeChange && IfCvtBranchFold) {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000427 BranchFolder BF(false, false, *MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000428 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000429 getAnalysisIfAvailable<MachineModuleInfo>());
430 }
431
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000432 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000433 return MadeChange;
434}
435
Evan Cheng3a51c852007-06-16 09:34:52 +0000436/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
437/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000438static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000439 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000440 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
441 E = BB->succ_end(); SI != E; ++SI) {
442 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000443 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000444 return SuccBB;
445 }
Craig Topperc0196b12014-04-14 00:51:57 +0000446 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000447}
448
Evan Cheng3a51c852007-06-16 09:34:52 +0000449/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000450/// branch. Swap block's 'true' and 'false' successors.
Evan Cheng312b7232007-06-04 06:47:22 +0000451bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000452 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000453 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
454 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000455 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000456 std::swap(BBI.TrueBB, BBI.FalseBB);
457 return true;
458 }
459 return false;
460}
461
Evan Cheng2117d1f2007-06-09 01:03:43 +0000462/// getNextBlock - Returns the next block in the function blocks ordering. If
463/// it is the end, returns NULL.
464static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
465 MachineFunction::iterator I = BB;
466 MachineFunction::iterator E = BB->getParent()->end();
467 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000468 return nullptr;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000469 return I;
470}
471
Evan Cheng7783f822007-06-08 09:36:04 +0000472/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000473/// predecessor) forms a valid simple shape for ifcvt. It also returns the
474/// number of instructions that the ifcvt would need to duplicate if performed
475/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000476bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000477 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000478 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000479 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000480 return false;
481
Evan Chenga955c022007-06-19 21:45:13 +0000482 if (TrueBBI.IsBrAnalyzable)
483 return false;
484
Evan Cheng23402fc2007-06-15 21:18:05 +0000485 if (TrueBBI.BB->pred_size() > 1) {
486 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000487 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000488 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000489 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000490 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000491 }
492
Evan Chenga955c022007-06-19 21:45:13 +0000493 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000494}
495
Evan Cheng7783f822007-06-08 09:36:04 +0000496/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000497/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000498/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000499/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000500/// returns the number of instructions that the ifcvt would need to duplicate
501/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000502bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000503 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000504 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000505 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000506 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000507 return false;
508
Evan Cheng23402fc2007-06-15 21:18:05 +0000509 if (TrueBBI.BB->pred_size() > 1) {
510 if (TrueBBI.CannotBeCopied)
511 return false;
512
Evan Cheng92fb5452007-06-15 07:36:12 +0000513 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000514 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000515 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000516 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000517 --Size;
518 else {
519 MachineBasicBlock *FExit = FalseBranch
520 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
521 if (FExit)
522 // Require a conditional branch
523 ++Size;
524 }
525 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000526 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000527 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000528 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000529 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000530
Evan Cheng7783f822007-06-08 09:36:04 +0000531 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
532 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Evan Chengbe9859e2007-06-07 02:12:15 +0000533 MachineFunction::iterator I = TrueBBI.BB;
534 if (++I == TrueBBI.BB->getParent()->end())
535 return false;
Evan Cheng7783f822007-06-08 09:36:04 +0000536 TExit = I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000537 }
Evan Cheng7783f822007-06-08 09:36:04 +0000538 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000539}
540
Evan Cheng7783f822007-06-08 09:36:04 +0000541/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000542/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000543bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
544 unsigned &Dups1, unsigned &Dups2) const {
545 Dups1 = Dups2 = 0;
546 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
547 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000548 return false;
549
Evan Cheng2117d1f2007-06-09 01:03:43 +0000550 MachineBasicBlock *TT = TrueBBI.TrueBB;
551 MachineBasicBlock *FT = FalseBBI.TrueBB;
552
553 if (!TT && blockAlwaysFallThrough(TrueBBI))
554 TT = getNextBlock(TrueBBI.BB);
555 if (!FT && blockAlwaysFallThrough(FalseBBI))
556 FT = getNextBlock(FalseBBI.BB);
557 if (TT != FT)
558 return false;
Craig Topperc0196b12014-04-14 00:51:57 +0000559 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng2117d1f2007-06-09 01:03:43 +0000560 return false;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000561 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
562 return false;
563
564 // FIXME: Allow true block to have an early exit?
565 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
566 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000567 return false;
568
Bob Wilsone1961fe2010-10-26 00:02:24 +0000569 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach6201b992010-06-07 21:28:55 +0000570 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
571 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilsone1961fe2010-10-26 00:02:24 +0000572 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
573 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
574 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000575 // Skip dbg_value instructions. These do not count.
Bob Wilsone1961fe2010-10-26 00:02:24 +0000576 if (TIB->isDebugValue()) {
577 while (TIB != TIE && TIB->isDebugValue())
578 ++TIB;
579 if (TIB == TIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000580 break;
581 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000582 if (FIB->isDebugValue()) {
583 while (FIB != FIE && FIB->isDebugValue())
584 ++FIB;
585 if (FIB == FIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000586 break;
587 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000588 if (!TIB->isIdenticalTo(FIB))
589 break;
590 ++Dups1;
591 ++TIB;
592 ++FIB;
593 }
594
595 // Now, in preparation for counting duplicate instructions at the ends of the
596 // blocks, move the end iterators up past any branch instructions.
597 while (TIE != TIB) {
598 --TIE;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000599 if (!TIE->isBranch())
Bob Wilsone1961fe2010-10-26 00:02:24 +0000600 break;
601 }
602 while (FIE != FIB) {
603 --FIE;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000604 if (!FIE->isBranch())
Bob Wilsone1961fe2010-10-26 00:02:24 +0000605 break;
606 }
607
608 // If Dups1 includes all of a block, then don't count duplicate
609 // instructions at the end of the blocks.
610 if (TIB == TIE || FIB == FIE)
611 return true;
612
613 // Count duplicate instructions at the ends of the blocks.
614 while (TIE != TIB && FIE != FIB) {
615 // Skip dbg_value instructions. These do not count.
616 if (TIE->isDebugValue()) {
617 while (TIE != TIB && TIE->isDebugValue())
618 --TIE;
619 if (TIE == TIB)
620 break;
621 }
622 if (FIE->isDebugValue()) {
623 while (FIE != FIB && FIE->isDebugValue())
624 --FIE;
625 if (FIE == FIB)
626 break;
627 }
628 if (!TIE->isIdenticalTo(FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000629 break;
630 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000631 --TIE;
632 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000633 }
634
635 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000636}
637
Evan Cheng4dd31a72007-06-11 22:26:22 +0000638/// ScanInstructions - Scan all the instructions in the block to determine if
639/// the block is predicable. In most cases, that means all the instructions
Chris Lattnera98c6792008-01-07 01:56:04 +0000640/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng4dd31a72007-06-11 22:26:22 +0000641/// instruction which can clobber a predicate (e.g. condition code register).
642/// If so, the block is not predicable unless it's the last instruction.
643void IfConverter::ScanInstructions(BBInfo &BBI) {
644 if (BBI.IsDone)
645 return;
646
Evan Chengc5adcca2012-06-08 21:53:50 +0000647 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000648 // First analyze the end of BB branches.
Craig Topperc0196b12014-04-14 00:51:57 +0000649 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000650 BBI.BrCond.clear();
651 BBI.IsBrAnalyzable =
652 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000653 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000654
655 if (BBI.BrCond.size()) {
656 // No false branch. This BB must end with a conditional branch and a
657 // fallthrough.
658 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000659 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000660 if (!BBI.FalseBB) {
661 // Malformed bcc? True and false blocks are the same?
662 BBI.IsUnpredicable = true;
663 return;
664 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000665 }
666
667 // Then scan all the instructions.
668 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000669 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000670 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000671 BBI.ClobbersPred = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000672 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
673 I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000674 if (I->isDebugValue())
675 continue;
676
Evan Cheng7f8e5632011-12-07 07:15:52 +0000677 if (I->isNotDuplicable())
Evan Cheng23402fc2007-06-15 21:18:05 +0000678 BBI.CannotBeCopied = true;
679
Evan Cheng4dd31a72007-06-11 22:26:22 +0000680 bool isPredicated = TII->isPredicated(I);
Evan Cheng7f8e5632011-12-07 07:15:52 +0000681 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000682
Joey Goulya5153cb2013-09-09 14:21:49 +0000683 // A conditional branch is not predicable, but it may be eliminated.
684 if (isCondBr)
685 continue;
686
687 if (!isPredicated) {
688 BBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000689 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
690 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000691 if (NumCycles > 1)
692 BBI.ExtraCost += NumCycles-1;
693 BBI.ExtraCost2 += ExtraPredCost;
694 } else if (!AlreadyPredicated) {
695 // FIXME: This instruction is already predicated before the
696 // if-conversion pass. It's probably something like a conditional move.
697 // Mark this block unpredicable for now.
698 BBI.IsUnpredicable = true;
699 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000700 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000701
702 if (BBI.ClobbersPred && !isPredicated) {
703 // Predicate modification instruction should end the block (except for
704 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000705 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000706 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000707 BBI.IsUnpredicable = true;
708 return;
709 }
710
Evan Chengfbc73092007-07-10 17:50:43 +0000711 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
712 // still potentially predicable.
713 std::vector<MachineOperand> PredDefs;
714 if (TII->DefinesPredicate(I, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000715 BBI.ClobbersPred = true;
716
Evan Cheng1f4062f2009-11-21 06:20:26 +0000717 if (!TII->isPredicable(I)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000718 BBI.IsUnpredicable = true;
719 return;
720 }
721 }
722}
723
724/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
725/// predicated by the specified predicate.
726bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000727 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng4dd31a72007-06-11 22:26:22 +0000728 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000729 // If the block is dead or unpredicable, then it cannot be predicated.
730 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000731 return false;
732
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000733 // If it is already predicated but we couldn't analyze its terminator, the
734 // latter might fallthrough, but we can't determine where to.
735 // Conservatively avoid if-converting again.
736 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
737 return false;
738
Quentin Colombetbdab2272013-07-24 20:20:37 +0000739 // If it is already predicated, check if the new predicate subsumes
740 // its predicate.
741 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000742 return false;
743
744 if (BBI.BrCond.size()) {
745 if (!isTriangle)
746 return false;
747
Bob Wilson2371f4f2009-05-13 23:25:24 +0000748 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000749 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
750 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000751 if (RevBranch) {
752 if (TII->ReverseBranchCondition(Cond))
753 return false;
754 }
755 if (TII->ReverseBranchCondition(RevPred) ||
756 !TII->SubsumesPredicate(Cond, RevPred))
757 return false;
758 }
759
760 return true;
761}
762
Evan Cheng7783f822007-06-08 09:36:04 +0000763/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +0000764/// the specified block. Record its successors and whether it looks like an
765/// if-conversion candidate.
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000766void IfConverter::AnalyzeBlock(MachineBasicBlock *MBB,
767 std::vector<IfcvtToken*> &Tokens) {
768 struct BBState {
769 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
770 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000771
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000772 /// This flag is true if MBB's successors have been analyzed.
773 bool SuccsAnalyzed;
774 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000775
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000776 // Push MBB to the stack.
777 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000778
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000779 while (!BBStack.empty()) {
780 BBState &State = BBStack.back();
781 MachineBasicBlock *BB = State.MBB;
782 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000783
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000784 if (!State.SuccsAnalyzed) {
785 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
786 BBStack.pop_back();
787 continue;
788 }
Evan Cheng9030b982007-06-06 10:16:17 +0000789
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000790 BBI.BB = BB;
791 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000792
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000793 ScanInstructions(BBI);
Evan Chengb9bff582009-06-15 21:24:34 +0000794
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000795 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
796 // not considered for ifcvt anymore.
797 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
798 BBI.IsBeingAnalyzed = false;
799 BBI.IsAnalyzed = true;
800 BBStack.pop_back();
801 continue;
802 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000803
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000804 // Do not ifcvt if either path is a back edge to the entry block.
805 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
806 BBI.IsBeingAnalyzed = false;
807 BBI.IsAnalyzed = true;
808 BBStack.pop_back();
809 continue;
810 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000811
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000812 // Do not ifcvt if true and false fallthrough blocks are the same.
813 if (!BBI.FalseBB) {
814 BBI.IsBeingAnalyzed = false;
815 BBI.IsAnalyzed = true;
816 BBStack.pop_back();
817 continue;
818 }
Evan Cheng7783f822007-06-08 09:36:04 +0000819
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000820 // Push the False and True blocks to the stack.
821 State.SuccsAnalyzed = true;
822 BBStack.push_back(BBI.FalseBB);
823 BBStack.push_back(BBI.TrueBB);
824 continue;
825 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000826
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000827 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
828 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +0000829
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000830 if (TrueBBI.IsDone && FalseBBI.IsDone) {
831 BBI.IsBeingAnalyzed = false;
832 BBI.IsAnalyzed = true;
833 BBStack.pop_back();
834 continue;
835 }
836
837 SmallVector<MachineOperand, 4>
838 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
839 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
840
841 unsigned Dups = 0;
842 unsigned Dups2 = 0;
843 bool TNeedSub = !TrueBBI.Predicate.empty();
844 bool FNeedSub = !FalseBBI.Predicate.empty();
845 bool Enqueued = false;
846
847 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
848
849 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
850 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
851 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
852 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000853 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000854 Prediction) &&
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000855 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
856 FeasibilityAnalysis(FalseBBI, RevCond)) {
857 // Diamond:
858 // EBB
859 // / \_
860 // | |
861 // TBB FBB
862 // \ /
863 // TailBB
864 // Note TailBB can be empty.
865 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
866 Dups2));
Evan Cheng3a51c852007-06-16 09:34:52 +0000867 Enqueued = true;
868 }
869
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000870 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
871 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
872 TrueBBI.ExtraCost2, Prediction) &&
873 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
874 // Triangle:
875 // EBB
876 // | \_
877 // | |
878 // | TBB
879 // | /
880 // FBB
881 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
882 Enqueued = true;
883 }
884
885 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
886 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
887 TrueBBI.ExtraCost2, Prediction) &&
888 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
889 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
890 Enqueued = true;
891 }
892
893 if (ValidSimple(TrueBBI, Dups, Prediction) &&
894 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
895 TrueBBI.ExtraCost2, Prediction) &&
896 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
897 // Simple (split, no rejoin):
898 // EBB
899 // | \_
900 // | |
901 // | TBB---> exit
902 // |
903 // FBB
904 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
905 Enqueued = true;
906 }
907
908 if (CanRevCond) {
909 // Try the other path...
910 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
911 Prediction.getCompl()) &&
912 MeetIfcvtSizeLimit(*FalseBBI.BB,
913 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
914 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
915 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
916 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
917 Enqueued = true;
918 }
919
920 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
921 Prediction.getCompl()) &&
922 MeetIfcvtSizeLimit(*FalseBBI.BB,
923 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000924 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000925 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000926 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
927 Enqueued = true;
928 }
929
930 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
931 MeetIfcvtSizeLimit(*FalseBBI.BB,
932 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
933 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
934 FeasibilityAnalysis(FalseBBI, RevCond)) {
935 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
936 Enqueued = true;
937 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000938 }
939
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000940 BBI.IsEnqueued = Enqueued;
941 BBI.IsBeingAnalyzed = false;
942 BBI.IsAnalyzed = true;
943 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +0000944 }
Evan Cheng2e82cef2007-05-18 18:14:37 +0000945}
946
Evan Cheng905a8f42007-05-30 19:49:19 +0000947/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000948/// candidates.
949void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Cheng3a51c852007-06-16 09:34:52 +0000950 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng9808d312011-04-27 19:32:43 +0000951 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
952 MachineBasicBlock *BB = I;
953 AnalyzeBlock(BB, Tokens);
Evan Chengf5e53a52007-05-16 02:00:57 +0000954 }
Evan Cheng905a8f42007-05-30 19:49:19 +0000955
Evan Cheng20e05992007-06-01 00:12:12 +0000956 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +0000957 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +0000958}
959
Evan Cheng288f1542007-06-08 22:01:07 +0000960/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
961/// that all the intervening blocks are empty (given BB can fall through to its
962/// next block).
963static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Chengf128bdc2010-06-16 07:35:02 +0000964 MachineFunction::iterator PI = BB;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000965 MachineFunction::iterator I = std::next(PI);
Evan Cheng2c1acd62007-06-05 07:05:25 +0000966 MachineFunction::iterator TI = ToBB;
967 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +0000968 while (I != TI) {
969 // Check isSuccessor to avoid case where the next block is empty, but
970 // it's not a successor.
971 if (I == E || !I->empty() || !PI->isSuccessor(I))
Evan Cheng312b7232007-06-04 06:47:22 +0000972 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +0000973 PI = I++;
974 }
Evan Cheng312b7232007-06-04 06:47:22 +0000975 return true;
Evan Chenge26c0912007-05-21 22:22:58 +0000976}
977
Evan Cheng51eb2c32007-06-18 08:37:25 +0000978/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
979/// to determine if it can be if-converted. If predecessor is already enqueued,
980/// dequeue it!
981void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +0000982 for (const auto &Predecessor : BB->predecessors()) {
983 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +0000984 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +0000985 continue;
Evan Chengadd97762007-06-14 23:34:09 +0000986 PBBI.IsAnalyzed = false;
987 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +0000988 }
989}
990
Evan Chengc2237ce2007-05-29 22:31:16 +0000991/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
992///
993static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
994 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000995 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +0000996 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +0000997 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +0000998}
999
Evan Cheng288f1542007-06-08 22:01:07 +00001000/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1001/// successors.
1002void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001003 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001004 SmallVector<MachineOperand, 4> Cond;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001005 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
1006 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001007}
1008
Matthias Braund616ccc2013-10-11 19:04:37 +00001009/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1010/// values defined in MI which are not live/used by MI.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001011static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) {
Pete Cooper7605e372015-05-05 20:14:22 +00001012 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
1013 Redefs.stepForward(*MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001014
Pete Cooper7605e372015-05-05 20:14:22 +00001015 // Now add the implicit uses for each of the clobbered values.
1016 for (auto Reg : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001017 // FIXME: Const cast here is nasty, but better than making StepForward
1018 // take a mutable instruction instead of const.
Pete Cooper27483912015-05-06 22:51:04 +00001019 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1020 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001021 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001022 if (Op.isRegMask()) {
1023 // First handle regmasks. They clobber any entries in the mask which
1024 // means that we need a def for those registers.
Pete Cooper7605e372015-05-05 20:14:22 +00001025 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Pete Cooperce9ad752015-05-05 22:09:41 +00001026
1027 // We also need to add an implicit def of this register for the later
1028 // use to read from.
1029 // For the register allocator to have allocated a register clobbered
1030 // by the call which is used later, it must be the case that
1031 // the call doesn't return.
1032 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1033 continue;
1034 }
1035 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001036 if (Op.isDead()) {
1037 // If we found a dead def, but it needs to be live, then remove the dead
1038 // flag.
1039 if (Redefs.contains(Op.getReg()))
1040 Op.setIsDead(false);
1041 }
Pete Cooperce9ad752015-05-05 22:09:41 +00001042 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Matthias Braund616ccc2013-10-11 19:04:37 +00001043 }
1044}
1045
1046/**
1047 * Remove kill flags from operands with a registers in the @p DontKill set.
1048 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001049static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001050 for (MIBundleOperands O(&MI); O.isValid(); ++O) {
1051 if (!O->isReg() || !O->isKill())
1052 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001053 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001054 O->setIsKill(false);
1055 }
1056}
1057
1058/**
1059 * Walks a range of machine instructions and removes kill flags for registers
1060 * in the @p DontKill set.
1061 */
1062static void RemoveKills(MachineBasicBlock::iterator I,
1063 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001064 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001065 const MCRegisterInfo &MCRI) {
1066 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001067 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001068}
1069
Evan Cheng312b7232007-06-04 06:47:22 +00001070/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001071///
Evan Cheng3a51c852007-06-16 09:34:52 +00001072bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001073 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1074 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1075 BBInfo *CvtBBI = &TrueBBI;
1076 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001077
Owen Anderson4f6bf042008-08-14 22:49:33 +00001078 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001079 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001080 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001081
Evan Cheng51eb2c32007-06-18 08:37:25 +00001082 if (CvtBBI->IsDone ||
1083 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001084 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001085 BBI.IsAnalyzed = false;
1086 CvtBBI->IsAnalyzed = false;
1087 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001088 }
Evan Chengd0e66912007-05-23 07:23:16 +00001089
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001090 if (CvtBBI->BB->hasAddressTaken())
1091 // Conservatively abort if-conversion if BB's address is taken.
1092 return false;
1093
Evan Cheng3a51c852007-06-16 09:34:52 +00001094 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001095 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001096 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001097
Bob Wilson45814342010-06-19 05:33:57 +00001098 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001099 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001100 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001101 Redefs.addLiveIns(CvtBBI->BB);
1102 Redefs.addLiveIns(NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001103
1104 // Compute a set of registers which must not be killed by instructions in
1105 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001106 DontKill.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001107 DontKill.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001108
Evan Cheng92fb5452007-06-15 07:36:12 +00001109 if (CvtBBI->BB->pred_size() > 1) {
1110 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001111 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001112 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001113 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001114
1115 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1116 // explicitly remove CvtBBI as a successor.
1117 BBI.BB->removeSuccessor(CvtBBI->BB);
Evan Cheng92fb5452007-06-15 07:36:12 +00001118 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001119 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001120 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001121
Evan Cheng92fb5452007-06-15 07:36:12 +00001122 // Merge converted block into entry block.
1123 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1124 MergeBlocks(BBI, *CvtBBI);
1125 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001126
Evan Chenge4ec9182007-06-06 02:08:52 +00001127 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001128 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001129 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001130 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001131 // Now ifcvt'd block will look like this:
1132 // BB:
1133 // ...
1134 // t, f = cmp
1135 // if t op
1136 // b BBf
1137 //
1138 // We cannot further ifcvt this block because the unconditional branch
1139 // will have to be predicated on the new condition, that will not be
1140 // available if cmp executes.
1141 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001142 }
Evan Chenge26c0912007-05-21 22:22:58 +00001143
Evan Cheng288f1542007-06-08 22:01:07 +00001144 RemoveExtraEdges(BBI);
1145
Evan Chengd0e66912007-05-23 07:23:16 +00001146 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001147 if (!IterIfcvt)
1148 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001149 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001150 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001151
1152 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001153 return true;
1154}
1155
Manman Renb6819182014-01-29 23:18:47 +00001156/// Scale down weights to fit into uint32_t. NewTrue is the new weight
1157/// for successor TrueBB, and NewFalse is the new weight for successor
1158/// FalseBB.
1159static void ScaleWeights(uint64_t NewTrue, uint64_t NewFalse,
1160 MachineBasicBlock *MBB,
1161 const MachineBasicBlock *TrueBB,
1162 const MachineBasicBlock *FalseBB,
1163 const MachineBranchProbabilityInfo *MBPI) {
1164 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1165 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1166 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1167 SE = MBB->succ_end();
1168 SI != SE; ++SI) {
1169 if (*SI == TrueBB)
1170 MBB->setSuccWeight(SI, (uint32_t)(NewTrue / Scale));
1171 else if (*SI == FalseBB)
1172 MBB->setSuccWeight(SI, (uint32_t)(NewFalse / Scale));
1173 else
1174 MBB->setSuccWeight(SI, MBPI->getEdgeWeight(MBB, SI) / Scale);
1175 }
1176}
1177
Evan Chengaf716102007-05-16 21:54:37 +00001178/// IfConvertTriangle - If convert a triangle sub-CFG.
1179///
Evan Cheng3a51c852007-06-16 09:34:52 +00001180bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001181 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001182 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1183 BBInfo *CvtBBI = &TrueBBI;
1184 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001185 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001186
Owen Anderson4f6bf042008-08-14 22:49:33 +00001187 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001188 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001189 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001190
Evan Cheng51eb2c32007-06-18 08:37:25 +00001191 if (CvtBBI->IsDone ||
1192 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001193 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001194 BBI.IsAnalyzed = false;
1195 CvtBBI->IsAnalyzed = false;
1196 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001197 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001198
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001199 if (CvtBBI->BB->hasAddressTaken())
1200 // Conservatively abort if-conversion if BB's address is taken.
1201 return false;
1202
Evan Cheng3a51c852007-06-16 09:34:52 +00001203 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001204 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001205 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001206
Evan Cheng3a51c852007-06-16 09:34:52 +00001207 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001208 if (ReverseBranchCondition(*CvtBBI)) {
1209 // BB has been changed, modify its predecessors (except for this
1210 // one) so they don't get ifcvt'ed based on bad intel.
1211 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1212 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1213 MachineBasicBlock *PBB = *PI;
1214 if (PBB == BBI.BB)
1215 continue;
1216 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1217 if (PBBI.IsEnqueued) {
1218 PBBI.IsAnalyzed = false;
1219 PBBI.IsEnqueued = false;
1220 }
Evan Chengadd97762007-06-14 23:34:09 +00001221 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001222 }
1223 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001224
Bob Wilson45814342010-06-19 05:33:57 +00001225 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001226 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001227 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001228 Redefs.addLiveIns(CvtBBI->BB);
1229 Redefs.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001230
Andrew Trick276dd452013-10-14 20:45:17 +00001231 DontKill.clear();
1232
Craig Topperc0196b12014-04-14 00:51:57 +00001233 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Manman Ren37c92672014-02-07 00:38:56 +00001234 uint64_t CvtNext = 0, CvtFalse = 0, BBNext = 0, BBCvt = 0, SumWeight = 0;
Cong Houec105872015-08-06 18:17:29 +00001235 uint32_t WeightScale = 0;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001236
Manman Renb6819182014-01-29 23:18:47 +00001237 if (HasEarlyExit) {
Manman Ren37c92672014-02-07 00:38:56 +00001238 // Get weights before modifying CvtBBI->BB and BBI.BB.
Manman Renb6819182014-01-29 23:18:47 +00001239 CvtNext = MBPI->getEdgeWeight(CvtBBI->BB, NextBBI->BB);
1240 CvtFalse = MBPI->getEdgeWeight(CvtBBI->BB, CvtBBI->FalseBB);
Manman Ren37c92672014-02-07 00:38:56 +00001241 BBNext = MBPI->getEdgeWeight(BBI.BB, NextBBI->BB);
1242 BBCvt = MBPI->getEdgeWeight(BBI.BB, CvtBBI->BB);
Cong Houec105872015-08-06 18:17:29 +00001243 SumWeight = MBPI->getSumForBlock(CvtBBI->BB, WeightScale);
Manman Renb6819182014-01-29 23:18:47 +00001244 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001245
Bob Wilson1e5da552010-06-29 00:55:23 +00001246 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001247 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001248 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001249 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001250 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001251
1252 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1253 // explicitly remove CvtBBI as a successor.
1254 BBI.BB->removeSuccessor(CvtBBI->BB);
Evan Cheng92fb5452007-06-15 07:36:12 +00001255 } else {
1256 // Predicate the 'true' block after removing its branch.
1257 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001258 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001259
Evan Cheng0598b2d2007-06-18 22:44:57 +00001260 // Now merge the entry of the triangle with the true block.
1261 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001262 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001263 }
1264
Evan Cheng312b7232007-06-04 06:47:22 +00001265 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001266 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001267 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1268 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001269 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001270 llvm_unreachable("Unable to reverse branch condition!");
Craig Topperc0196b12014-04-14 00:51:57 +00001271 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001272 BBI.BB->addSuccessor(CvtBBI->FalseBB);
Manman Renb6819182014-01-29 23:18:47 +00001273 // Update the edge weight for both CvtBBI->FalseBB and NextBBI.
1274 // New_Weight(BBI.BB, NextBBI->BB) =
1275 // Weight(BBI.BB, NextBBI->BB) * getSumForBlock(CvtBBI->BB) +
1276 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, NextBBI->BB)
1277 // New_Weight(BBI.BB, CvtBBI->FalseBB) =
1278 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, CvtBBI->FalseBB)
1279
Cong Houec105872015-08-06 18:17:29 +00001280 uint64_t NewNext = BBNext * SumWeight + (BBCvt * CvtNext) / WeightScale;
1281 uint64_t NewFalse = (BBCvt * CvtFalse) / WeightScale;
Manman Renb6819182014-01-29 23:18:47 +00001282 // We need to scale down all weights of BBI.BB to fit uint32_t.
1283 // Here BBI.BB is connected to CvtBBI->FalseBB and will fall through to
1284 // the next block.
1285 ScaleWeights(NewNext, NewFalse, BBI.BB, getNextBlock(BBI.BB),
1286 CvtBBI->FalseBB, MBPI);
Evan Cheng92fb5452007-06-15 07:36:12 +00001287 }
Evan Cheng7783f822007-06-08 09:36:04 +00001288
1289 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001290 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001291 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001292 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001293 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001294 if (!isFallThrough) {
1295 // Only merge them if the true block does not fallthrough to the false
1296 // block. By not merging them, we make it possible to iteratively
1297 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001298 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001299 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1300 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001301 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001302 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001303 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001304 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1305 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001306 }
Evan Cheng7783f822007-06-08 09:36:04 +00001307 // Mixed predicated and unpredicated code. This cannot be iteratively
1308 // predicated.
1309 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001310 }
Evan Chenge26c0912007-05-21 22:22:58 +00001311
Evan Cheng288f1542007-06-08 22:01:07 +00001312 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001313
Evan Chengd0e66912007-05-23 07:23:16 +00001314 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001315 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001316 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001317 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001318 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001319 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001320 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001321
1322 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001323 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001324}
1325
Evan Chengaf716102007-05-16 21:54:37 +00001326/// IfConvertDiamond - If convert a diamond sub-CFG.
1327///
Evan Cheng51eb2c32007-06-18 08:37:25 +00001328bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1329 unsigned NumDups1, unsigned NumDups2) {
Evan Cheng312b7232007-06-04 06:47:22 +00001330 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2e82cef2007-05-18 18:14:37 +00001331 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng3a51c852007-06-16 09:34:52 +00001332 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson2371f4f2009-05-13 23:25:24 +00001333 // True block must fall through or end with an unanalyzable terminator.
Evan Cheng3a51c852007-06-16 09:34:52 +00001334 if (!TailBB) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001335 if (blockAlwaysFallThrough(TrueBBI))
1336 TailBB = FalseBBI.TrueBB;
1337 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Chengf5e53a52007-05-16 02:00:57 +00001338 }
Evan Chenge26c0912007-05-21 22:22:58 +00001339
Evan Cheng51eb2c32007-06-18 08:37:25 +00001340 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1341 TrueBBI.BB->pred_size() > 1 ||
1342 FalseBBI.BB->pred_size() > 1) {
1343 // Something has changed. It's no longer safe to predicate these blocks.
1344 BBI.IsAnalyzed = false;
1345 TrueBBI.IsAnalyzed = false;
1346 FalseBBI.IsAnalyzed = false;
1347 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001348 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001349
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001350 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1351 // Conservatively abort if-conversion if either BB has its address taken.
1352 return false;
1353
Bob Wilson1e5da552010-06-29 00:55:23 +00001354 // Put the predicated instructions from the 'true' block before the
1355 // instructions from the 'false' block, unless the true block would clobber
1356 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001357 BBInfo *BBI1 = &TrueBBI;
1358 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001359 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001360 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001361 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001362 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1363 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001364
Evan Cheng3a51c852007-06-16 09:34:52 +00001365 // Figure out the more profitable ordering.
1366 bool DoSwap = false;
1367 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1368 DoSwap = true;
1369 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001370 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001371 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001372 }
1373 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001374 std::swap(BBI1, BBI2);
1375 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001376 }
Evan Cheng79484222007-06-05 23:46:14 +00001377
Evan Cheng51eb2c32007-06-18 08:37:25 +00001378 // Remove the conditional branch from entry to the blocks.
1379 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1380
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001381 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001382 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001383 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001384 Redefs.addLiveIns(BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001385
Evan Cheng51eb2c32007-06-18 08:37:25 +00001386 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001387 // Skip dbg_value instructions
Benjamin Kramer6b568962015-06-23 14:47:29 +00001388 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1389 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001390 BBI1->NonPredSize -= NumDups1;
1391 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001392
1393 // Skip past the dups on each side separately since there may be
1394 // differing dbg_value entries.
1395 for (unsigned i = 0; i < NumDups1; ++DI1) {
1396 if (!DI1->isDebugValue())
1397 ++i;
1398 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001399 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001400 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001401 if (!DI2->isDebugValue())
1402 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001403 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001404
Matthias Braund616ccc2013-10-11 19:04:37 +00001405 // Compute a set of registers which must not be killed by instructions in BB1:
1406 // This is everything used+live in BB2 after the duplicated instructions. We
1407 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001408 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001409 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1410 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001411 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001412 }
1413
1414 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1415 ++I) {
Pete Cooper7605e372015-05-05 20:14:22 +00001416 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1417 Redefs.stepForward(*I, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001418 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001419 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1420 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1421
Evan Cheng4266a792011-12-19 22:01:30 +00001422 // Remove branch from 'true' block and remove duplicated instructions.
Evan Cheng79484222007-06-05 23:46:14 +00001423 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001424 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001425 for (unsigned i = 0; i != NumDups2; ) {
1426 // NumDups2 only counted non-dbg_value instructions, so this won't
1427 // run off the head of the list.
1428 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001429 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001430 // skip dbg_value instructions
1431 if (!DI1->isDebugValue())
1432 ++i;
1433 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001434 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001435
Matthias Braund616ccc2013-10-11 19:04:37 +00001436 // Kill flags in the true block for registers living into the false block
1437 // must be removed.
1438 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1439
Evan Cheng4266a792011-12-19 22:01:30 +00001440 // Remove 'false' block branch and find the last instruction to predicate.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001441 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1442 DI2 = BBI2->BB->end();
1443 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001444 // NumDups2 only counted non-dbg_value instructions, so this won't
1445 // run off the head of the list.
1446 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001447 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001448 // skip dbg_value instructions
1449 if (!DI2->isDebugValue())
1450 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001451 }
Evan Cheng4266a792011-12-19 22:01:30 +00001452
1453 // Remember which registers would later be defined by the false block.
1454 // This allows us not to predicate instructions in the true block that would
1455 // later be re-defined. That is, rather than
1456 // subeq r0, r1, #1
1457 // addne r0, r1, #1
1458 // generate:
1459 // sub r0, r1, #1
1460 // addne r0, r1, #1
1461 SmallSet<unsigned, 4> RedefsByFalse;
1462 SmallSet<unsigned, 4> ExtUses;
1463 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1464 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1465 if (FI->isDebugValue())
1466 continue;
1467 SmallVector<unsigned, 4> Defs;
1468 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1469 const MachineOperand &MO = FI->getOperand(i);
1470 if (!MO.isReg())
1471 continue;
1472 unsigned Reg = MO.getReg();
1473 if (!Reg)
1474 continue;
1475 if (MO.isDef()) {
1476 Defs.push_back(Reg);
1477 } else if (!RedefsByFalse.count(Reg)) {
1478 // These are defined before ctrl flow reach the 'false' instructions.
1479 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001480 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1481 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001482 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001483 }
1484 }
1485
1486 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1487 unsigned Reg = Defs[i];
1488 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001489 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1490 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001491 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001492 }
1493 }
1494 }
1495 }
1496
1497 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001498 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001499
1500 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001501 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001502
Evan Cheng0598b2d2007-06-18 22:44:57 +00001503 // Merge the true block into the entry of the diamond.
Craig Topperc0196b12014-04-14 00:51:57 +00001504 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1505 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001506
Bob Wilson2371f4f2009-05-13 23:25:24 +00001507 // If the if-converted block falls through or unconditionally branches into
1508 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001509 // fold the tail block in as well. Otherwise, unless it falls through to the
1510 // tail, add a unconditional branch to it.
1511 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001512 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001513 bool CanMergeTail = !TailBBI.HasFallThrough &&
1514 !TailBBI.BB->hasAddressTaken();
Bob Wilson1e5da552010-06-29 00:55:23 +00001515 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1516 // check if there are any other predecessors besides those.
1517 unsigned NumPreds = TailBB->pred_size();
1518 if (NumPreds > 1)
1519 CanMergeTail = false;
1520 else if (NumPreds == 1 && CanMergeTail) {
1521 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1522 if (*PI != BBI1->BB && *PI != BBI2->BB)
1523 CanMergeTail = false;
1524 }
1525 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001526 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001527 TailBBI.IsDone = true;
1528 } else {
Bob Wilson1e5da552010-06-29 00:55:23 +00001529 BBI.BB->addSuccessor(TailBB);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001530 InsertUncondBranch(BBI.BB, TailBB, TII);
1531 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001532 }
Evan Chenge26c0912007-05-21 22:22:58 +00001533 }
1534
Bob Wilson1e5da552010-06-29 00:55:23 +00001535 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1536 // which can happen here if TailBB is unanalyzable and is merged, so
1537 // explicitly remove BBI1 and BBI2 as successors.
1538 BBI.BB->removeSuccessor(BBI1->BB);
1539 BBI.BB->removeSuccessor(BBI2->BB);
Evan Cheng288f1542007-06-08 22:01:07 +00001540 RemoveExtraEdges(BBI);
1541
Evan Cheng79484222007-06-05 23:46:14 +00001542 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001543 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001544 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001545
1546 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001547 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001548}
1549
Evan Cheng4266a792011-12-19 22:01:30 +00001550static bool MaySpeculate(const MachineInstr *MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001551 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001552 bool SawStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001553 if (!MI->isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001554 return false;
1555
1556 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1557 const MachineOperand &MO = MI->getOperand(i);
1558 if (!MO.isReg())
1559 continue;
1560 unsigned Reg = MO.getReg();
1561 if (!Reg)
1562 continue;
1563 if (MO.isDef() && !LaterRedefs.count(Reg))
1564 return false;
1565 }
1566
1567 return true;
1568}
1569
Evan Cheng51eb2c32007-06-18 08:37:25 +00001570/// PredicateBlock - Predicate instructions from the start of the block to the
1571/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001572void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001573 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001574 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001575 SmallSet<unsigned, 4> *LaterRedefs) {
1576 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001577 bool MaySpec = LaterRedefs != nullptr;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001578 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +00001579 if (I->isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001580 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001581 // It may be possible not to predicate an instruction if it's the 'true'
1582 // side of a diamond and the 'false' side may re-define the instruction's
1583 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001584 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001585 AnyUnpred = true;
1586 continue;
1587 }
1588 // If any instruction is predicated, then every instruction after it must
1589 // be predicated.
1590 MaySpec = false;
Evan Cheng312b7232007-06-04 06:47:22 +00001591 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001592#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001593 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001594#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001595 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001596 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001597
Bob Wilson45814342010-06-19 05:33:57 +00001598 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001599 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001600 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001601 }
Evan Chengd0e66912007-05-23 07:23:16 +00001602
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001603 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001604
Evan Cheng92fb5452007-06-15 07:36:12 +00001605 BBI.IsAnalyzed = false;
1606 BBI.NonPredSize = 0;
1607
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001608 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001609 if (AnyUnpred)
1610 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001611}
1612
Evan Cheng92fb5452007-06-15 07:36:12 +00001613/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1614/// the destination block. Skip end of block branches if IgnoreBr is true.
1615void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001616 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001617 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001618 MachineFunction &MF = *ToBBI.BB->getParent();
1619
Evan Cheng92fb5452007-06-15 07:36:12 +00001620 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1621 E = FromBBI.BB->end(); I != E; ++I) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001622 // Do not copy the end of the block branches.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001623 if (IgnoreBr && I->isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001624 break;
1625
Dan Gohman3b460302008-07-07 23:14:23 +00001626 MachineInstr *MI = MF.CloneMachineInstr(I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001627 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001628 ToBBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +00001629 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
1630 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001631 if (NumCycles > 1)
1632 ToBBI.ExtraCost += NumCycles-1;
1633 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001634
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001635 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001636 if (!TII->PredicateInstruction(MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001637#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001638 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001639#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001640 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001641 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001642 }
1643
Bob Wilson45814342010-06-19 05:33:57 +00001644 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001645 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001646 UpdatePredRedefs(MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001647
1648 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001649 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001650 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001651 }
1652
Bob Wilson1e5da552010-06-29 00:55:23 +00001653 if (!IgnoreBr) {
1654 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1655 FromBBI.BB->succ_end());
1656 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001657 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001658
Bob Wilson1e5da552010-06-29 00:55:23 +00001659 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1660 MachineBasicBlock *Succ = Succs[i];
1661 // Fallthrough edge can't be transferred.
1662 if (Succ == FallThrough)
1663 continue;
1664 ToBBI.BB->addSuccessor(Succ);
1665 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001666 }
1667
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001668 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1669 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001670
1671 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1672 ToBBI.IsAnalyzed = false;
1673
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001674 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001675}
1676
Evan Cheng0f745da2007-05-18 00:20:58 +00001677/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00001678/// This will leave FromBB as an empty block, so remove all of its
1679/// successor edges except for the fall-through edge. If AddEdges is true,
1680/// i.e., when FromBBI's branch is being moved, add those successor edges to
1681/// ToBBI.
1682void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001683 assert(!FromBBI.BB->hasAddressTaken() &&
1684 "Removing a BB whose address is taken!");
1685
Evan Cheng0f745da2007-05-18 00:20:58 +00001686 ToBBI.BB->splice(ToBBI.BB->end(),
1687 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00001688
Evan Chengbe9859e2007-06-07 02:12:15 +00001689 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1690 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00001691 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001692 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng312b7232007-06-04 06:47:22 +00001693
Evan Chengbe9859e2007-06-07 02:12:15 +00001694 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1695 MachineBasicBlock *Succ = Succs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00001696 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001697 if (Succ == FallThrough)
1698 continue;
1699 FromBBI.BB->removeSuccessor(Succ);
Jakob Stoklund Olesene0ef4742013-01-24 23:59:08 +00001700 if (AddEdges && !ToBBI.BB->isSuccessor(Succ))
Bob Wilson1e5da552010-06-29 00:55:23 +00001701 ToBBI.BB->addSuccessor(Succ);
Evan Chengbe9859e2007-06-07 02:12:15 +00001702 }
1703
Bob Wilson2371f4f2009-05-13 23:25:24 +00001704 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00001705 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00001706 FromBBI.BB->addSuccessor(NBB);
1707
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001708 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001709 FromBBI.Predicate.clear();
1710
Evan Chengd0e66912007-05-23 07:23:16 +00001711 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001712 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001713 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001714 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001715 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001716 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001717
Evan Cheng4dd31a72007-06-11 22:26:22 +00001718 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001719 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001720 ToBBI.IsAnalyzed = false;
1721 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001722}
Akira Hatanaka4a616192015-06-08 18:50:43 +00001723
1724FunctionPass *
1725llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
1726 return new IfConverter(Ftor);
1727}