blob: bab55126c29a2abebdf41830cca518443e55c0a2 [file] [log] [blame]
Evan Cheng4e654852007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Cheng4e654852007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the machine instruction level if-conversion pass.
11//
12//===----------------------------------------------------------------------===//
13
Evan Cheng5f702182007-06-01 00:12:12 +000014#define DEBUG_TYPE "ifcvt"
Evan Cheng030a0a02009-09-04 07:47:40 +000015#include "BranchFolding.h"
Evan Cheng4e654852007-05-16 02:00:57 +000016#include "llvm/CodeGen/Passes.h"
17#include "llvm/CodeGen/MachineModuleInfo.h"
Jakub Staszak07672672011-08-03 22:53:41 +000018#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Cheng4e654852007-05-16 02:00:57 +000019#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Cheng791e2e02012-06-08 21:53:50 +000020#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Chengab8be962011-06-29 01:14:12 +000021#include "llvm/MC/MCInstrItineraries.h"
Evan Cheng4e654852007-05-16 02:00:57 +000022#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng86cbfea2007-05-18 00:20:58 +000023#include "llvm/Target/TargetLowering.h"
Evan Cheng4e654852007-05-16 02:00:57 +000024#include "llvm/Target/TargetMachine.h"
Evan Cheng46df4eb2010-06-16 07:35:02 +000025#include "llvm/Target/TargetRegisterInfo.h"
Evan Chengedf48962007-06-08 19:10:51 +000026#include "llvm/Support/CommandLine.h"
Evan Cheng4e654852007-05-16 02:00:57 +000027#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000030#include "llvm/ADT/SmallSet.h"
Evan Cheng4e654852007-05-16 02:00:57 +000031#include "llvm/ADT/Statistic.h"
Evan Chenga1a87872007-06-18 08:37:25 +000032#include "llvm/ADT/STLExtras.h"
Evan Cheng4e654852007-05-16 02:00:57 +000033using namespace llvm;
34
Chris Lattnerf86e1df2008-01-07 05:40:58 +000035// Hidden options for help debugging.
36static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
37static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
38static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000039static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000040 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000041static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000042 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000043static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000044 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000045static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000046 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000047static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000048 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000049static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000050 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000051static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000052 cl::init(false), cl::Hidden);
Evan Cheng46df4eb2010-06-16 07:35:02 +000053static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
54 cl::init(true), cl::Hidden);
Evan Chengedf48962007-06-08 19:10:51 +000055
Evan Cheng1c9f91d2007-06-09 01:03:43 +000056STATISTIC(NumSimple, "Number of simple if-conversions performed");
57STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
58STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Chengcc8fb462007-06-12 23:54:05 +000059STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng1c9f91d2007-06-09 01:03:43 +000060STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
61STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
62STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
63STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng2c8c3a42007-06-15 07:36:12 +000064STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng8787c5f2011-12-19 22:01:30 +000065STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Cheng4e654852007-05-16 02:00:57 +000066
67namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000068 class IfConverter : public MachineFunctionPass {
Evan Chenge882fca2007-06-16 09:34:52 +000069 enum IfcvtKind {
Evan Cheng4e654852007-05-16 02:00:57 +000070 ICNotClassfied, // BB data valid, but not classified.
Evan Chengb6665f62007-06-04 06:47:22 +000071 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Chenge882fca2007-06-16 09:34:52 +000072 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
73 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Chengcc8fb462007-06-12 23:54:05 +000074 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng1c9f91d2007-06-09 01:03:43 +000075 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Chenge882fca2007-06-16 09:34:52 +000076 ICTriangle, // BB is entry of a triangle sub-CFG.
Evan Cheng9618bca2007-06-11 22:26:22 +000077 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Cheng4e654852007-05-16 02:00:57 +000078 };
79
80 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
81 /// if-conversion feasibility analysis. This includes results from
82 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng86cbfea2007-05-18 00:20:58 +000083 /// classification, and common tail block of its successors (if it's a
Evan Chengcf6cc112007-05-18 18:14:37 +000084 /// diamond shape), its size, whether it's predicable, and whether any
85 /// instruction can clobber the 'would-be' predicate.
Evan Chenga13aa952007-05-23 07:23:16 +000086 ///
Evan Cheng9618bca2007-06-11 22:26:22 +000087 /// IsDone - True if BB is not to be considered for ifcvt.
88 /// IsBeingAnalyzed - True if BB is currently being analyzed.
89 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
90 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
91 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
92 /// HasFallThrough - True if BB may fallthrough to the following BB.
93 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Cheng11ce02d2007-07-10 17:50:43 +000094 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng7a655472007-06-06 10:16:17 +000095 /// cmp, call, etc.)
Evan Cheng9618bca2007-06-11 22:26:22 +000096 /// NonPredSize - Number of non-predicated instructions.
Evan Cheng8239daf2010-11-03 00:45:17 +000097 /// ExtraCost - Extra cost for multi-cycle instructions.
98 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chenga13aa952007-05-23 07:23:16 +000099 /// BB - Corresponding MachineBasicBlock.
100 /// TrueBB / FalseBB- See AnalyzeBranch().
101 /// BrCond - Conditions for end of block conditional branches.
102 /// Predicate - Predicate used in the BB.
Evan Cheng4e654852007-05-16 02:00:57 +0000103 struct BBInfo {
Evan Cheng9618bca2007-06-11 22:26:22 +0000104 bool IsDone : 1;
105 bool IsBeingAnalyzed : 1;
106 bool IsAnalyzed : 1;
107 bool IsEnqueued : 1;
108 bool IsBrAnalyzable : 1;
109 bool HasFallThrough : 1;
110 bool IsUnpredicable : 1;
Evan Chenga2acf842007-06-15 21:18:05 +0000111 bool CannotBeCopied : 1;
Evan Cheng9618bca2007-06-11 22:26:22 +0000112 bool ClobbersPred : 1;
Evan Chenga13aa952007-05-23 07:23:16 +0000113 unsigned NonPredSize;
Bob Wilson2ad40d32010-10-26 00:02:21 +0000114 unsigned ExtraCost;
Evan Cheng8239daf2010-11-03 00:45:17 +0000115 unsigned ExtraCost2;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000116 MachineBasicBlock *BB;
117 MachineBasicBlock *TrueBB;
118 MachineBasicBlock *FalseBB;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000119 SmallVector<MachineOperand, 4> BrCond;
120 SmallVector<MachineOperand, 4> Predicate;
Evan Chenge882fca2007-06-16 09:34:52 +0000121 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng9618bca2007-06-11 22:26:22 +0000122 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
123 HasFallThrough(false), IsUnpredicable(false),
Evan Chenga2acf842007-06-15 21:18:05 +0000124 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Evan Cheng8239daf2010-11-03 00:45:17 +0000125 ExtraCost(0), ExtraCost2(0), BB(0), TrueBB(0), FalseBB(0) {}
Evan Chenge882fca2007-06-16 09:34:52 +0000126 };
127
Bob Wilson669db042010-06-15 18:19:27 +0000128 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Chenge882fca2007-06-16 09:34:52 +0000129 /// BBI - Corresponding BBInfo.
130 /// Kind - Type of block. See IfcvtKind.
Bob Wilson9c4856a2009-05-13 23:25:24 +0000131 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Chenge882fca2007-06-16 09:34:52 +0000132 /// predicated.
Evan Chenga1a87872007-06-18 08:37:25 +0000133 /// NumDups - Number of instructions that would be duplicated due
134 /// to this if-conversion. (For diamonds, the number of
135 /// identical instructions at the beginnings of both
136 /// paths).
137 /// NumDups2 - For diamonds, the number of identical instructions
138 /// at the ends of both paths.
Evan Chenge882fca2007-06-16 09:34:52 +0000139 struct IfcvtToken {
140 BBInfo &BBI;
141 IfcvtKind Kind;
Bob Wilson9c4856a2009-05-13 23:25:24 +0000142 bool NeedSubsumption;
Evan Chenga1a87872007-06-18 08:37:25 +0000143 unsigned NumDups;
144 unsigned NumDups2;
145 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson9c4856a2009-05-13 23:25:24 +0000146 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Cheng4e654852007-05-16 02:00:57 +0000147 };
148
149 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
150 /// basic block number.
151 std::vector<BBInfo> BBAnalysis;
152
Evan Cheng86cbfea2007-05-18 00:20:58 +0000153 const TargetLowering *TLI;
Evan Cheng4e654852007-05-16 02:00:57 +0000154 const TargetInstrInfo *TII;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000155 const TargetRegisterInfo *TRI;
Evan Cheng3ef1c872010-09-10 01:29:16 +0000156 const InstrItineraryData *InstrItins;
Jakub Staszak990f78d2011-08-03 22:34:43 +0000157 const MachineBranchProbabilityInfo *MBPI;
Evan Cheng791e2e02012-06-08 21:53:50 +0000158 MachineRegisterInfo *MRI;
Jakub Staszak990f78d2011-08-03 22:34:43 +0000159
Evan Cheng791e2e02012-06-08 21:53:50 +0000160 bool PreRegAlloc;
Evan Cheng4e654852007-05-16 02:00:57 +0000161 bool MadeChange;
Owen Anderson13bbe4b2009-06-24 23:41:44 +0000162 int FnNum;
Evan Cheng4e654852007-05-16 02:00:57 +0000163 public:
164 static char ID;
Owen Anderson081c34b2010-10-19 17:21:58 +0000165 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
166 initializeIfConverterPass(*PassRegistry::getPassRegistry());
167 }
Jakub Staszak990f78d2011-08-03 22:34:43 +0000168
Owen Anderson7571ee72010-09-28 20:42:15 +0000169 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Jakub Staszak990f78d2011-08-03 22:34:43 +0000170 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson7571ee72010-09-28 20:42:15 +0000171 MachineFunctionPass::getAnalysisUsage(AU);
172 }
Evan Cheng4e654852007-05-16 02:00:57 +0000173
174 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Cheng4e654852007-05-16 02:00:57 +0000175
176 private:
Evan Chengb6665f62007-06-04 06:47:22 +0000177 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersone3cc84a2010-10-01 22:45:50 +0000178 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000179 const BranchProbability &Prediction) const;
Evan Chengac5f1422007-06-08 09:36:04 +0000180 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000181 bool FalseBranch, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000182 const BranchProbability &Prediction) const;
Evan Chenga1a87872007-06-18 08:37:25 +0000183 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
184 unsigned &Dups1, unsigned &Dups2) const;
Evan Chengac5f1422007-06-08 09:36:04 +0000185 void ScanInstructions(BBInfo &BBI);
Evan Chenge882fca2007-06-16 09:34:52 +0000186 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
187 std::vector<IfcvtToken*> &Tokens);
Owen Anderson44eb65c2008-08-14 22:49:33 +0000188 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Chengac5f1422007-06-08 09:36:04 +0000189 bool isTriangle = false, bool RevBranch = false);
Bob Wilson6fb124b2010-06-15 18:57:15 +0000190 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Evan Chenga1a87872007-06-18 08:37:25 +0000191 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng7e75ba82007-06-08 22:01:07 +0000192 void RemoveExtraEdges(BBInfo &BBI);
Evan Chenge882fca2007-06-16 09:34:52 +0000193 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
194 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Chenga1a87872007-06-18 08:37:25 +0000195 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
196 unsigned NumDups1, unsigned NumDups2);
Evan Chenga13aa952007-05-23 07:23:16 +0000197 void PredicateBlock(BBInfo &BBI,
Evan Chenga1a87872007-06-18 08:37:25 +0000198 MachineBasicBlock::iterator E,
Evan Cheng46df4eb2010-06-16 07:35:02 +0000199 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng8787c5f2011-12-19 22:01:30 +0000200 SmallSet<unsigned, 4> &Redefs,
201 SmallSet<unsigned, 4> *LaterRedefs = 0);
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000202 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +0000203 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng46df4eb2010-06-16 07:35:02 +0000204 SmallSet<unsigned, 4> &Redefs,
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000205 bool IgnoreBr = false);
Bob Wilson8eab75f2010-06-29 00:55:23 +0000206 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng5f702182007-06-01 00:12:12 +0000207
Evan Cheng8239daf2010-11-03 00:45:17 +0000208 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
209 unsigned Cycle, unsigned Extra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000210 const BranchProbability &Prediction) const {
Evan Cheng8239daf2010-11-03 00:45:17 +0000211 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000212 Prediction);
Evan Cheng13151432010-06-25 22:42:03 +0000213 }
214
Evan Cheng8239daf2010-11-03 00:45:17 +0000215 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
216 unsigned TCycle, unsigned TExtra,
217 MachineBasicBlock &FBB,
218 unsigned FCycle, unsigned FExtra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000219 const BranchProbability &Prediction) const {
Evan Cheng8239daf2010-11-03 00:45:17 +0000220 return TCycle > 0 && FCycle > 0 &&
221 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000222 Prediction);
Evan Chenga1a87872007-06-18 08:37:25 +0000223 }
224
Evan Chengd4de6d92007-06-07 02:12:15 +0000225 // blockAlwaysFallThrough - Block ends without a terminator.
226 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Evan Cheng9618bca2007-06-11 22:26:22 +0000227 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
Evan Cheng7a655472007-06-06 10:16:17 +0000228 }
229
Evan Chenge882fca2007-06-16 09:34:52 +0000230 // IfcvtTokenCmp - Used to sort if-conversion candidates.
231 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
Evan Chenga1a87872007-06-18 08:37:25 +0000232 int Incr1 = (C1->Kind == ICDiamond)
233 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
234 int Incr2 = (C2->Kind == ICDiamond)
235 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
236 if (Incr1 > Incr2)
Evan Chenge882fca2007-06-16 09:34:52 +0000237 return true;
Evan Chenga1a87872007-06-18 08:37:25 +0000238 else if (Incr1 == Incr2) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000239 // Favors subsumption.
240 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
Evan Chenge882fca2007-06-16 09:34:52 +0000241 return true;
Bob Wilson9c4856a2009-05-13 23:25:24 +0000242 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Chenge882fca2007-06-16 09:34:52 +0000243 // Favors diamond over triangle, etc.
244 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
245 return true;
246 else if (C1->Kind == C2->Kind)
247 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
248 }
249 }
250 return false;
Evan Cheng5f702182007-06-01 00:12:12 +0000251 }
Evan Cheng4e654852007-05-16 02:00:57 +0000252 };
Evan Chenge882fca2007-06-16 09:34:52 +0000253
Evan Cheng4e654852007-05-16 02:00:57 +0000254 char IfConverter::ID = 0;
255}
256
Andrew Trick1dd8c852012-02-08 21:23:13 +0000257char &llvm::IfConverterID = IfConverter::ID;
258
Owen Anderson2ab36d32010-10-12 19:48:12 +0000259INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak990f78d2011-08-03 22:34:43 +0000260INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000261INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilsona5971032009-10-28 20:46:46 +0000262
Evan Cheng4e654852007-05-16 02:00:57 +0000263bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng86cbfea2007-05-18 00:20:58 +0000264 TLI = MF.getTarget().getTargetLowering();
Evan Cheng4e654852007-05-16 02:00:57 +0000265 TII = MF.getTarget().getInstrInfo();
Evan Cheng46df4eb2010-06-16 07:35:02 +0000266 TRI = MF.getTarget().getRegisterInfo();
Jakub Staszak990f78d2011-08-03 22:34:43 +0000267 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Cheng791e2e02012-06-08 21:53:50 +0000268 MRI = &MF.getRegInfo();
Evan Cheng3ef1c872010-09-10 01:29:16 +0000269 InstrItins = MF.getTarget().getInstrItineraryData();
Evan Cheng4e654852007-05-16 02:00:57 +0000270 if (!TII) return false;
271
Evan Cheng791e2e02012-06-08 21:53:50 +0000272 PreRegAlloc = MRI->isSSA();
273
274 bool BFChange = false;
275 if (!PreRegAlloc) {
276 // Tail merge tend to expose more if-conversion opportunities.
277 BranchFolder BF(true, false);
278 BFChange = BF.OptimizeFunction(MF, TII,
Evan Cheng86050dc2010-06-18 23:09:54 +0000279 MF.getTarget().getRegisterInfo(),
280 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Cheng791e2e02012-06-08 21:53:50 +0000281 }
Evan Cheng86050dc2010-06-18 23:09:54 +0000282
David Greene083b7ff2010-01-04 22:02:01 +0000283 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Topper96601ca2012-08-22 06:07:19 +0000284 << MF.getName() << "\'");
Evan Chengedf48962007-06-08 19:10:51 +0000285
286 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene083b7ff2010-01-04 22:02:01 +0000287 DEBUG(dbgs() << " skipped\n");
Evan Chengedf48962007-06-08 19:10:51 +0000288 return false;
289 }
David Greene083b7ff2010-01-04 22:02:01 +0000290 DEBUG(dbgs() << "\n");
Evan Cheng5f702182007-06-01 00:12:12 +0000291
Evan Cheng4e654852007-05-16 02:00:57 +0000292 MF.RenumberBlocks();
Evan Cheng5f702182007-06-01 00:12:12 +0000293 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Cheng4e654852007-05-16 02:00:57 +0000294
Evan Chenge882fca2007-06-16 09:34:52 +0000295 std::vector<IfcvtToken*> Tokens;
Evan Cheng47d25022007-05-18 01:55:58 +0000296 MadeChange = false;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000297 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
298 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
299 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000300 // Do an initial analysis for each basic block and find all the potential
301 // candidates to perform if-conversion.
Bob Wilson6fb124b2010-06-15 18:57:15 +0000302 bool Change = false;
303 AnalyzeBlocks(MF, Tokens);
Evan Chenge882fca2007-06-16 09:34:52 +0000304 while (!Tokens.empty()) {
305 IfcvtToken *Token = Tokens.back();
306 Tokens.pop_back();
307 BBInfo &BBI = Token->BBI;
308 IfcvtKind Kind = Token->Kind;
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000309 unsigned NumDups = Token->NumDups;
Duncan Sands20d629c2008-11-04 18:05:30 +0000310 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000311
312 delete Token;
Evan Chengb6665f62007-06-04 06:47:22 +0000313
Evan Cheng9618bca2007-06-11 22:26:22 +0000314 // If the block has been evicted out of the queue or it has already been
315 // marked dead (due to it being predicated), then skip it.
Evan Chenge882fca2007-06-16 09:34:52 +0000316 if (BBI.IsDone)
317 BBI.IsEnqueued = false;
318 if (!BBI.IsEnqueued)
Evan Cheng9618bca2007-06-11 22:26:22 +0000319 continue;
Evan Chenge882fca2007-06-16 09:34:52 +0000320
Evan Cheng86ff2962007-06-14 20:28:52 +0000321 BBI.IsEnqueued = false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000322
Evan Chengb6665f62007-06-04 06:47:22 +0000323 bool RetVal = false;
Evan Chenge882fca2007-06-16 09:34:52 +0000324 switch (Kind) {
Craig Topper5e25ee82012-02-05 08:31:47 +0000325 default: llvm_unreachable("Unexpected!");
Evan Chengb6665f62007-06-04 06:47:22 +0000326 case ICSimple:
Evan Chengcb78d672007-06-06 01:12:44 +0000327 case ICSimpleFalse: {
Evan Chenge882fca2007-06-16 09:34:52 +0000328 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000329 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson92fffe02010-06-15 22:18:54 +0000330 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
331 " false" : "")
Bill Wendling44ff7942009-08-22 20:11:17 +0000332 << "): BB#" << BBI.BB->getNumber() << " ("
333 << ((Kind == ICSimpleFalse)
334 ? BBI.FalseBB->getNumber()
335 : BBI.TrueBB->getNumber()) << ") ");
Evan Chenge882fca2007-06-16 09:34:52 +0000336 RetVal = IfConvertSimple(BBI, Kind);
David Greene083b7ff2010-01-04 22:02:01 +0000337 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +0000338 if (RetVal) {
Dan Gohmanfe601042010-06-22 15:08:57 +0000339 if (isFalse) ++NumSimpleFalse;
340 else ++NumSimple;
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +0000341 }
Evan Chengb6665f62007-06-04 06:47:22 +0000342 break;
Evan Chengcb78d672007-06-06 01:12:44 +0000343 }
Evan Chenga13aa952007-05-23 07:23:16 +0000344 case ICTriangle:
Evan Chengcc8fb462007-06-12 23:54:05 +0000345 case ICTriangleRev:
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000346 case ICTriangleFalse:
Reid Spencera9bf49c2007-06-10 00:19:17 +0000347 case ICTriangleFRev: {
Evan Chenge882fca2007-06-16 09:34:52 +0000348 bool isFalse = Kind == ICTriangleFalse;
349 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Chengcc8fb462007-06-12 23:54:05 +0000350 if (DisableTriangle && !isFalse && !isRev) break;
351 if (DisableTriangleR && !isFalse && isRev) break;
352 if (DisableTriangleF && isFalse && !isRev) break;
353 if (DisableTriangleFR && isFalse && isRev) break;
David Greene083b7ff2010-01-04 22:02:01 +0000354 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000355 if (isFalse)
David Greene083b7ff2010-01-04 22:02:01 +0000356 DEBUG(dbgs() << " false");
Evan Chengcc8fb462007-06-12 23:54:05 +0000357 if (isRev)
David Greene083b7ff2010-01-04 22:02:01 +0000358 DEBUG(dbgs() << " rev");
359 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendling44ff7942009-08-22 20:11:17 +0000360 << BBI.TrueBB->getNumber() << ",F:"
361 << BBI.FalseBB->getNumber() << ") ");
Evan Chenge882fca2007-06-16 09:34:52 +0000362 RetVal = IfConvertTriangle(BBI, Kind);
David Greene083b7ff2010-01-04 22:02:01 +0000363 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000364 if (RetVal) {
Evan Chengcc8fb462007-06-12 23:54:05 +0000365 if (isFalse) {
Dan Gohmanfe601042010-06-22 15:08:57 +0000366 if (isRev) ++NumTriangleFRev;
367 else ++NumTriangleFalse;
Evan Chengcc8fb462007-06-12 23:54:05 +0000368 } else {
Dan Gohmanfe601042010-06-22 15:08:57 +0000369 if (isRev) ++NumTriangleRev;
370 else ++NumTriangle;
Evan Chengcc8fb462007-06-12 23:54:05 +0000371 }
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000372 }
Evan Chenga13aa952007-05-23 07:23:16 +0000373 break;
Reid Spencera9bf49c2007-06-10 00:19:17 +0000374 }
Evan Chenge882fca2007-06-16 09:34:52 +0000375 case ICDiamond: {
Evan Chengedf48962007-06-08 19:10:51 +0000376 if (DisableDiamond) break;
David Greene083b7ff2010-01-04 22:02:01 +0000377 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendling44ff7942009-08-22 20:11:17 +0000378 << BBI.TrueBB->getNumber() << ",F:"
379 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000380 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene083b7ff2010-01-04 22:02:01 +0000381 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanfe601042010-06-22 15:08:57 +0000382 if (RetVal) ++NumDiamonds;
Evan Chenga13aa952007-05-23 07:23:16 +0000383 break;
384 }
Evan Chenge882fca2007-06-16 09:34:52 +0000385 }
386
Evan Chengb6665f62007-06-04 06:47:22 +0000387 Change |= RetVal;
Evan Chengedf48962007-06-08 19:10:51 +0000388
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000389 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
390 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
391 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chengedf48962007-06-08 19:10:51 +0000392 break;
Evan Cheng4e654852007-05-16 02:00:57 +0000393 }
Evan Chenga13aa952007-05-23 07:23:16 +0000394
Evan Chenga13aa952007-05-23 07:23:16 +0000395 if (!Change)
396 break;
Evan Chengb6665f62007-06-04 06:47:22 +0000397 MadeChange |= Change;
Evan Cheng4e654852007-05-16 02:00:57 +0000398 }
Evan Cheng47d25022007-05-18 01:55:58 +0000399
Evan Chenge882fca2007-06-16 09:34:52 +0000400 // Delete tokens in case of early exit.
401 while (!Tokens.empty()) {
402 IfcvtToken *Token = Tokens.back();
403 Tokens.pop_back();
404 delete Token;
405 }
406
407 Tokens.clear();
Evan Cheng47d25022007-05-18 01:55:58 +0000408 BBAnalysis.clear();
409
Evan Cheng6a5e2832010-06-18 22:17:13 +0000410 if (MadeChange && IfCvtBranchFold) {
Evan Chengcbc988b2011-05-12 00:56:58 +0000411 BranchFolder BF(false, false);
Evan Cheng030a0a02009-09-04 07:47:40 +0000412 BF.OptimizeFunction(MF, TII,
413 MF.getTarget().getRegisterInfo(),
414 getAnalysisIfAvailable<MachineModuleInfo>());
415 }
416
Evan Cheng86050dc2010-06-18 23:09:54 +0000417 MadeChange |= BFChange;
Evan Cheng4e654852007-05-16 02:00:57 +0000418 return MadeChange;
419}
420
Evan Chenge882fca2007-06-16 09:34:52 +0000421/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
422/// its 'true' successor.
Evan Cheng4e654852007-05-16 02:00:57 +0000423static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng86cbfea2007-05-18 00:20:58 +0000424 MachineBasicBlock *TrueBB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000425 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
426 E = BB->succ_end(); SI != E; ++SI) {
427 MachineBasicBlock *SuccBB = *SI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000428 if (SuccBB != TrueBB)
Evan Cheng4e654852007-05-16 02:00:57 +0000429 return SuccBB;
430 }
431 return NULL;
432}
433
Evan Chenge882fca2007-06-16 09:34:52 +0000434/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson9c4856a2009-05-13 23:25:24 +0000435/// branch. Swap block's 'true' and 'false' successors.
Evan Chengb6665f62007-06-04 06:47:22 +0000436bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings3bf91252010-06-17 22:43:56 +0000437 DebugLoc dl; // FIXME: this is nowhere
Evan Chengb6665f62007-06-04 06:47:22 +0000438 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
439 TII->RemoveBranch(*BBI.BB);
Stuart Hastings3bf91252010-06-17 22:43:56 +0000440 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Chengb6665f62007-06-04 06:47:22 +0000441 std::swap(BBI.TrueBB, BBI.FalseBB);
442 return true;
443 }
444 return false;
445}
446
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000447/// getNextBlock - Returns the next block in the function blocks ordering. If
448/// it is the end, returns NULL.
449static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
450 MachineFunction::iterator I = BB;
451 MachineFunction::iterator E = BB->getParent()->end();
452 if (++I == E)
453 return NULL;
454 return I;
455}
456
Evan Chengac5f1422007-06-08 09:36:04 +0000457/// ValidSimple - Returns true if the 'true' block (along with its
Evan Chenge882fca2007-06-16 09:34:52 +0000458/// predecessor) forms a valid simple shape for ifcvt. It also returns the
459/// number of instructions that the ifcvt would need to duplicate if performed
460/// in Dups.
Owen Anderson7571ee72010-09-28 20:42:15 +0000461bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000462 const BranchProbability &Prediction) const {
Evan Chenge882fca2007-06-16 09:34:52 +0000463 Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000464 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000465 return false;
466
Evan Cheng9ffd3402007-06-19 21:45:13 +0000467 if (TrueBBI.IsBrAnalyzable)
468 return false;
469
Evan Chenga2acf842007-06-15 21:18:05 +0000470 if (TrueBBI.BB->pred_size() > 1) {
471 if (TrueBBI.CannotBeCopied ||
Owen Anderson7571ee72010-09-28 20:42:15 +0000472 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000473 Prediction))
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000474 return false;
Evan Chenge882fca2007-06-16 09:34:52 +0000475 Dups = TrueBBI.NonPredSize;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000476 }
477
Evan Cheng9ffd3402007-06-19 21:45:13 +0000478 return true;
Evan Cheng7a655472007-06-06 10:16:17 +0000479}
480
Evan Chengac5f1422007-06-08 09:36:04 +0000481/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000482/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Chenge882fca2007-06-16 09:34:52 +0000483/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson92fffe02010-06-15 22:18:54 +0000484/// branches to the 'false' block rather than the other way around. It also
Evan Chenge882fca2007-06-16 09:34:52 +0000485/// returns the number of instructions that the ifcvt would need to duplicate
486/// if performed in 'Dups'.
Evan Chengac5f1422007-06-08 09:36:04 +0000487bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000488 bool FalseBranch, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000489 const BranchProbability &Prediction) const {
Evan Chenge882fca2007-06-16 09:34:52 +0000490 Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000491 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000492 return false;
493
Evan Chenga2acf842007-06-15 21:18:05 +0000494 if (TrueBBI.BB->pred_size() > 1) {
495 if (TrueBBI.CannotBeCopied)
496 return false;
497
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000498 unsigned Size = TrueBBI.NonPredSize;
Evan Chenge882fca2007-06-16 09:34:52 +0000499 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman30359592008-01-29 13:02:09 +0000500 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson9c4856a2009-05-13 23:25:24 +0000501 // Ends with an unconditional branch. It will be removed.
Evan Chenge882fca2007-06-16 09:34:52 +0000502 --Size;
503 else {
504 MachineBasicBlock *FExit = FalseBranch
505 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
506 if (FExit)
507 // Require a conditional branch
508 ++Size;
509 }
510 }
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000511 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000512 return false;
Evan Chenge882fca2007-06-16 09:34:52 +0000513 Dups = Size;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000514 }
Evan Chengd4de6d92007-06-07 02:12:15 +0000515
Evan Chengac5f1422007-06-08 09:36:04 +0000516 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
517 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Evan Chengd4de6d92007-06-07 02:12:15 +0000518 MachineFunction::iterator I = TrueBBI.BB;
519 if (++I == TrueBBI.BB->getParent()->end())
520 return false;
Evan Chengac5f1422007-06-08 09:36:04 +0000521 TExit = I;
Evan Chengd4de6d92007-06-07 02:12:15 +0000522 }
Evan Chengac5f1422007-06-08 09:36:04 +0000523 return TExit && TExit == FalseBBI.BB;
Evan Chengd4de6d92007-06-07 02:12:15 +0000524}
525
Evan Chengac5f1422007-06-08 09:36:04 +0000526/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000527/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Chenga1a87872007-06-18 08:37:25 +0000528bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
529 unsigned &Dups1, unsigned &Dups2) const {
530 Dups1 = Dups2 = 0;
531 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
532 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000533 return false;
534
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000535 MachineBasicBlock *TT = TrueBBI.TrueBB;
536 MachineBasicBlock *FT = FalseBBI.TrueBB;
537
538 if (!TT && blockAlwaysFallThrough(TrueBBI))
539 TT = getNextBlock(TrueBBI.BB);
540 if (!FT && blockAlwaysFallThrough(FalseBBI))
541 FT = getNextBlock(FalseBBI.BB);
542 if (TT != FT)
543 return false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000544 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000545 return false;
Evan Chengc4047a82007-06-18 22:44:57 +0000546 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
547 return false;
548
549 // FIXME: Allow true block to have an early exit?
550 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
551 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Chenga1a87872007-06-18 08:37:25 +0000552 return false;
553
Bob Wilson7c730e72010-10-26 00:02:24 +0000554 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach66f360e2010-06-07 21:28:55 +0000555 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
556 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilson7c730e72010-10-26 00:02:24 +0000557 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
558 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
559 while (TIB != TIE && FIB != FIE) {
Evan Chenga9934dc2010-06-18 21:52:57 +0000560 // Skip dbg_value instructions. These do not count.
Bob Wilson7c730e72010-10-26 00:02:24 +0000561 if (TIB->isDebugValue()) {
562 while (TIB != TIE && TIB->isDebugValue())
563 ++TIB;
564 if (TIB == TIE)
Evan Chenga9934dc2010-06-18 21:52:57 +0000565 break;
566 }
Bob Wilson7c730e72010-10-26 00:02:24 +0000567 if (FIB->isDebugValue()) {
568 while (FIB != FIE && FIB->isDebugValue())
569 ++FIB;
570 if (FIB == FIE)
Evan Chenga9934dc2010-06-18 21:52:57 +0000571 break;
572 }
Bob Wilson7c730e72010-10-26 00:02:24 +0000573 if (!TIB->isIdenticalTo(FIB))
574 break;
575 ++Dups1;
576 ++TIB;
577 ++FIB;
578 }
579
580 // Now, in preparation for counting duplicate instructions at the ends of the
581 // blocks, move the end iterators up past any branch instructions.
582 while (TIE != TIB) {
583 --TIE;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000584 if (!TIE->isBranch())
Bob Wilson7c730e72010-10-26 00:02:24 +0000585 break;
586 }
587 while (FIE != FIB) {
588 --FIE;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000589 if (!FIE->isBranch())
Bob Wilson7c730e72010-10-26 00:02:24 +0000590 break;
591 }
592
593 // If Dups1 includes all of a block, then don't count duplicate
594 // instructions at the end of the blocks.
595 if (TIB == TIE || FIB == FIE)
596 return true;
597
598 // Count duplicate instructions at the ends of the blocks.
599 while (TIE != TIB && FIE != FIB) {
600 // Skip dbg_value instructions. These do not count.
601 if (TIE->isDebugValue()) {
602 while (TIE != TIB && TIE->isDebugValue())
603 --TIE;
604 if (TIE == TIB)
605 break;
606 }
607 if (FIE->isDebugValue()) {
608 while (FIE != FIB && FIE->isDebugValue())
609 --FIE;
610 if (FIE == FIB)
611 break;
612 }
613 if (!TIE->isIdenticalTo(FIE))
Evan Chenga1a87872007-06-18 08:37:25 +0000614 break;
615 ++Dups2;
Bob Wilson7c730e72010-10-26 00:02:24 +0000616 --TIE;
617 --FIE;
Evan Chenga1a87872007-06-18 08:37:25 +0000618 }
619
620 return true;
Evan Chengd4de6d92007-06-07 02:12:15 +0000621}
622
Evan Cheng9618bca2007-06-11 22:26:22 +0000623/// ScanInstructions - Scan all the instructions in the block to determine if
624/// the block is predicable. In most cases, that means all the instructions
Chris Lattner69244302008-01-07 01:56:04 +0000625/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng9618bca2007-06-11 22:26:22 +0000626/// instruction which can clobber a predicate (e.g. condition code register).
627/// If so, the block is not predicable unless it's the last instruction.
628void IfConverter::ScanInstructions(BBInfo &BBI) {
629 if (BBI.IsDone)
630 return;
631
Evan Cheng791e2e02012-06-08 21:53:50 +0000632 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng9618bca2007-06-11 22:26:22 +0000633 // First analyze the end of BB branches.
Evan Chengb7c908b2007-06-14 21:26:08 +0000634 BBI.TrueBB = BBI.FalseBB = NULL;
Evan Cheng9618bca2007-06-11 22:26:22 +0000635 BBI.BrCond.clear();
636 BBI.IsBrAnalyzable =
637 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
638 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
639
640 if (BBI.BrCond.size()) {
641 // No false branch. This BB must end with a conditional branch and a
642 // fallthrough.
643 if (!BBI.FalseBB)
Bob Wilson92fffe02010-06-15 22:18:54 +0000644 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Cheng2077e182009-06-15 21:24:34 +0000645 if (!BBI.FalseBB) {
646 // Malformed bcc? True and false blocks are the same?
647 BBI.IsUnpredicable = true;
648 return;
649 }
Evan Cheng9618bca2007-06-11 22:26:22 +0000650 }
651
652 // Then scan all the instructions.
653 BBI.NonPredSize = 0;
Bob Wilson2ad40d32010-10-26 00:02:21 +0000654 BBI.ExtraCost = 0;
Evan Cheng8239daf2010-11-03 00:45:17 +0000655 BBI.ExtraCost2 = 0;
Evan Cheng9618bca2007-06-11 22:26:22 +0000656 BBI.ClobbersPred = false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000657 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
658 I != E; ++I) {
Jim Grosbach870c8052010-06-04 23:01:26 +0000659 if (I->isDebugValue())
660 continue;
661
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000662 if (I->isNotDuplicable())
Evan Chenga2acf842007-06-15 21:18:05 +0000663 BBI.CannotBeCopied = true;
664
Evan Cheng9618bca2007-06-11 22:26:22 +0000665 bool isPredicated = TII->isPredicated(I);
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000666 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
Evan Cheng9618bca2007-06-11 22:26:22 +0000667
Evan Chengd2c5eb82007-07-06 23:24:39 +0000668 if (!isCondBr) {
Evan Cheng3ef1c872010-09-10 01:29:16 +0000669 if (!isPredicated) {
Bob Wilson2ad40d32010-10-26 00:02:21 +0000670 BBI.NonPredSize++;
Evan Cheng8239daf2010-11-03 00:45:17 +0000671 unsigned ExtraPredCost = 0;
672 unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I,
673 &ExtraPredCost);
674 if (NumCycles > 1)
675 BBI.ExtraCost += NumCycles-1;
676 BBI.ExtraCost2 += ExtraPredCost;
Evan Cheng3ef1c872010-09-10 01:29:16 +0000677 } else if (!AlreadyPredicated) {
Evan Chengd2c5eb82007-07-06 23:24:39 +0000678 // FIXME: This instruction is already predicated before the
679 // if-conversion pass. It's probably something like a conditional move.
680 // Mark this block unpredicable for now.
681 BBI.IsUnpredicable = true;
682 return;
683 }
Evan Chengd2c5eb82007-07-06 23:24:39 +0000684 }
Evan Cheng9618bca2007-06-11 22:26:22 +0000685
686 if (BBI.ClobbersPred && !isPredicated) {
687 // Predicate modification instruction should end the block (except for
688 // already predicated instructions and end of block branches).
689 if (isCondBr) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000690 // A conditional branch is not predicable, but it may be eliminated.
Evan Cheng9618bca2007-06-11 22:26:22 +0000691 continue;
692 }
693
694 // Predicate may have been modified, the subsequent (currently)
Evan Chengd2c5eb82007-07-06 23:24:39 +0000695 // unpredicated instructions cannot be correctly predicated.
Evan Cheng9618bca2007-06-11 22:26:22 +0000696 BBI.IsUnpredicable = true;
697 return;
698 }
699
Evan Cheng11ce02d2007-07-10 17:50:43 +0000700 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
701 // still potentially predicable.
702 std::vector<MachineOperand> PredDefs;
703 if (TII->DefinesPredicate(I, PredDefs))
Evan Cheng9618bca2007-06-11 22:26:22 +0000704 BBI.ClobbersPred = true;
705
Evan Chenge54cb162009-11-21 06:20:26 +0000706 if (!TII->isPredicable(I)) {
Evan Cheng9618bca2007-06-11 22:26:22 +0000707 BBI.IsUnpredicable = true;
708 return;
709 }
710 }
711}
712
713/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
714/// predicated by the specified predicate.
715bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +0000716 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng9618bca2007-06-11 22:26:22 +0000717 bool isTriangle, bool RevBranch) {
Evan Chenge882fca2007-06-16 09:34:52 +0000718 // If the block is dead or unpredicable, then it cannot be predicated.
719 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng9618bca2007-06-11 22:26:22 +0000720 return false;
721
Evan Cheng9618bca2007-06-11 22:26:22 +0000722 // If it is already predicated, check if its predicate subsumes the new
723 // predicate.
724 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
725 return false;
726
727 if (BBI.BrCond.size()) {
728 if (!isTriangle)
729 return false;
730
Bob Wilson9c4856a2009-05-13 23:25:24 +0000731 // Test predicate subsumption.
Owen Anderson44eb65c2008-08-14 22:49:33 +0000732 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
733 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng9618bca2007-06-11 22:26:22 +0000734 if (RevBranch) {
735 if (TII->ReverseBranchCondition(Cond))
736 return false;
737 }
738 if (TII->ReverseBranchCondition(RevPred) ||
739 !TII->SubsumesPredicate(Cond, RevPred))
740 return false;
741 }
742
743 return true;
744}
745
Evan Chengac5f1422007-06-08 09:36:04 +0000746/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Chengcf6cc112007-05-18 18:14:37 +0000747/// the specified block. Record its successors and whether it looks like an
748/// if-conversion candidate.
Evan Chenge882fca2007-06-16 09:34:52 +0000749IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
750 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng4e654852007-05-16 02:00:57 +0000751 BBInfo &BBI = BBAnalysis[BB->getNumber()];
752
Evan Cheng9618bca2007-06-11 22:26:22 +0000753 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
754 return BBI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000755
Evan Cheng9618bca2007-06-11 22:26:22 +0000756 BBI.BB = BB;
757 BBI.IsBeingAnalyzed = true;
Evan Cheng9618bca2007-06-11 22:26:22 +0000758
759 ScanInstructions(BBI);
760
Jakub Staszak2b33f4c2011-07-10 02:00:16 +0000761 // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
762 // considered for ifcvt anymore.
763 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
Evan Cheng9618bca2007-06-11 22:26:22 +0000764 BBI.IsBeingAnalyzed = false;
765 BBI.IsAnalyzed = true;
766 return BBI;
Evan Cheng7a655472007-06-06 10:16:17 +0000767 }
768
Evan Cheng9618bca2007-06-11 22:26:22 +0000769 // Do not ifcvt if either path is a back edge to the entry block.
770 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
771 BBI.IsBeingAnalyzed = false;
772 BBI.IsAnalyzed = true;
773 return BBI;
774 }
775
Evan Cheng2077e182009-06-15 21:24:34 +0000776 // Do not ifcvt if true and false fallthrough blocks are the same.
777 if (!BBI.FalseBB) {
778 BBI.IsBeingAnalyzed = false;
779 BBI.IsAnalyzed = true;
780 return BBI;
781 }
782
Evan Chenge882fca2007-06-16 09:34:52 +0000783 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
784 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
Evan Cheng9618bca2007-06-11 22:26:22 +0000785
786 if (TrueBBI.IsDone && FalseBBI.IsDone) {
787 BBI.IsBeingAnalyzed = false;
788 BBI.IsAnalyzed = true;
789 return BBI;
790 }
791
Owen Anderson44eb65c2008-08-14 22:49:33 +0000792 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chengb6665f62007-06-04 06:47:22 +0000793 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
Evan Chengac5f1422007-06-08 09:36:04 +0000794
Evan Chenge882fca2007-06-16 09:34:52 +0000795 unsigned Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000796 unsigned Dups2 = 0;
Evan Cheng791e2e02012-06-08 21:53:50 +0000797 bool TNeedSub = !TrueBBI.Predicate.empty();
798 bool FNeedSub = !FalseBBI.Predicate.empty();
Evan Chenge882fca2007-06-16 09:34:52 +0000799 bool Enqueued = false;
Benjamin Kramer6406d002010-09-29 22:38:50 +0000800
Jakub Staszak990f78d2011-08-03 22:34:43 +0000801 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
802
Evan Chenga1a87872007-06-18 08:37:25 +0000803 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000804 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
Evan Cheng8239daf2010-11-03 00:45:17 +0000805 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
Bob Wilson2ad40d32010-10-26 00:02:21 +0000806 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Cheng8239daf2010-11-03 00:45:17 +0000807 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000808 Prediction) &&
Evan Chengac5f1422007-06-08 09:36:04 +0000809 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
810 FeasibilityAnalysis(FalseBBI, RevCond)) {
Evan Cheng4e654852007-05-16 02:00:57 +0000811 // Diamond:
812 // EBB
813 // / \_
814 // | |
815 // TBB FBB
816 // \ /
Evan Cheng86cbfea2007-05-18 00:20:58 +0000817 // TailBB
Evan Cheng993fc952007-06-05 23:46:14 +0000818 // Note TailBB can be empty.
Evan Chenga1a87872007-06-18 08:37:25 +0000819 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
820 Dups2));
Evan Chenge882fca2007-06-16 09:34:52 +0000821 Enqueued = true;
822 }
823
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000824 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000825 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000826 TrueBBI.ExtraCost2, Prediction) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000827 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
828 // Triangle:
829 // EBB
830 // | \_
831 // | |
832 // | TBB
833 // | /
834 // FBB
835 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
836 Enqueued = true;
837 }
Bob Wilson92fffe02010-06-15 22:18:54 +0000838
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000839 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000840 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000841 TrueBBI.ExtraCost2, Prediction) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000842 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
843 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
844 Enqueued = true;
845 }
846
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000847 if (ValidSimple(TrueBBI, Dups, Prediction) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000848 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000849 TrueBBI.ExtraCost2, Prediction) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000850 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
851 // Simple (split, no rejoin):
852 // EBB
853 // | \_
854 // | |
855 // | TBB---> exit
Bob Wilson92fffe02010-06-15 22:18:54 +0000856 // |
Evan Chenge882fca2007-06-16 09:34:52 +0000857 // FBB
858 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
859 Enqueued = true;
860 }
861
862 if (CanRevCond) {
863 // Try the other path...
Owen Andersone3cc84a2010-10-01 22:45:50 +0000864 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000865 Prediction.getCompl()) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000866 MeetIfcvtSizeLimit(*FalseBBI.BB,
867 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000868 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000869 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
870 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
871 Enqueued = true;
872 }
873
Owen Andersone3cc84a2010-10-01 22:45:50 +0000874 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000875 Prediction.getCompl()) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000876 MeetIfcvtSizeLimit(*FalseBBI.BB,
877 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000878 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000879 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
880 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
881 Enqueued = true;
882 }
883
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000884 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000885 MeetIfcvtSizeLimit(*FalseBBI.BB,
886 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000887 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000888 FeasibilityAnalysis(FalseBBI, RevCond)) {
889 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
890 Enqueued = true;
Evan Chengb6665f62007-06-04 06:47:22 +0000891 }
Evan Cheng4e654852007-05-16 02:00:57 +0000892 }
Evan Cheng4e654852007-05-16 02:00:57 +0000893
Evan Chenge882fca2007-06-16 09:34:52 +0000894 BBI.IsEnqueued = Enqueued;
Evan Cheng9618bca2007-06-11 22:26:22 +0000895 BBI.IsBeingAnalyzed = false;
896 BBI.IsAnalyzed = true;
897 return BBI;
Evan Chengcf6cc112007-05-18 18:14:37 +0000898}
899
Evan Cheng82582102007-05-30 19:49:19 +0000900/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilson6fb124b2010-06-15 18:57:15 +0000901/// candidates.
902void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Chenge882fca2007-06-16 09:34:52 +0000903 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng309db7c2011-04-27 19:32:43 +0000904 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
905 MachineBasicBlock *BB = I;
906 AnalyzeBlock(BB, Tokens);
Evan Cheng4e654852007-05-16 02:00:57 +0000907 }
Evan Cheng82582102007-05-30 19:49:19 +0000908
Evan Cheng5f702182007-06-01 00:12:12 +0000909 // Sort to favor more complex ifcvt scheme.
Evan Chenge882fca2007-06-16 09:34:52 +0000910 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Cheng4e654852007-05-16 02:00:57 +0000911}
912
Evan Cheng7e75ba82007-06-08 22:01:07 +0000913/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
914/// that all the intervening blocks are empty (given BB can fall through to its
915/// next block).
916static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Cheng46df4eb2010-06-16 07:35:02 +0000917 MachineFunction::iterator PI = BB;
918 MachineFunction::iterator I = llvm::next(PI);
Evan Chengc53ef582007-06-05 07:05:25 +0000919 MachineFunction::iterator TI = ToBB;
920 MachineFunction::iterator E = BB->getParent()->end();
Evan Cheng46df4eb2010-06-16 07:35:02 +0000921 while (I != TI) {
922 // Check isSuccessor to avoid case where the next block is empty, but
923 // it's not a successor.
924 if (I == E || !I->empty() || !PI->isSuccessor(I))
Evan Chengb6665f62007-06-04 06:47:22 +0000925 return false;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000926 PI = I++;
927 }
Evan Chengb6665f62007-06-04 06:47:22 +0000928 return true;
Evan Chenga6b4f432007-05-21 22:22:58 +0000929}
930
Evan Chenga1a87872007-06-18 08:37:25 +0000931/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
932/// to determine if it can be if-converted. If predecessor is already enqueued,
933/// dequeue it!
934void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Evan Chenga13aa952007-05-23 07:23:16 +0000935 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
936 E = BB->pred_end(); PI != E; ++PI) {
937 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
Evan Chengbc198ee2007-06-14 23:34:09 +0000938 if (PBBI.IsDone || PBBI.BB == BB)
Evan Chenge37e2432007-06-14 23:13:19 +0000939 continue;
Evan Chengbc198ee2007-06-14 23:34:09 +0000940 PBBI.IsAnalyzed = false;
941 PBBI.IsEnqueued = false;
Evan Chenga13aa952007-05-23 07:23:16 +0000942 }
943}
944
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000945/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
946///
947static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
948 const TargetInstrInfo *TII) {
Stuart Hastings3bf91252010-06-17 22:43:56 +0000949 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman1501cdb2008-08-22 16:07:55 +0000950 SmallVector<MachineOperand, 0> NoCond;
Stuart Hastings3bf91252010-06-17 22:43:56 +0000951 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000952}
953
Evan Cheng7e75ba82007-06-08 22:01:07 +0000954/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
955/// successors.
956void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
957 MachineBasicBlock *TBB = NULL, *FBB = NULL;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000958 SmallVector<MachineOperand, 4> Cond;
Evan Chengc4047a82007-06-18 22:44:57 +0000959 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
960 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng7e75ba82007-06-08 22:01:07 +0000961}
962
Evan Cheng46df4eb2010-06-16 07:35:02 +0000963/// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
964/// modeled as read + write (sort like two-address instructions). These
965/// routines track register liveness and add implicit uses to if-converted
966/// instructions to conform to the model.
967static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
968 const TargetRegisterInfo *TRI) {
969 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
970 E = BB->livein_end(); I != E; ++I) {
971 unsigned Reg = *I;
972 Redefs.insert(Reg);
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000973 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
974 Redefs.insert(*SubRegs);
Evan Cheng46df4eb2010-06-16 07:35:02 +0000975 }
976}
977
978static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
979 const TargetRegisterInfo *TRI,
980 bool AddImpUse = false) {
981 SmallVector<unsigned, 4> Defs;
982 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
983 const MachineOperand &MO = MI->getOperand(i);
984 if (!MO.isReg())
985 continue;
986 unsigned Reg = MO.getReg();
987 if (!Reg)
988 continue;
989 if (MO.isDef())
990 Defs.push_back(Reg);
991 else if (MO.isKill()) {
992 Redefs.erase(Reg);
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000993 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
994 Redefs.erase(*SubRegs);
Evan Cheng46df4eb2010-06-16 07:35:02 +0000995 }
996 }
997 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
998 unsigned Reg = Defs[i];
999 if (Redefs.count(Reg)) {
1000 if (AddImpUse)
1001 // Treat predicated update as read + write.
1002 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
Evan Cheng3d4166d2012-05-30 00:42:02 +00001003 true/*IsImp*/,false/*IsKill*/,
1004 false/*IsDead*/,true/*IsUndef*/));
Evan Cheng46df4eb2010-06-16 07:35:02 +00001005 } else {
1006 Redefs.insert(Reg);
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +00001007 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1008 Redefs.insert(*SubRegs);
Evan Cheng46df4eb2010-06-16 07:35:02 +00001009 }
1010 }
1011}
1012
1013static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1014 MachineBasicBlock::iterator E,
1015 SmallSet<unsigned,4> &Redefs,
1016 const TargetRegisterInfo *TRI) {
1017 while (I != E) {
1018 UpdatePredRedefs(I, Redefs, TRI);
1019 ++I;
1020 }
1021}
1022
Evan Chengb6665f62007-06-04 06:47:22 +00001023/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenga6b4f432007-05-21 22:22:58 +00001024///
Evan Chenge882fca2007-06-16 09:34:52 +00001025bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenga6b4f432007-05-21 22:22:58 +00001026 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1027 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1028 BBInfo *CvtBBI = &TrueBBI;
1029 BBInfo *NextBBI = &FalseBBI;
Evan Chenga13aa952007-05-23 07:23:16 +00001030
Owen Anderson44eb65c2008-08-14 22:49:33 +00001031 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chenge882fca2007-06-16 09:34:52 +00001032 if (Kind == ICSimpleFalse)
Evan Chengb5a06902007-06-01 20:29:21 +00001033 std::swap(CvtBBI, NextBBI);
Evan Chenga2acf842007-06-15 21:18:05 +00001034
Evan Chenga1a87872007-06-18 08:37:25 +00001035 if (CvtBBI->IsDone ||
1036 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Chenga2acf842007-06-15 21:18:05 +00001037 // Something has changed. It's no longer safe to predicate this block.
Evan Chenga2acf842007-06-15 21:18:05 +00001038 BBI.IsAnalyzed = false;
1039 CvtBBI->IsAnalyzed = false;
1040 return false;
Evan Chengb5a06902007-06-01 20:29:21 +00001041 }
Evan Chenga13aa952007-05-23 07:23:16 +00001042
Evan Chenge882fca2007-06-16 09:34:52 +00001043 if (Kind == ICSimpleFalse)
Dan Gohman279c22e2008-10-21 03:29:32 +00001044 if (TII->ReverseBranchCondition(Cond))
Craig Topper5e25ee82012-02-05 08:31:47 +00001045 llvm_unreachable("Unable to reverse branch condition!");
Evan Chenga2acf842007-06-15 21:18:05 +00001046
Bob Wilson54eee522010-06-19 05:33:57 +00001047 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001048 // predicated instructions.
1049 SmallSet<unsigned, 4> Redefs;
1050 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1051 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1052
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001053 if (CvtBBI->BB->pred_size() > 1) {
1054 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson9c4856a2009-05-13 23:25:24 +00001055 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001056 // the entry block.
Evan Cheng46df4eb2010-06-16 07:35:02 +00001057 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001058 } else {
Evan Cheng46df4eb2010-06-16 07:35:02 +00001059 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Evan Chenga6b4f432007-05-21 22:22:58 +00001060
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001061 // Merge converted block into entry block.
1062 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1063 MergeBlocks(BBI, *CvtBBI);
1064 }
Evan Chengd4de6d92007-06-07 02:12:15 +00001065
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001066 bool IterIfcvt = true;
Evan Cheng7e75ba82007-06-08 22:01:07 +00001067 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc8ed9ba2007-05-29 22:31:16 +00001068 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001069 BBI.HasFallThrough = false;
Evan Chengac5f1422007-06-08 09:36:04 +00001070 // Now ifcvt'd block will look like this:
1071 // BB:
1072 // ...
1073 // t, f = cmp
1074 // if t op
1075 // b BBf
1076 //
1077 // We cannot further ifcvt this block because the unconditional branch
1078 // will have to be predicated on the new condition, that will not be
1079 // available if cmp executes.
1080 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001081 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001082
Evan Cheng7e75ba82007-06-08 22:01:07 +00001083 RemoveExtraEdges(BBI);
1084
Evan Chenga13aa952007-05-23 07:23:16 +00001085 // Update block info. BB can be iteratively if-converted.
Evan Cheng9618bca2007-06-11 22:26:22 +00001086 if (!IterIfcvt)
1087 BBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001088 InvalidatePreds(BBI.BB);
Evan Cheng9618bca2007-06-11 22:26:22 +00001089 CvtBBI->IsDone = true;
Evan Chenga6b4f432007-05-21 22:22:58 +00001090
1091 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001092 return true;
1093}
1094
Evan Chengd6ddc302007-05-16 21:54:37 +00001095/// IfConvertTriangle - If convert a triangle sub-CFG.
1096///
Evan Chenge882fca2007-06-16 09:34:52 +00001097bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenga13aa952007-05-23 07:23:16 +00001098 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001099 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1100 BBInfo *CvtBBI = &TrueBBI;
1101 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings3bf91252010-06-17 22:43:56 +00001102 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001103
Owen Anderson44eb65c2008-08-14 22:49:33 +00001104 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chenge882fca2007-06-16 09:34:52 +00001105 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001106 std::swap(CvtBBI, NextBBI);
Evan Chenga2acf842007-06-15 21:18:05 +00001107
Evan Chenga1a87872007-06-18 08:37:25 +00001108 if (CvtBBI->IsDone ||
1109 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Chenga2acf842007-06-15 21:18:05 +00001110 // Something has changed. It's no longer safe to predicate this block.
Evan Chenga2acf842007-06-15 21:18:05 +00001111 BBI.IsAnalyzed = false;
1112 CvtBBI->IsAnalyzed = false;
1113 return false;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001114 }
Evan Chenga2acf842007-06-15 21:18:05 +00001115
Evan Chenge882fca2007-06-16 09:34:52 +00001116 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman279c22e2008-10-21 03:29:32 +00001117 if (TII->ReverseBranchCondition(Cond))
Craig Topper5e25ee82012-02-05 08:31:47 +00001118 llvm_unreachable("Unable to reverse branch condition!");
Evan Chenga2acf842007-06-15 21:18:05 +00001119
Evan Chenge882fca2007-06-16 09:34:52 +00001120 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman279c22e2008-10-21 03:29:32 +00001121 if (ReverseBranchCondition(*CvtBBI)) {
1122 // BB has been changed, modify its predecessors (except for this
1123 // one) so they don't get ifcvt'ed based on bad intel.
1124 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1125 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1126 MachineBasicBlock *PBB = *PI;
1127 if (PBB == BBI.BB)
1128 continue;
1129 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1130 if (PBBI.IsEnqueued) {
1131 PBBI.IsAnalyzed = false;
1132 PBBI.IsEnqueued = false;
1133 }
Evan Chengbc198ee2007-06-14 23:34:09 +00001134 }
Evan Chengcc8fb462007-06-12 23:54:05 +00001135 }
1136 }
Evan Cheng8c529382007-06-01 07:41:07 +00001137
Bob Wilson54eee522010-06-19 05:33:57 +00001138 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001139 // predicated instructions.
1140 SmallSet<unsigned, 4> Redefs;
1141 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1142 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1143
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001144 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
Bob Wilson8eab75f2010-06-29 00:55:23 +00001145 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001146 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson9c4856a2009-05-13 23:25:24 +00001147 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001148 // the entry block.
Evan Cheng46df4eb2010-06-16 07:35:02 +00001149 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001150 } else {
1151 // Predicate the 'true' block after removing its branch.
1152 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Cheng46df4eb2010-06-16 07:35:02 +00001153 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Evan Chenga6b4f432007-05-21 22:22:58 +00001154
Evan Chengc4047a82007-06-18 22:44:57 +00001155 // Now merge the entry of the triangle with the true block.
1156 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson8eab75f2010-06-29 00:55:23 +00001157 MergeBlocks(BBI, *CvtBBI, false);
Evan Chengc4047a82007-06-18 22:44:57 +00001158 }
1159
Evan Chengb6665f62007-06-04 06:47:22 +00001160 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng8ed680c2007-06-05 01:31:40 +00001161 if (HasEarlyExit) {
Owen Anderson44eb65c2008-08-14 22:49:33 +00001162 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1163 CvtBBI->BrCond.end());
Evan Cheng8c529382007-06-01 07:41:07 +00001164 if (TII->ReverseBranchCondition(RevCond))
Craig Topper5e25ee82012-02-05 08:31:47 +00001165 llvm_unreachable("Unable to reverse branch condition!");
Stuart Hastings3bf91252010-06-17 22:43:56 +00001166 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
Evan Chengc4047a82007-06-18 22:44:57 +00001167 BBI.BB->addSuccessor(CvtBBI->FalseBB);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001168 }
Evan Chengac5f1422007-06-08 09:36:04 +00001169
1170 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson9c4856a2009-05-13 23:25:24 +00001171 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Chengf5305f92007-06-05 00:07:37 +00001172 bool FalseBBDead = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001173 bool IterIfcvt = true;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001174 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengf4769612007-06-07 08:13:00 +00001175 if (!isFallThrough) {
1176 // Only merge them if the true block does not fallthrough to the false
1177 // block. By not merging them, we make it possible to iteratively
1178 // ifcvt the blocks.
Evan Chenga1a87872007-06-18 08:37:25 +00001179 if (!HasEarlyExit &&
1180 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001181 MergeBlocks(BBI, *NextBBI);
Evan Chengf4769612007-06-07 08:13:00 +00001182 FalseBBDead = true;
Evan Chengf4769612007-06-07 08:13:00 +00001183 } else {
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001184 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1185 BBI.HasFallThrough = false;
Evan Chengf4769612007-06-07 08:13:00 +00001186 }
Evan Chengac5f1422007-06-08 09:36:04 +00001187 // Mixed predicated and unpredicated code. This cannot be iteratively
1188 // predicated.
1189 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001190 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001191
Evan Cheng7e75ba82007-06-08 22:01:07 +00001192 RemoveExtraEdges(BBI);
Evan Chenga6b4f432007-05-21 22:22:58 +00001193
Evan Chenga13aa952007-05-23 07:23:16 +00001194 // Update block info. BB can be iteratively if-converted.
Bob Wilson92fffe02010-06-15 22:18:54 +00001195 if (!IterIfcvt)
Evan Cheng9618bca2007-06-11 22:26:22 +00001196 BBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001197 InvalidatePreds(BBI.BB);
Evan Cheng9618bca2007-06-11 22:26:22 +00001198 CvtBBI->IsDone = true;
Evan Chengf5305f92007-06-05 00:07:37 +00001199 if (FalseBBDead)
Evan Cheng9618bca2007-06-11 22:26:22 +00001200 NextBBI->IsDone = true;
Evan Chenga6b4f432007-05-21 22:22:58 +00001201
1202 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001203 return true;
Evan Cheng4e654852007-05-16 02:00:57 +00001204}
1205
Evan Chengd6ddc302007-05-16 21:54:37 +00001206/// IfConvertDiamond - If convert a diamond sub-CFG.
1207///
Evan Chenga1a87872007-06-18 08:37:25 +00001208bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1209 unsigned NumDups1, unsigned NumDups2) {
Evan Chengb6665f62007-06-04 06:47:22 +00001210 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Chengcf6cc112007-05-18 18:14:37 +00001211 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chenge882fca2007-06-16 09:34:52 +00001212 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson9c4856a2009-05-13 23:25:24 +00001213 // True block must fall through or end with an unanalyzable terminator.
Evan Chenge882fca2007-06-16 09:34:52 +00001214 if (!TailBB) {
Evan Chenga1a87872007-06-18 08:37:25 +00001215 if (blockAlwaysFallThrough(TrueBBI))
1216 TailBB = FalseBBI.TrueBB;
1217 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Cheng4e654852007-05-16 02:00:57 +00001218 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001219
Evan Chenga1a87872007-06-18 08:37:25 +00001220 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1221 TrueBBI.BB->pred_size() > 1 ||
1222 FalseBBI.BB->pred_size() > 1) {
1223 // Something has changed. It's no longer safe to predicate these blocks.
1224 BBI.IsAnalyzed = false;
1225 TrueBBI.IsAnalyzed = false;
1226 FalseBBI.IsAnalyzed = false;
1227 return false;
Evan Chenga6b4f432007-05-21 22:22:58 +00001228 }
Evan Chenga1a87872007-06-18 08:37:25 +00001229
Bob Wilson8eab75f2010-06-29 00:55:23 +00001230 // Put the predicated instructions from the 'true' block before the
1231 // instructions from the 'false' block, unless the true block would clobber
1232 // the predicate, in which case, do the opposite.
Evan Cheng993fc952007-06-05 23:46:14 +00001233 BBInfo *BBI1 = &TrueBBI;
1234 BBInfo *BBI2 = &FalseBBI;
Owen Anderson44eb65c2008-08-14 22:49:33 +00001235 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman279c22e2008-10-21 03:29:32 +00001236 if (TII->ReverseBranchCondition(RevCond))
Craig Topper5e25ee82012-02-05 08:31:47 +00001237 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson44eb65c2008-08-14 22:49:33 +00001238 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1239 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Chenge7052132007-06-06 00:57:55 +00001240
Evan Chenge882fca2007-06-16 09:34:52 +00001241 // Figure out the more profitable ordering.
1242 bool DoSwap = false;
1243 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1244 DoSwap = true;
1245 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Chengc4047a82007-06-18 22:44:57 +00001246 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Chenge882fca2007-06-16 09:34:52 +00001247 DoSwap = true;
Evan Chenge882fca2007-06-16 09:34:52 +00001248 }
1249 if (DoSwap) {
Evan Chenge7052132007-06-06 00:57:55 +00001250 std::swap(BBI1, BBI2);
1251 std::swap(Cond1, Cond2);
Evan Chenge7052132007-06-06 00:57:55 +00001252 }
Evan Cheng993fc952007-06-05 23:46:14 +00001253
Evan Chenga1a87872007-06-18 08:37:25 +00001254 // Remove the conditional branch from entry to the blocks.
1255 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1256
Jim Grosbach135ec502010-06-25 22:02:28 +00001257 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001258 // predicated instructions.
1259 SmallSet<unsigned, 4> Redefs;
1260 InitPredRedefs(BBI1->BB, Redefs, TRI);
1261
Evan Chenga1a87872007-06-18 08:37:25 +00001262 // Remove the duplicated instructions at the beginnings of both paths.
1263 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1264 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbachc834f412010-06-14 21:30:32 +00001265 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1266 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1267 // Skip dbg_value instructions
1268 while (DI1 != DIE1 && DI1->isDebugValue())
1269 ++DI1;
1270 while (DI2 != DIE2 && DI2->isDebugValue())
1271 ++DI2;
Evan Chenga1a87872007-06-18 08:37:25 +00001272 BBI1->NonPredSize -= NumDups1;
1273 BBI2->NonPredSize -= NumDups1;
Jim Grosbachd459f452010-06-28 20:26:00 +00001274
1275 // Skip past the dups on each side separately since there may be
1276 // differing dbg_value entries.
1277 for (unsigned i = 0; i < NumDups1; ++DI1) {
1278 if (!DI1->isDebugValue())
1279 ++i;
1280 }
Jim Grosbach9f054f02010-06-25 23:05:46 +00001281 while (NumDups1 != 0) {
Evan Chenga1a87872007-06-18 08:37:25 +00001282 ++DI2;
Jim Grosbachd459f452010-06-28 20:26:00 +00001283 if (!DI2->isDebugValue())
1284 --NumDups1;
Evan Chenga1a87872007-06-18 08:37:25 +00001285 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001286
1287 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
Evan Chenga1a87872007-06-18 08:37:25 +00001288 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1289 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1290
Evan Cheng8787c5f2011-12-19 22:01:30 +00001291 // Remove branch from 'true' block and remove duplicated instructions.
Evan Cheng993fc952007-06-05 23:46:14 +00001292 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
Evan Chenga1a87872007-06-18 08:37:25 +00001293 DI1 = BBI1->BB->end();
Jim Grosbachc834f412010-06-14 21:30:32 +00001294 for (unsigned i = 0; i != NumDups2; ) {
1295 // NumDups2 only counted non-dbg_value instructions, so this won't
1296 // run off the head of the list.
1297 assert (DI1 != BBI1->BB->begin());
Evan Chenga1a87872007-06-18 08:37:25 +00001298 --DI1;
Jim Grosbachc834f412010-06-14 21:30:32 +00001299 // skip dbg_value instructions
1300 if (!DI1->isDebugValue())
1301 ++i;
1302 }
Evan Chenga1a87872007-06-18 08:37:25 +00001303 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng993fc952007-06-05 23:46:14 +00001304
Evan Cheng8787c5f2011-12-19 22:01:30 +00001305 // Remove 'false' block branch and find the last instruction to predicate.
Evan Chenga1a87872007-06-18 08:37:25 +00001306 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1307 DI2 = BBI2->BB->end();
1308 while (NumDups2 != 0) {
Jim Grosbachc834f412010-06-14 21:30:32 +00001309 // NumDups2 only counted non-dbg_value instructions, so this won't
1310 // run off the head of the list.
1311 assert (DI2 != BBI2->BB->begin());
Evan Chenga1a87872007-06-18 08:37:25 +00001312 --DI2;
Jim Grosbachc834f412010-06-14 21:30:32 +00001313 // skip dbg_value instructions
1314 if (!DI2->isDebugValue())
1315 --NumDups2;
Evan Chenga1a87872007-06-18 08:37:25 +00001316 }
Evan Cheng8787c5f2011-12-19 22:01:30 +00001317
1318 // Remember which registers would later be defined by the false block.
1319 // This allows us not to predicate instructions in the true block that would
1320 // later be re-defined. That is, rather than
1321 // subeq r0, r1, #1
1322 // addne r0, r1, #1
1323 // generate:
1324 // sub r0, r1, #1
1325 // addne r0, r1, #1
1326 SmallSet<unsigned, 4> RedefsByFalse;
1327 SmallSet<unsigned, 4> ExtUses;
1328 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1329 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1330 if (FI->isDebugValue())
1331 continue;
1332 SmallVector<unsigned, 4> Defs;
1333 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1334 const MachineOperand &MO = FI->getOperand(i);
1335 if (!MO.isReg())
1336 continue;
1337 unsigned Reg = MO.getReg();
1338 if (!Reg)
1339 continue;
1340 if (MO.isDef()) {
1341 Defs.push_back(Reg);
1342 } else if (!RedefsByFalse.count(Reg)) {
1343 // These are defined before ctrl flow reach the 'false' instructions.
1344 // They cannot be modified by the 'true' instructions.
1345 ExtUses.insert(Reg);
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +00001346 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1347 ExtUses.insert(*SubRegs);
Evan Cheng8787c5f2011-12-19 22:01:30 +00001348 }
1349 }
1350
1351 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1352 unsigned Reg = Defs[i];
1353 if (!ExtUses.count(Reg)) {
1354 RedefsByFalse.insert(Reg);
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +00001355 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1356 RedefsByFalse.insert(*SubRegs);
Evan Cheng8787c5f2011-12-19 22:01:30 +00001357 }
1358 }
1359 }
1360 }
1361
1362 // Predicate the 'true' block.
1363 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs, &RedefsByFalse);
1364
1365 // Predicate the 'false' block.
Evan Cheng46df4eb2010-06-16 07:35:02 +00001366 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
Evan Cheng993fc952007-06-05 23:46:14 +00001367
Evan Chengc4047a82007-06-18 22:44:57 +00001368 // Merge the true block into the entry of the diamond.
Bob Wilson8eab75f2010-06-29 00:55:23 +00001369 MergeBlocks(BBI, *BBI1, TailBB == 0);
1370 MergeBlocks(BBI, *BBI2, TailBB == 0);
Evan Chenge7052132007-06-06 00:57:55 +00001371
Bob Wilson9c4856a2009-05-13 23:25:24 +00001372 // If the if-converted block falls through or unconditionally branches into
1373 // the tail block, and the tail block does not have other predecessors, then
Evan Chenga1a87872007-06-18 08:37:25 +00001374 // fold the tail block in as well. Otherwise, unless it falls through to the
1375 // tail, add a unconditional branch to it.
1376 if (TailBB) {
Pete Cooper9c58aa742011-11-04 23:49:14 +00001377 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Bob Wilson8eab75f2010-06-29 00:55:23 +00001378 bool CanMergeTail = !TailBBI.HasFallThrough;
1379 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1380 // check if there are any other predecessors besides those.
1381 unsigned NumPreds = TailBB->pred_size();
1382 if (NumPreds > 1)
1383 CanMergeTail = false;
1384 else if (NumPreds == 1 && CanMergeTail) {
1385 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1386 if (*PI != BBI1->BB && *PI != BBI2->BB)
1387 CanMergeTail = false;
1388 }
1389 if (CanMergeTail) {
Evan Chengc4047a82007-06-18 22:44:57 +00001390 MergeBlocks(BBI, TailBBI);
Evan Chenga1a87872007-06-18 08:37:25 +00001391 TailBBI.IsDone = true;
1392 } else {
Bob Wilson8eab75f2010-06-29 00:55:23 +00001393 BBI.BB->addSuccessor(TailBB);
Evan Chengc4047a82007-06-18 22:44:57 +00001394 InsertUncondBranch(BBI.BB, TailBB, TII);
1395 BBI.HasFallThrough = false;
Evan Chenga1a87872007-06-18 08:37:25 +00001396 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001397 }
1398
Bob Wilson8eab75f2010-06-29 00:55:23 +00001399 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1400 // which can happen here if TailBB is unanalyzable and is merged, so
1401 // explicitly remove BBI1 and BBI2 as successors.
1402 BBI.BB->removeSuccessor(BBI1->BB);
1403 BBI.BB->removeSuccessor(BBI2->BB);
Evan Cheng7e75ba82007-06-08 22:01:07 +00001404 RemoveExtraEdges(BBI);
1405
Evan Cheng993fc952007-06-05 23:46:14 +00001406 // Update block info.
Evan Cheng9618bca2007-06-11 22:26:22 +00001407 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001408 InvalidatePreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +00001409
1410 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001411 return true;
Evan Cheng4e654852007-05-16 02:00:57 +00001412}
1413
Evan Cheng8787c5f2011-12-19 22:01:30 +00001414static bool MaySpeculate(const MachineInstr *MI,
1415 SmallSet<unsigned, 4> &LaterRedefs,
1416 const TargetInstrInfo *TII) {
1417 bool SawStore = true;
1418 if (!MI->isSafeToMove(TII, 0, SawStore))
1419 return false;
1420
1421 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1422 const MachineOperand &MO = MI->getOperand(i);
1423 if (!MO.isReg())
1424 continue;
1425 unsigned Reg = MO.getReg();
1426 if (!Reg)
1427 continue;
1428 if (MO.isDef() && !LaterRedefs.count(Reg))
1429 return false;
1430 }
1431
1432 return true;
1433}
1434
Evan Chenga1a87872007-06-18 08:37:25 +00001435/// PredicateBlock - Predicate instructions from the start of the block to the
1436/// specified end with the specified condition.
Evan Chenga13aa952007-05-23 07:23:16 +00001437void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Chenga1a87872007-06-18 08:37:25 +00001438 MachineBasicBlock::iterator E,
Evan Cheng46df4eb2010-06-16 07:35:02 +00001439 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng8787c5f2011-12-19 22:01:30 +00001440 SmallSet<unsigned, 4> &Redefs,
1441 SmallSet<unsigned, 4> *LaterRedefs) {
1442 bool AnyUnpred = false;
1443 bool MaySpec = LaterRedefs != 0;
Evan Chenga1a87872007-06-18 08:37:25 +00001444 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbach870c8052010-06-04 23:01:26 +00001445 if (I->isDebugValue() || TII->isPredicated(I))
Evan Chenga13aa952007-05-23 07:23:16 +00001446 continue;
Evan Cheng8787c5f2011-12-19 22:01:30 +00001447 // It may be possible not to predicate an instruction if it's the 'true'
1448 // side of a diamond and the 'false' side may re-define the instruction's
1449 // defs.
1450 if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
1451 AnyUnpred = true;
1452 continue;
1453 }
1454 // If any instruction is predicated, then every instruction after it must
1455 // be predicated.
1456 MaySpec = false;
Evan Chengb6665f62007-06-04 06:47:22 +00001457 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwinf3689232009-07-12 20:07:01 +00001458#ifndef NDEBUG
David Greene083b7ff2010-01-04 22:02:01 +00001459 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwinf3689232009-07-12 20:07:01 +00001460#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001461 llvm_unreachable(0);
Evan Chengd6ddc302007-05-16 21:54:37 +00001462 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001463
Bob Wilson54eee522010-06-19 05:33:57 +00001464 // If the predicated instruction now redefines a register as the result of
Evan Cheng46df4eb2010-06-16 07:35:02 +00001465 // if-conversion, add an implicit kill.
1466 UpdatePredRedefs(I, Redefs, TRI, true);
Evan Cheng4e654852007-05-16 02:00:57 +00001467 }
Evan Chenga13aa952007-05-23 07:23:16 +00001468
Evan Cheng2acdbcc2007-06-08 19:17:12 +00001469 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1470
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001471 BBI.IsAnalyzed = false;
1472 BBI.NonPredSize = 0;
1473
Dan Gohmanfe601042010-06-22 15:08:57 +00001474 ++NumIfConvBBs;
Evan Cheng8787c5f2011-12-19 22:01:30 +00001475 if (AnyUnpred)
1476 ++NumUnpred;
Evan Chengb6665f62007-06-04 06:47:22 +00001477}
1478
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001479/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1480/// the destination block. Skip end of block branches if IgnoreBr is true.
1481void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +00001482 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng46df4eb2010-06-16 07:35:02 +00001483 SmallSet<unsigned, 4> &Redefs,
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001484 bool IgnoreBr) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001485 MachineFunction &MF = *ToBBI.BB->getParent();
1486
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001487 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1488 E = FromBBI.BB->end(); I != E; ++I) {
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001489 // Do not copy the end of the block branches.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001490 if (IgnoreBr && I->isBranch())
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001491 break;
1492
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001493 MachineInstr *MI = MF.CloneMachineInstr(I);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001494 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilson2ad40d32010-10-26 00:02:21 +00001495 ToBBI.NonPredSize++;
Evan Cheng8239daf2010-11-03 00:45:17 +00001496 unsigned ExtraPredCost = 0;
1497 unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I, &ExtraPredCost);
1498 if (NumCycles > 1)
1499 ToBBI.ExtraCost += NumCycles-1;
1500 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001501
Bob Wilsonf50e9522010-06-18 17:07:23 +00001502 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001503 if (!TII->PredicateInstruction(MI, Cond)) {
Torok Edwinf3689232009-07-12 20:07:01 +00001504#ifndef NDEBUG
David Greene083b7ff2010-01-04 22:02:01 +00001505 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwinf3689232009-07-12 20:07:01 +00001506#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001507 llvm_unreachable(0);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001508 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001509 }
1510
Bob Wilson54eee522010-06-19 05:33:57 +00001511 // If the predicated instruction now redefines a register as the result of
Evan Cheng46df4eb2010-06-16 07:35:02 +00001512 // if-conversion, add an implicit kill.
1513 UpdatePredRedefs(MI, Redefs, TRI, true);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001514 }
1515
Bob Wilson8eab75f2010-06-29 00:55:23 +00001516 if (!IgnoreBr) {
1517 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1518 FromBBI.BB->succ_end());
1519 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1520 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
Evan Chengc4047a82007-06-18 22:44:57 +00001521
Bob Wilson8eab75f2010-06-29 00:55:23 +00001522 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1523 MachineBasicBlock *Succ = Succs[i];
1524 // Fallthrough edge can't be transferred.
1525 if (Succ == FallThrough)
1526 continue;
1527 ToBBI.BB->addSuccessor(Succ);
1528 }
Evan Chengc4047a82007-06-18 22:44:57 +00001529 }
1530
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001531 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1532 std::back_inserter(ToBBI.Predicate));
1533 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1534
1535 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1536 ToBBI.IsAnalyzed = false;
1537
Dan Gohmanfe601042010-06-22 15:08:57 +00001538 ++NumDupBBs;
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001539}
1540
Evan Cheng86cbfea2007-05-18 00:20:58 +00001541/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson8eab75f2010-06-29 00:55:23 +00001542/// This will leave FromBB as an empty block, so remove all of its
1543/// successor edges except for the fall-through edge. If AddEdges is true,
1544/// i.e., when FromBBI's branch is being moved, add those successor edges to
1545/// ToBBI.
1546void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng86cbfea2007-05-18 00:20:58 +00001547 ToBBI.BB->splice(ToBBI.BB->end(),
1548 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +00001549
Evan Chengd4de6d92007-06-07 02:12:15 +00001550 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1551 FromBBI.BB->succ_end());
Evan Cheng7e75ba82007-06-08 22:01:07 +00001552 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001553 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
Evan Chengb6665f62007-06-04 06:47:22 +00001554
Evan Chengd4de6d92007-06-07 02:12:15 +00001555 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1556 MachineBasicBlock *Succ = Succs[i];
Evan Cheng7e75ba82007-06-08 22:01:07 +00001557 // Fallthrough edge can't be transferred.
Evan Chengd4de6d92007-06-07 02:12:15 +00001558 if (Succ == FallThrough)
1559 continue;
1560 FromBBI.BB->removeSuccessor(Succ);
Bob Wilson8eab75f2010-06-29 00:55:23 +00001561 if (AddEdges)
1562 ToBBI.BB->addSuccessor(Succ);
Evan Chengd4de6d92007-06-07 02:12:15 +00001563 }
1564
Bob Wilson9c4856a2009-05-13 23:25:24 +00001565 // Now FromBBI always falls through to the next block!
Bob Wilson8308e8f2009-05-13 23:48:58 +00001566 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng7e75ba82007-06-08 22:01:07 +00001567 FromBBI.BB->addSuccessor(NBB);
1568
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001569 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1570 std::back_inserter(ToBBI.Predicate));
1571 FromBBI.Predicate.clear();
1572
Evan Chenga13aa952007-05-23 07:23:16 +00001573 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilson2ad40d32010-10-26 00:02:21 +00001574 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Cheng8239daf2010-11-03 00:45:17 +00001575 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chenga13aa952007-05-23 07:23:16 +00001576 FromBBI.NonPredSize = 0;
Bob Wilson2ad40d32010-10-26 00:02:21 +00001577 FromBBI.ExtraCost = 0;
Evan Cheng8239daf2010-11-03 00:45:17 +00001578 FromBBI.ExtraCost2 = 0;
Evan Cheng7a655472007-06-06 10:16:17 +00001579
Evan Cheng9618bca2007-06-11 22:26:22 +00001580 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001581 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng86ff2962007-06-14 20:28:52 +00001582 ToBBI.IsAnalyzed = false;
1583 FromBBI.IsAnalyzed = false;
Evan Cheng4e654852007-05-16 02:00:57 +00001584}