blob: ce7ed293daacdd0cf14b774d4d1af1b83b570ad1 [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 Cheng5f702182007-06-01 00:12:12 +000016#include "llvm/Function.h"
Evan Cheng4e654852007-05-16 02:00:57 +000017#include "llvm/CodeGen/Passes.h"
18#include "llvm/CodeGen/MachineModuleInfo.h"
Jakub Staszak07672672011-08-03 22:53:41 +000019#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Cheng4e654852007-05-16 02:00:57 +000020#include "llvm/CodeGen/MachineFunctionPass.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 Cheng4e654852007-05-16 02:00:57 +000065
66namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000067 class IfConverter : public MachineFunctionPass {
Evan Chenge882fca2007-06-16 09:34:52 +000068 enum IfcvtKind {
Evan Cheng4e654852007-05-16 02:00:57 +000069 ICNotClassfied, // BB data valid, but not classified.
Evan Chengb6665f62007-06-04 06:47:22 +000070 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Chenge882fca2007-06-16 09:34:52 +000071 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
72 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Chengcc8fb462007-06-12 23:54:05 +000073 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng1c9f91d2007-06-09 01:03:43 +000074 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Chenge882fca2007-06-16 09:34:52 +000075 ICTriangle, // BB is entry of a triangle sub-CFG.
Evan Cheng9618bca2007-06-11 22:26:22 +000076 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Cheng4e654852007-05-16 02:00:57 +000077 };
78
79 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
80 /// if-conversion feasibility analysis. This includes results from
81 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng86cbfea2007-05-18 00:20:58 +000082 /// classification, and common tail block of its successors (if it's a
Evan Chengcf6cc112007-05-18 18:14:37 +000083 /// diamond shape), its size, whether it's predicable, and whether any
84 /// instruction can clobber the 'would-be' predicate.
Evan Chenga13aa952007-05-23 07:23:16 +000085 ///
Evan Cheng9618bca2007-06-11 22:26:22 +000086 /// IsDone - True if BB is not to be considered for ifcvt.
87 /// IsBeingAnalyzed - True if BB is currently being analyzed.
88 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
89 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
90 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
91 /// HasFallThrough - True if BB may fallthrough to the following BB.
92 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Cheng11ce02d2007-07-10 17:50:43 +000093 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng7a655472007-06-06 10:16:17 +000094 /// cmp, call, etc.)
Evan Cheng9618bca2007-06-11 22:26:22 +000095 /// NonPredSize - Number of non-predicated instructions.
Evan Cheng8239daf2010-11-03 00:45:17 +000096 /// ExtraCost - Extra cost for multi-cycle instructions.
97 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chenga13aa952007-05-23 07:23:16 +000098 /// BB - Corresponding MachineBasicBlock.
99 /// TrueBB / FalseBB- See AnalyzeBranch().
100 /// BrCond - Conditions for end of block conditional branches.
101 /// Predicate - Predicate used in the BB.
Evan Cheng4e654852007-05-16 02:00:57 +0000102 struct BBInfo {
Evan Cheng9618bca2007-06-11 22:26:22 +0000103 bool IsDone : 1;
104 bool IsBeingAnalyzed : 1;
105 bool IsAnalyzed : 1;
106 bool IsEnqueued : 1;
107 bool IsBrAnalyzable : 1;
108 bool HasFallThrough : 1;
109 bool IsUnpredicable : 1;
Evan Chenga2acf842007-06-15 21:18:05 +0000110 bool CannotBeCopied : 1;
Evan Cheng9618bca2007-06-11 22:26:22 +0000111 bool ClobbersPred : 1;
Evan Chenga13aa952007-05-23 07:23:16 +0000112 unsigned NonPredSize;
Bob Wilson2ad40d32010-10-26 00:02:21 +0000113 unsigned ExtraCost;
Evan Cheng8239daf2010-11-03 00:45:17 +0000114 unsigned ExtraCost2;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000115 MachineBasicBlock *BB;
116 MachineBasicBlock *TrueBB;
117 MachineBasicBlock *FalseBB;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000118 SmallVector<MachineOperand, 4> BrCond;
119 SmallVector<MachineOperand, 4> Predicate;
Evan Chenge882fca2007-06-16 09:34:52 +0000120 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng9618bca2007-06-11 22:26:22 +0000121 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
122 HasFallThrough(false), IsUnpredicable(false),
Evan Chenga2acf842007-06-15 21:18:05 +0000123 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Evan Cheng8239daf2010-11-03 00:45:17 +0000124 ExtraCost(0), ExtraCost2(0), BB(0), TrueBB(0), FalseBB(0) {}
Evan Chenge882fca2007-06-16 09:34:52 +0000125 };
126
Bob Wilson669db042010-06-15 18:19:27 +0000127 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Chenge882fca2007-06-16 09:34:52 +0000128 /// BBI - Corresponding BBInfo.
129 /// Kind - Type of block. See IfcvtKind.
Bob Wilson9c4856a2009-05-13 23:25:24 +0000130 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Chenge882fca2007-06-16 09:34:52 +0000131 /// predicated.
Evan Chenga1a87872007-06-18 08:37:25 +0000132 /// NumDups - Number of instructions that would be duplicated due
133 /// to this if-conversion. (For diamonds, the number of
134 /// identical instructions at the beginnings of both
135 /// paths).
136 /// NumDups2 - For diamonds, the number of identical instructions
137 /// at the ends of both paths.
Evan Chenge882fca2007-06-16 09:34:52 +0000138 struct IfcvtToken {
139 BBInfo &BBI;
140 IfcvtKind Kind;
Bob Wilson9c4856a2009-05-13 23:25:24 +0000141 bool NeedSubsumption;
Evan Chenga1a87872007-06-18 08:37:25 +0000142 unsigned NumDups;
143 unsigned NumDups2;
144 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson9c4856a2009-05-13 23:25:24 +0000145 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Cheng4e654852007-05-16 02:00:57 +0000146 };
147
148 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
149 /// basic block number.
150 std::vector<BBInfo> BBAnalysis;
151
Evan Cheng86cbfea2007-05-18 00:20:58 +0000152 const TargetLowering *TLI;
Evan Cheng4e654852007-05-16 02:00:57 +0000153 const TargetInstrInfo *TII;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000154 const TargetRegisterInfo *TRI;
Evan Cheng3ef1c872010-09-10 01:29:16 +0000155 const InstrItineraryData *InstrItins;
Jakub Staszak990f78d2011-08-03 22:34:43 +0000156 const MachineBranchProbabilityInfo *MBPI;
157
Evan Cheng4e654852007-05-16 02:00:57 +0000158 bool MadeChange;
Owen Anderson13bbe4b2009-06-24 23:41:44 +0000159 int FnNum;
Evan Cheng4e654852007-05-16 02:00:57 +0000160 public:
161 static char ID;
Owen Anderson081c34b2010-10-19 17:21:58 +0000162 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
163 initializeIfConverterPass(*PassRegistry::getPassRegistry());
164 }
Jakub Staszak990f78d2011-08-03 22:34:43 +0000165
Owen Anderson7571ee72010-09-28 20:42:15 +0000166 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Jakub Staszak990f78d2011-08-03 22:34:43 +0000167 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson7571ee72010-09-28 20:42:15 +0000168 MachineFunctionPass::getAnalysisUsage(AU);
169 }
Evan Cheng4e654852007-05-16 02:00:57 +0000170
171 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chengb3dd2642008-06-04 09:15:51 +0000172 virtual const char *getPassName() const { return "If Converter"; }
Evan Cheng4e654852007-05-16 02:00:57 +0000173
174 private:
Evan Chengb6665f62007-06-04 06:47:22 +0000175 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersone3cc84a2010-10-01 22:45:50 +0000176 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000177 const BranchProbability &Prediction) const;
Evan Chengac5f1422007-06-08 09:36:04 +0000178 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000179 bool FalseBranch, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000180 const BranchProbability &Prediction) const;
Evan Chenga1a87872007-06-18 08:37:25 +0000181 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
182 unsigned &Dups1, unsigned &Dups2) const;
Evan Chengac5f1422007-06-08 09:36:04 +0000183 void ScanInstructions(BBInfo &BBI);
Evan Chenge882fca2007-06-16 09:34:52 +0000184 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
185 std::vector<IfcvtToken*> &Tokens);
Owen Anderson44eb65c2008-08-14 22:49:33 +0000186 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Chengac5f1422007-06-08 09:36:04 +0000187 bool isTriangle = false, bool RevBranch = false);
Bob Wilson6fb124b2010-06-15 18:57:15 +0000188 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Evan Chenga1a87872007-06-18 08:37:25 +0000189 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng7e75ba82007-06-08 22:01:07 +0000190 void RemoveExtraEdges(BBInfo &BBI);
Evan Chenge882fca2007-06-16 09:34:52 +0000191 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
192 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Chenga1a87872007-06-18 08:37:25 +0000193 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
194 unsigned NumDups1, unsigned NumDups2);
Evan Chenga13aa952007-05-23 07:23:16 +0000195 void PredicateBlock(BBInfo &BBI,
Evan Chenga1a87872007-06-18 08:37:25 +0000196 MachineBasicBlock::iterator E,
Evan Cheng46df4eb2010-06-16 07:35:02 +0000197 SmallVectorImpl<MachineOperand> &Cond,
198 SmallSet<unsigned, 4> &Redefs);
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000199 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +0000200 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng46df4eb2010-06-16 07:35:02 +0000201 SmallSet<unsigned, 4> &Redefs,
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000202 bool IgnoreBr = false);
Bob Wilson8eab75f2010-06-29 00:55:23 +0000203 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng5f702182007-06-01 00:12:12 +0000204
Evan Cheng8239daf2010-11-03 00:45:17 +0000205 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
206 unsigned Cycle, unsigned Extra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000207 const BranchProbability &Prediction) const {
Evan Cheng8239daf2010-11-03 00:45:17 +0000208 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000209 Prediction);
Evan Cheng13151432010-06-25 22:42:03 +0000210 }
211
Evan Cheng8239daf2010-11-03 00:45:17 +0000212 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
213 unsigned TCycle, unsigned TExtra,
214 MachineBasicBlock &FBB,
215 unsigned FCycle, unsigned FExtra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000216 const BranchProbability &Prediction) const {
Evan Cheng8239daf2010-11-03 00:45:17 +0000217 return TCycle > 0 && FCycle > 0 &&
218 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000219 Prediction);
Evan Chenga1a87872007-06-18 08:37:25 +0000220 }
221
Evan Chengd4de6d92007-06-07 02:12:15 +0000222 // blockAlwaysFallThrough - Block ends without a terminator.
223 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Evan Cheng9618bca2007-06-11 22:26:22 +0000224 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
Evan Cheng7a655472007-06-06 10:16:17 +0000225 }
226
Evan Chenge882fca2007-06-16 09:34:52 +0000227 // IfcvtTokenCmp - Used to sort if-conversion candidates.
228 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
Evan Chenga1a87872007-06-18 08:37:25 +0000229 int Incr1 = (C1->Kind == ICDiamond)
230 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
231 int Incr2 = (C2->Kind == ICDiamond)
232 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
233 if (Incr1 > Incr2)
Evan Chenge882fca2007-06-16 09:34:52 +0000234 return true;
Evan Chenga1a87872007-06-18 08:37:25 +0000235 else if (Incr1 == Incr2) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000236 // Favors subsumption.
237 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
Evan Chenge882fca2007-06-16 09:34:52 +0000238 return true;
Bob Wilson9c4856a2009-05-13 23:25:24 +0000239 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Chenge882fca2007-06-16 09:34:52 +0000240 // Favors diamond over triangle, etc.
241 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
242 return true;
243 else if (C1->Kind == C2->Kind)
244 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
245 }
246 }
247 return false;
Evan Cheng5f702182007-06-01 00:12:12 +0000248 }
Evan Cheng4e654852007-05-16 02:00:57 +0000249 };
Evan Chenge882fca2007-06-16 09:34:52 +0000250
Evan Cheng4e654852007-05-16 02:00:57 +0000251 char IfConverter::ID = 0;
252}
253
Owen Anderson2ab36d32010-10-12 19:48:12 +0000254INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak990f78d2011-08-03 22:34:43 +0000255INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000256INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilsona5971032009-10-28 20:46:46 +0000257
258FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
Evan Cheng4e654852007-05-16 02:00:57 +0000259
260bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng86cbfea2007-05-18 00:20:58 +0000261 TLI = MF.getTarget().getTargetLowering();
Evan Cheng4e654852007-05-16 02:00:57 +0000262 TII = MF.getTarget().getInstrInfo();
Evan Cheng46df4eb2010-06-16 07:35:02 +0000263 TRI = MF.getTarget().getRegisterInfo();
Jakub Staszak990f78d2011-08-03 22:34:43 +0000264 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Cheng3ef1c872010-09-10 01:29:16 +0000265 InstrItins = MF.getTarget().getInstrItineraryData();
Evan Cheng4e654852007-05-16 02:00:57 +0000266 if (!TII) return false;
267
Evan Cheng86050dc2010-06-18 23:09:54 +0000268 // Tail merge tend to expose more if-conversion opportunities.
Evan Chengcbc988b2011-05-12 00:56:58 +0000269 BranchFolder BF(true, false);
Evan Cheng86050dc2010-06-18 23:09:54 +0000270 bool BFChange = BF.OptimizeFunction(MF, TII,
271 MF.getTarget().getRegisterInfo(),
272 getAnalysisIfAvailable<MachineModuleInfo>());
273
David Greene083b7ff2010-01-04 22:02:01 +0000274 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Bill Wendling44ff7942009-08-22 20:11:17 +0000275 << MF.getFunction()->getName() << "\'");
Evan Chengedf48962007-06-08 19:10:51 +0000276
277 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene083b7ff2010-01-04 22:02:01 +0000278 DEBUG(dbgs() << " skipped\n");
Evan Chengedf48962007-06-08 19:10:51 +0000279 return false;
280 }
David Greene083b7ff2010-01-04 22:02:01 +0000281 DEBUG(dbgs() << "\n");
Evan Cheng5f702182007-06-01 00:12:12 +0000282
Evan Cheng4e654852007-05-16 02:00:57 +0000283 MF.RenumberBlocks();
Evan Cheng5f702182007-06-01 00:12:12 +0000284 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Cheng4e654852007-05-16 02:00:57 +0000285
Evan Chenge882fca2007-06-16 09:34:52 +0000286 std::vector<IfcvtToken*> Tokens;
Evan Cheng47d25022007-05-18 01:55:58 +0000287 MadeChange = false;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000288 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
289 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
290 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000291 // Do an initial analysis for each basic block and find all the potential
292 // candidates to perform if-conversion.
Bob Wilson6fb124b2010-06-15 18:57:15 +0000293 bool Change = false;
294 AnalyzeBlocks(MF, Tokens);
Evan Chenge882fca2007-06-16 09:34:52 +0000295 while (!Tokens.empty()) {
296 IfcvtToken *Token = Tokens.back();
297 Tokens.pop_back();
298 BBInfo &BBI = Token->BBI;
299 IfcvtKind Kind = Token->Kind;
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000300 unsigned NumDups = Token->NumDups;
Duncan Sands20d629c2008-11-04 18:05:30 +0000301 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000302
303 delete Token;
Evan Chengb6665f62007-06-04 06:47:22 +0000304
Evan Cheng9618bca2007-06-11 22:26:22 +0000305 // If the block has been evicted out of the queue or it has already been
306 // marked dead (due to it being predicated), then skip it.
Evan Chenge882fca2007-06-16 09:34:52 +0000307 if (BBI.IsDone)
308 BBI.IsEnqueued = false;
309 if (!BBI.IsEnqueued)
Evan Cheng9618bca2007-06-11 22:26:22 +0000310 continue;
Evan Chenge882fca2007-06-16 09:34:52 +0000311
Evan Cheng86ff2962007-06-14 20:28:52 +0000312 BBI.IsEnqueued = false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000313
Evan Chengb6665f62007-06-04 06:47:22 +0000314 bool RetVal = false;
Evan Chenge882fca2007-06-16 09:34:52 +0000315 switch (Kind) {
Evan Chenga13aa952007-05-23 07:23:16 +0000316 default: assert(false && "Unexpected!");
317 break;
Evan Chengb6665f62007-06-04 06:47:22 +0000318 case ICSimple:
Evan Chengcb78d672007-06-06 01:12:44 +0000319 case ICSimpleFalse: {
Evan Chenge882fca2007-06-16 09:34:52 +0000320 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000321 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson92fffe02010-06-15 22:18:54 +0000322 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
323 " false" : "")
Bill Wendling44ff7942009-08-22 20:11:17 +0000324 << "): BB#" << BBI.BB->getNumber() << " ("
325 << ((Kind == ICSimpleFalse)
326 ? BBI.FalseBB->getNumber()
327 : BBI.TrueBB->getNumber()) << ") ");
Evan Chenge882fca2007-06-16 09:34:52 +0000328 RetVal = IfConvertSimple(BBI, Kind);
David Greene083b7ff2010-01-04 22:02:01 +0000329 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +0000330 if (RetVal) {
Dan Gohmanfe601042010-06-22 15:08:57 +0000331 if (isFalse) ++NumSimpleFalse;
332 else ++NumSimple;
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +0000333 }
Evan Chengb6665f62007-06-04 06:47:22 +0000334 break;
Evan Chengcb78d672007-06-06 01:12:44 +0000335 }
Evan Chenga13aa952007-05-23 07:23:16 +0000336 case ICTriangle:
Evan Chengcc8fb462007-06-12 23:54:05 +0000337 case ICTriangleRev:
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000338 case ICTriangleFalse:
Reid Spencera9bf49c2007-06-10 00:19:17 +0000339 case ICTriangleFRev: {
Evan Chenge882fca2007-06-16 09:34:52 +0000340 bool isFalse = Kind == ICTriangleFalse;
341 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Chengcc8fb462007-06-12 23:54:05 +0000342 if (DisableTriangle && !isFalse && !isRev) break;
343 if (DisableTriangleR && !isFalse && isRev) break;
344 if (DisableTriangleF && isFalse && !isRev) break;
345 if (DisableTriangleFR && isFalse && isRev) break;
David Greene083b7ff2010-01-04 22:02:01 +0000346 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000347 if (isFalse)
David Greene083b7ff2010-01-04 22:02:01 +0000348 DEBUG(dbgs() << " false");
Evan Chengcc8fb462007-06-12 23:54:05 +0000349 if (isRev)
David Greene083b7ff2010-01-04 22:02:01 +0000350 DEBUG(dbgs() << " rev");
351 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendling44ff7942009-08-22 20:11:17 +0000352 << BBI.TrueBB->getNumber() << ",F:"
353 << BBI.FalseBB->getNumber() << ") ");
Evan Chenge882fca2007-06-16 09:34:52 +0000354 RetVal = IfConvertTriangle(BBI, Kind);
David Greene083b7ff2010-01-04 22:02:01 +0000355 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000356 if (RetVal) {
Evan Chengcc8fb462007-06-12 23:54:05 +0000357 if (isFalse) {
Dan Gohmanfe601042010-06-22 15:08:57 +0000358 if (isRev) ++NumTriangleFRev;
359 else ++NumTriangleFalse;
Evan Chengcc8fb462007-06-12 23:54:05 +0000360 } else {
Dan Gohmanfe601042010-06-22 15:08:57 +0000361 if (isRev) ++NumTriangleRev;
362 else ++NumTriangle;
Evan Chengcc8fb462007-06-12 23:54:05 +0000363 }
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000364 }
Evan Chenga13aa952007-05-23 07:23:16 +0000365 break;
Reid Spencera9bf49c2007-06-10 00:19:17 +0000366 }
Evan Chenge882fca2007-06-16 09:34:52 +0000367 case ICDiamond: {
Evan Chengedf48962007-06-08 19:10:51 +0000368 if (DisableDiamond) break;
David Greene083b7ff2010-01-04 22:02:01 +0000369 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendling44ff7942009-08-22 20:11:17 +0000370 << BBI.TrueBB->getNumber() << ",F:"
371 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000372 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene083b7ff2010-01-04 22:02:01 +0000373 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanfe601042010-06-22 15:08:57 +0000374 if (RetVal) ++NumDiamonds;
Evan Chenga13aa952007-05-23 07:23:16 +0000375 break;
376 }
Evan Chenge882fca2007-06-16 09:34:52 +0000377 }
378
Evan Chengb6665f62007-06-04 06:47:22 +0000379 Change |= RetVal;
Evan Chengedf48962007-06-08 19:10:51 +0000380
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000381 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
382 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
383 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chengedf48962007-06-08 19:10:51 +0000384 break;
Evan Cheng4e654852007-05-16 02:00:57 +0000385 }
Evan Chenga13aa952007-05-23 07:23:16 +0000386
Evan Chenga13aa952007-05-23 07:23:16 +0000387 if (!Change)
388 break;
Evan Chengb6665f62007-06-04 06:47:22 +0000389 MadeChange |= Change;
Evan Cheng4e654852007-05-16 02:00:57 +0000390 }
Evan Cheng47d25022007-05-18 01:55:58 +0000391
Evan Chenge882fca2007-06-16 09:34:52 +0000392 // Delete tokens in case of early exit.
393 while (!Tokens.empty()) {
394 IfcvtToken *Token = Tokens.back();
395 Tokens.pop_back();
396 delete Token;
397 }
398
399 Tokens.clear();
Evan Cheng47d25022007-05-18 01:55:58 +0000400 BBAnalysis.clear();
401
Evan Cheng6a5e2832010-06-18 22:17:13 +0000402 if (MadeChange && IfCvtBranchFold) {
Evan Chengcbc988b2011-05-12 00:56:58 +0000403 BranchFolder BF(false, false);
Evan Cheng030a0a02009-09-04 07:47:40 +0000404 BF.OptimizeFunction(MF, TII,
405 MF.getTarget().getRegisterInfo(),
406 getAnalysisIfAvailable<MachineModuleInfo>());
407 }
408
Evan Cheng86050dc2010-06-18 23:09:54 +0000409 MadeChange |= BFChange;
Evan Cheng4e654852007-05-16 02:00:57 +0000410 return MadeChange;
411}
412
Evan Chenge882fca2007-06-16 09:34:52 +0000413/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
414/// its 'true' successor.
Evan Cheng4e654852007-05-16 02:00:57 +0000415static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng86cbfea2007-05-18 00:20:58 +0000416 MachineBasicBlock *TrueBB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000417 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
418 E = BB->succ_end(); SI != E; ++SI) {
419 MachineBasicBlock *SuccBB = *SI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000420 if (SuccBB != TrueBB)
Evan Cheng4e654852007-05-16 02:00:57 +0000421 return SuccBB;
422 }
423 return NULL;
424}
425
Evan Chenge882fca2007-06-16 09:34:52 +0000426/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson9c4856a2009-05-13 23:25:24 +0000427/// branch. Swap block's 'true' and 'false' successors.
Evan Chengb6665f62007-06-04 06:47:22 +0000428bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings3bf91252010-06-17 22:43:56 +0000429 DebugLoc dl; // FIXME: this is nowhere
Evan Chengb6665f62007-06-04 06:47:22 +0000430 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
431 TII->RemoveBranch(*BBI.BB);
Stuart Hastings3bf91252010-06-17 22:43:56 +0000432 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Chengb6665f62007-06-04 06:47:22 +0000433 std::swap(BBI.TrueBB, BBI.FalseBB);
434 return true;
435 }
436 return false;
437}
438
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000439/// getNextBlock - Returns the next block in the function blocks ordering. If
440/// it is the end, returns NULL.
441static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
442 MachineFunction::iterator I = BB;
443 MachineFunction::iterator E = BB->getParent()->end();
444 if (++I == E)
445 return NULL;
446 return I;
447}
448
Evan Chengac5f1422007-06-08 09:36:04 +0000449/// ValidSimple - Returns true if the 'true' block (along with its
Evan Chenge882fca2007-06-16 09:34:52 +0000450/// predecessor) forms a valid simple shape for ifcvt. It also returns the
451/// number of instructions that the ifcvt would need to duplicate if performed
452/// in Dups.
Owen Anderson7571ee72010-09-28 20:42:15 +0000453bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000454 const BranchProbability &Prediction) const {
Evan Chenge882fca2007-06-16 09:34:52 +0000455 Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000456 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000457 return false;
458
Evan Cheng9ffd3402007-06-19 21:45:13 +0000459 if (TrueBBI.IsBrAnalyzable)
460 return false;
461
Evan Chenga2acf842007-06-15 21:18:05 +0000462 if (TrueBBI.BB->pred_size() > 1) {
463 if (TrueBBI.CannotBeCopied ||
Owen Anderson7571ee72010-09-28 20:42:15 +0000464 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000465 Prediction))
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000466 return false;
Evan Chenge882fca2007-06-16 09:34:52 +0000467 Dups = TrueBBI.NonPredSize;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000468 }
469
Evan Cheng9ffd3402007-06-19 21:45:13 +0000470 return true;
Evan Cheng7a655472007-06-06 10:16:17 +0000471}
472
Evan Chengac5f1422007-06-08 09:36:04 +0000473/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000474/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Chenge882fca2007-06-16 09:34:52 +0000475/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson92fffe02010-06-15 22:18:54 +0000476/// branches to the 'false' block rather than the other way around. It also
Evan Chenge882fca2007-06-16 09:34:52 +0000477/// returns the number of instructions that the ifcvt would need to duplicate
478/// if performed in 'Dups'.
Evan Chengac5f1422007-06-08 09:36:04 +0000479bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000480 bool FalseBranch, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000481 const BranchProbability &Prediction) const {
Evan Chenge882fca2007-06-16 09:34:52 +0000482 Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000483 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000484 return false;
485
Evan Chenga2acf842007-06-15 21:18:05 +0000486 if (TrueBBI.BB->pred_size() > 1) {
487 if (TrueBBI.CannotBeCopied)
488 return false;
489
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000490 unsigned Size = TrueBBI.NonPredSize;
Evan Chenge882fca2007-06-16 09:34:52 +0000491 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman30359592008-01-29 13:02:09 +0000492 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson9c4856a2009-05-13 23:25:24 +0000493 // Ends with an unconditional branch. It will be removed.
Evan Chenge882fca2007-06-16 09:34:52 +0000494 --Size;
495 else {
496 MachineBasicBlock *FExit = FalseBranch
497 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
498 if (FExit)
499 // Require a conditional branch
500 ++Size;
501 }
502 }
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000503 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000504 return false;
Evan Chenge882fca2007-06-16 09:34:52 +0000505 Dups = Size;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000506 }
Evan Chengd4de6d92007-06-07 02:12:15 +0000507
Evan Chengac5f1422007-06-08 09:36:04 +0000508 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
509 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Evan Chengd4de6d92007-06-07 02:12:15 +0000510 MachineFunction::iterator I = TrueBBI.BB;
511 if (++I == TrueBBI.BB->getParent()->end())
512 return false;
Evan Chengac5f1422007-06-08 09:36:04 +0000513 TExit = I;
Evan Chengd4de6d92007-06-07 02:12:15 +0000514 }
Evan Chengac5f1422007-06-08 09:36:04 +0000515 return TExit && TExit == FalseBBI.BB;
Evan Chengd4de6d92007-06-07 02:12:15 +0000516}
517
Evan Chengac5f1422007-06-08 09:36:04 +0000518/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000519/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Chenga1a87872007-06-18 08:37:25 +0000520bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
521 unsigned &Dups1, unsigned &Dups2) const {
522 Dups1 = Dups2 = 0;
523 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
524 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000525 return false;
526
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000527 MachineBasicBlock *TT = TrueBBI.TrueBB;
528 MachineBasicBlock *FT = FalseBBI.TrueBB;
529
530 if (!TT && blockAlwaysFallThrough(TrueBBI))
531 TT = getNextBlock(TrueBBI.BB);
532 if (!FT && blockAlwaysFallThrough(FalseBBI))
533 FT = getNextBlock(FalseBBI.BB);
534 if (TT != FT)
535 return false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000536 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000537 return false;
Evan Chengc4047a82007-06-18 22:44:57 +0000538 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
539 return false;
540
541 // FIXME: Allow true block to have an early exit?
542 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
543 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Chenga1a87872007-06-18 08:37:25 +0000544 return false;
545
Bob Wilson7c730e72010-10-26 00:02:24 +0000546 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach66f360e2010-06-07 21:28:55 +0000547 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
548 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilson7c730e72010-10-26 00:02:24 +0000549 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
550 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
551 while (TIB != TIE && FIB != FIE) {
Evan Chenga9934dc2010-06-18 21:52:57 +0000552 // Skip dbg_value instructions. These do not count.
Bob Wilson7c730e72010-10-26 00:02:24 +0000553 if (TIB->isDebugValue()) {
554 while (TIB != TIE && TIB->isDebugValue())
555 ++TIB;
556 if (TIB == TIE)
Evan Chenga9934dc2010-06-18 21:52:57 +0000557 break;
558 }
Bob Wilson7c730e72010-10-26 00:02:24 +0000559 if (FIB->isDebugValue()) {
560 while (FIB != FIE && FIB->isDebugValue())
561 ++FIB;
562 if (FIB == FIE)
Evan Chenga9934dc2010-06-18 21:52:57 +0000563 break;
564 }
Bob Wilson7c730e72010-10-26 00:02:24 +0000565 if (!TIB->isIdenticalTo(FIB))
566 break;
567 ++Dups1;
568 ++TIB;
569 ++FIB;
570 }
571
572 // Now, in preparation for counting duplicate instructions at the ends of the
573 // blocks, move the end iterators up past any branch instructions.
574 while (TIE != TIB) {
575 --TIE;
576 if (!TIE->getDesc().isBranch())
577 break;
578 }
579 while (FIE != FIB) {
580 --FIE;
581 if (!FIE->getDesc().isBranch())
582 break;
583 }
584
585 // If Dups1 includes all of a block, then don't count duplicate
586 // instructions at the end of the blocks.
587 if (TIB == TIE || FIB == FIE)
588 return true;
589
590 // Count duplicate instructions at the ends of the blocks.
591 while (TIE != TIB && FIE != FIB) {
592 // Skip dbg_value instructions. These do not count.
593 if (TIE->isDebugValue()) {
594 while (TIE != TIB && TIE->isDebugValue())
595 --TIE;
596 if (TIE == TIB)
597 break;
598 }
599 if (FIE->isDebugValue()) {
600 while (FIE != FIB && FIE->isDebugValue())
601 --FIE;
602 if (FIE == FIB)
603 break;
604 }
605 if (!TIE->isIdenticalTo(FIE))
Evan Chenga1a87872007-06-18 08:37:25 +0000606 break;
607 ++Dups2;
Bob Wilson7c730e72010-10-26 00:02:24 +0000608 --TIE;
609 --FIE;
Evan Chenga1a87872007-06-18 08:37:25 +0000610 }
611
612 return true;
Evan Chengd4de6d92007-06-07 02:12:15 +0000613}
614
Evan Cheng9618bca2007-06-11 22:26:22 +0000615/// ScanInstructions - Scan all the instructions in the block to determine if
616/// the block is predicable. In most cases, that means all the instructions
Chris Lattner69244302008-01-07 01:56:04 +0000617/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng9618bca2007-06-11 22:26:22 +0000618/// instruction which can clobber a predicate (e.g. condition code register).
619/// If so, the block is not predicable unless it's the last instruction.
620void IfConverter::ScanInstructions(BBInfo &BBI) {
621 if (BBI.IsDone)
622 return;
623
Evan Chengd2c5eb82007-07-06 23:24:39 +0000624 bool AlreadyPredicated = BBI.Predicate.size() > 0;
Evan Cheng9618bca2007-06-11 22:26:22 +0000625 // First analyze the end of BB branches.
Evan Chengb7c908b2007-06-14 21:26:08 +0000626 BBI.TrueBB = BBI.FalseBB = NULL;
Evan Cheng9618bca2007-06-11 22:26:22 +0000627 BBI.BrCond.clear();
628 BBI.IsBrAnalyzable =
629 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
630 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
631
632 if (BBI.BrCond.size()) {
633 // No false branch. This BB must end with a conditional branch and a
634 // fallthrough.
635 if (!BBI.FalseBB)
Bob Wilson92fffe02010-06-15 22:18:54 +0000636 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Cheng2077e182009-06-15 21:24:34 +0000637 if (!BBI.FalseBB) {
638 // Malformed bcc? True and false blocks are the same?
639 BBI.IsUnpredicable = true;
640 return;
641 }
Evan Cheng9618bca2007-06-11 22:26:22 +0000642 }
643
644 // Then scan all the instructions.
645 BBI.NonPredSize = 0;
Bob Wilson2ad40d32010-10-26 00:02:21 +0000646 BBI.ExtraCost = 0;
Evan Cheng8239daf2010-11-03 00:45:17 +0000647 BBI.ExtraCost2 = 0;
Evan Cheng9618bca2007-06-11 22:26:22 +0000648 BBI.ClobbersPred = false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000649 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
650 I != E; ++I) {
Jim Grosbach870c8052010-06-04 23:01:26 +0000651 if (I->isDebugValue())
652 continue;
653
Evan Chenge837dea2011-06-28 19:10:37 +0000654 const MCInstrDesc &MCID = I->getDesc();
655 if (MCID.isNotDuplicable())
Evan Chenga2acf842007-06-15 21:18:05 +0000656 BBI.CannotBeCopied = true;
657
Evan Cheng9618bca2007-06-11 22:26:22 +0000658 bool isPredicated = TII->isPredicated(I);
Evan Chenge837dea2011-06-28 19:10:37 +0000659 bool isCondBr = BBI.IsBrAnalyzable && MCID.isConditionalBranch();
Evan Cheng9618bca2007-06-11 22:26:22 +0000660
Evan Chengd2c5eb82007-07-06 23:24:39 +0000661 if (!isCondBr) {
Evan Cheng3ef1c872010-09-10 01:29:16 +0000662 if (!isPredicated) {
Bob Wilson2ad40d32010-10-26 00:02:21 +0000663 BBI.NonPredSize++;
Evan Cheng8239daf2010-11-03 00:45:17 +0000664 unsigned ExtraPredCost = 0;
665 unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I,
666 &ExtraPredCost);
667 if (NumCycles > 1)
668 BBI.ExtraCost += NumCycles-1;
669 BBI.ExtraCost2 += ExtraPredCost;
Evan Cheng3ef1c872010-09-10 01:29:16 +0000670 } else if (!AlreadyPredicated) {
Evan Chengd2c5eb82007-07-06 23:24:39 +0000671 // FIXME: This instruction is already predicated before the
672 // if-conversion pass. It's probably something like a conditional move.
673 // Mark this block unpredicable for now.
674 BBI.IsUnpredicable = true;
675 return;
676 }
Evan Chengd2c5eb82007-07-06 23:24:39 +0000677 }
Evan Cheng9618bca2007-06-11 22:26:22 +0000678
679 if (BBI.ClobbersPred && !isPredicated) {
680 // Predicate modification instruction should end the block (except for
681 // already predicated instructions and end of block branches).
682 if (isCondBr) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000683 // A conditional branch is not predicable, but it may be eliminated.
Evan Cheng9618bca2007-06-11 22:26:22 +0000684 continue;
685 }
686
687 // Predicate may have been modified, the subsequent (currently)
Evan Chengd2c5eb82007-07-06 23:24:39 +0000688 // unpredicated instructions cannot be correctly predicated.
Evan Cheng9618bca2007-06-11 22:26:22 +0000689 BBI.IsUnpredicable = true;
690 return;
691 }
692
Evan Cheng11ce02d2007-07-10 17:50:43 +0000693 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
694 // still potentially predicable.
695 std::vector<MachineOperand> PredDefs;
696 if (TII->DefinesPredicate(I, PredDefs))
Evan Cheng9618bca2007-06-11 22:26:22 +0000697 BBI.ClobbersPred = true;
698
Evan Chenge54cb162009-11-21 06:20:26 +0000699 if (!TII->isPredicable(I)) {
Evan Cheng9618bca2007-06-11 22:26:22 +0000700 BBI.IsUnpredicable = true;
701 return;
702 }
703 }
704}
705
706/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
707/// predicated by the specified predicate.
708bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +0000709 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng9618bca2007-06-11 22:26:22 +0000710 bool isTriangle, bool RevBranch) {
Evan Chenge882fca2007-06-16 09:34:52 +0000711 // If the block is dead or unpredicable, then it cannot be predicated.
712 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng9618bca2007-06-11 22:26:22 +0000713 return false;
714
Evan Cheng9618bca2007-06-11 22:26:22 +0000715 // If it is already predicated, check if its predicate subsumes the new
716 // predicate.
717 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
718 return false;
719
720 if (BBI.BrCond.size()) {
721 if (!isTriangle)
722 return false;
723
Bob Wilson9c4856a2009-05-13 23:25:24 +0000724 // Test predicate subsumption.
Owen Anderson44eb65c2008-08-14 22:49:33 +0000725 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
726 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng9618bca2007-06-11 22:26:22 +0000727 if (RevBranch) {
728 if (TII->ReverseBranchCondition(Cond))
729 return false;
730 }
731 if (TII->ReverseBranchCondition(RevPred) ||
732 !TII->SubsumesPredicate(Cond, RevPred))
733 return false;
734 }
735
736 return true;
737}
738
Evan Chengac5f1422007-06-08 09:36:04 +0000739/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Chengcf6cc112007-05-18 18:14:37 +0000740/// the specified block. Record its successors and whether it looks like an
741/// if-conversion candidate.
Evan Chenge882fca2007-06-16 09:34:52 +0000742IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
743 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng4e654852007-05-16 02:00:57 +0000744 BBInfo &BBI = BBAnalysis[BB->getNumber()];
745
Evan Cheng9618bca2007-06-11 22:26:22 +0000746 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
747 return BBI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000748
Evan Cheng9618bca2007-06-11 22:26:22 +0000749 BBI.BB = BB;
750 BBI.IsBeingAnalyzed = true;
Evan Cheng9618bca2007-06-11 22:26:22 +0000751
752 ScanInstructions(BBI);
753
Jakub Staszak2b33f4c2011-07-10 02:00:16 +0000754 // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
755 // considered for ifcvt anymore.
756 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
Evan Cheng9618bca2007-06-11 22:26:22 +0000757 BBI.IsBeingAnalyzed = false;
758 BBI.IsAnalyzed = true;
759 return BBI;
Evan Cheng7a655472007-06-06 10:16:17 +0000760 }
761
Evan Cheng9618bca2007-06-11 22:26:22 +0000762 // Do not ifcvt if either path is a back edge to the entry block.
763 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
764 BBI.IsBeingAnalyzed = false;
765 BBI.IsAnalyzed = true;
766 return BBI;
767 }
768
Evan Cheng2077e182009-06-15 21:24:34 +0000769 // Do not ifcvt if true and false fallthrough blocks are the same.
770 if (!BBI.FalseBB) {
771 BBI.IsBeingAnalyzed = false;
772 BBI.IsAnalyzed = true;
773 return BBI;
774 }
775
Evan Chenge882fca2007-06-16 09:34:52 +0000776 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
777 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
Evan Cheng9618bca2007-06-11 22:26:22 +0000778
779 if (TrueBBI.IsDone && FalseBBI.IsDone) {
780 BBI.IsBeingAnalyzed = false;
781 BBI.IsAnalyzed = true;
782 return BBI;
783 }
784
Owen Anderson44eb65c2008-08-14 22:49:33 +0000785 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chengb6665f62007-06-04 06:47:22 +0000786 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
Evan Chengac5f1422007-06-08 09:36:04 +0000787
Evan Chenge882fca2007-06-16 09:34:52 +0000788 unsigned Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000789 unsigned Dups2 = 0;
Evan Chenge882fca2007-06-16 09:34:52 +0000790 bool TNeedSub = TrueBBI.Predicate.size() > 0;
791 bool FNeedSub = FalseBBI.Predicate.size() > 0;
792 bool Enqueued = false;
Benjamin Kramer6406d002010-09-29 22:38:50 +0000793
Jakub Staszak990f78d2011-08-03 22:34:43 +0000794 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
795
Evan Chenga1a87872007-06-18 08:37:25 +0000796 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000797 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
Evan Cheng8239daf2010-11-03 00:45:17 +0000798 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
Bob Wilson2ad40d32010-10-26 00:02:21 +0000799 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Cheng8239daf2010-11-03 00:45:17 +0000800 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000801 Prediction) &&
Evan Chengac5f1422007-06-08 09:36:04 +0000802 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
803 FeasibilityAnalysis(FalseBBI, RevCond)) {
Evan Cheng4e654852007-05-16 02:00:57 +0000804 // Diamond:
805 // EBB
806 // / \_
807 // | |
808 // TBB FBB
809 // \ /
Evan Cheng86cbfea2007-05-18 00:20:58 +0000810 // TailBB
Evan Cheng993fc952007-06-05 23:46:14 +0000811 // Note TailBB can be empty.
Evan Chenga1a87872007-06-18 08:37:25 +0000812 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
813 Dups2));
Evan Chenge882fca2007-06-16 09:34:52 +0000814 Enqueued = true;
815 }
816
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000817 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000818 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000819 TrueBBI.ExtraCost2, Prediction) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000820 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
821 // Triangle:
822 // EBB
823 // | \_
824 // | |
825 // | TBB
826 // | /
827 // FBB
828 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
829 Enqueued = true;
830 }
Bob Wilson92fffe02010-06-15 22:18:54 +0000831
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000832 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000833 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000834 TrueBBI.ExtraCost2, Prediction) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000835 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
836 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
837 Enqueued = true;
838 }
839
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000840 if (ValidSimple(TrueBBI, Dups, Prediction) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000841 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000842 TrueBBI.ExtraCost2, Prediction) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000843 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
844 // Simple (split, no rejoin):
845 // EBB
846 // | \_
847 // | |
848 // | TBB---> exit
Bob Wilson92fffe02010-06-15 22:18:54 +0000849 // |
Evan Chenge882fca2007-06-16 09:34:52 +0000850 // FBB
851 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
852 Enqueued = true;
853 }
854
855 if (CanRevCond) {
856 // Try the other path...
Owen Andersone3cc84a2010-10-01 22:45:50 +0000857 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000858 Prediction.getCompl()) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000859 MeetIfcvtSizeLimit(*FalseBBI.BB,
860 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000861 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000862 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
863 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
864 Enqueued = true;
865 }
866
Owen Andersone3cc84a2010-10-01 22:45:50 +0000867 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000868 Prediction.getCompl()) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000869 MeetIfcvtSizeLimit(*FalseBBI.BB,
870 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000871 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000872 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
873 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
874 Enqueued = true;
875 }
876
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000877 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000878 MeetIfcvtSizeLimit(*FalseBBI.BB,
879 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000880 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000881 FeasibilityAnalysis(FalseBBI, RevCond)) {
882 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
883 Enqueued = true;
Evan Chengb6665f62007-06-04 06:47:22 +0000884 }
Evan Cheng4e654852007-05-16 02:00:57 +0000885 }
Evan Cheng4e654852007-05-16 02:00:57 +0000886
Evan Chenge882fca2007-06-16 09:34:52 +0000887 BBI.IsEnqueued = Enqueued;
Evan Cheng9618bca2007-06-11 22:26:22 +0000888 BBI.IsBeingAnalyzed = false;
889 BBI.IsAnalyzed = true;
890 return BBI;
Evan Chengcf6cc112007-05-18 18:14:37 +0000891}
892
Evan Cheng82582102007-05-30 19:49:19 +0000893/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilson6fb124b2010-06-15 18:57:15 +0000894/// candidates.
895void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Chenge882fca2007-06-16 09:34:52 +0000896 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng309db7c2011-04-27 19:32:43 +0000897 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
898 MachineBasicBlock *BB = I;
899 AnalyzeBlock(BB, Tokens);
Evan Cheng4e654852007-05-16 02:00:57 +0000900 }
Evan Cheng82582102007-05-30 19:49:19 +0000901
Evan Cheng5f702182007-06-01 00:12:12 +0000902 // Sort to favor more complex ifcvt scheme.
Evan Chenge882fca2007-06-16 09:34:52 +0000903 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Cheng4e654852007-05-16 02:00:57 +0000904}
905
Evan Cheng7e75ba82007-06-08 22:01:07 +0000906/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
907/// that all the intervening blocks are empty (given BB can fall through to its
908/// next block).
909static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Cheng46df4eb2010-06-16 07:35:02 +0000910 MachineFunction::iterator PI = BB;
911 MachineFunction::iterator I = llvm::next(PI);
Evan Chengc53ef582007-06-05 07:05:25 +0000912 MachineFunction::iterator TI = ToBB;
913 MachineFunction::iterator E = BB->getParent()->end();
Evan Cheng46df4eb2010-06-16 07:35:02 +0000914 while (I != TI) {
915 // Check isSuccessor to avoid case where the next block is empty, but
916 // it's not a successor.
917 if (I == E || !I->empty() || !PI->isSuccessor(I))
Evan Chengb6665f62007-06-04 06:47:22 +0000918 return false;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000919 PI = I++;
920 }
Evan Chengb6665f62007-06-04 06:47:22 +0000921 return true;
Evan Chenga6b4f432007-05-21 22:22:58 +0000922}
923
Evan Chenga1a87872007-06-18 08:37:25 +0000924/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
925/// to determine if it can be if-converted. If predecessor is already enqueued,
926/// dequeue it!
927void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Evan Chenga13aa952007-05-23 07:23:16 +0000928 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
929 E = BB->pred_end(); PI != E; ++PI) {
930 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
Evan Chengbc198ee2007-06-14 23:34:09 +0000931 if (PBBI.IsDone || PBBI.BB == BB)
Evan Chenge37e2432007-06-14 23:13:19 +0000932 continue;
Evan Chengbc198ee2007-06-14 23:34:09 +0000933 PBBI.IsAnalyzed = false;
934 PBBI.IsEnqueued = false;
Evan Chenga13aa952007-05-23 07:23:16 +0000935 }
936}
937
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000938/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
939///
940static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
941 const TargetInstrInfo *TII) {
Stuart Hastings3bf91252010-06-17 22:43:56 +0000942 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman1501cdb2008-08-22 16:07:55 +0000943 SmallVector<MachineOperand, 0> NoCond;
Stuart Hastings3bf91252010-06-17 22:43:56 +0000944 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000945}
946
Evan Cheng7e75ba82007-06-08 22:01:07 +0000947/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
948/// successors.
949void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
950 MachineBasicBlock *TBB = NULL, *FBB = NULL;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000951 SmallVector<MachineOperand, 4> Cond;
Evan Chengc4047a82007-06-18 22:44:57 +0000952 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
953 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng7e75ba82007-06-08 22:01:07 +0000954}
955
Evan Cheng46df4eb2010-06-16 07:35:02 +0000956/// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
957/// modeled as read + write (sort like two-address instructions). These
958/// routines track register liveness and add implicit uses to if-converted
959/// instructions to conform to the model.
960static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
961 const TargetRegisterInfo *TRI) {
962 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
963 E = BB->livein_end(); I != E; ++I) {
964 unsigned Reg = *I;
965 Redefs.insert(Reg);
966 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
967 *Subreg; ++Subreg)
968 Redefs.insert(*Subreg);
969 }
970}
971
972static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
973 const TargetRegisterInfo *TRI,
974 bool AddImpUse = false) {
975 SmallVector<unsigned, 4> Defs;
976 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
977 const MachineOperand &MO = MI->getOperand(i);
978 if (!MO.isReg())
979 continue;
980 unsigned Reg = MO.getReg();
981 if (!Reg)
982 continue;
983 if (MO.isDef())
984 Defs.push_back(Reg);
985 else if (MO.isKill()) {
986 Redefs.erase(Reg);
987 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
988 Redefs.erase(*SR);
989 }
990 }
991 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
992 unsigned Reg = Defs[i];
993 if (Redefs.count(Reg)) {
994 if (AddImpUse)
995 // Treat predicated update as read + write.
996 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
Jim Grosbach135ec502010-06-25 22:02:28 +0000997 true/*IsImp*/,false/*IsKill*/));
Evan Cheng46df4eb2010-06-16 07:35:02 +0000998 } else {
999 Redefs.insert(Reg);
1000 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1001 Redefs.insert(*SR);
1002 }
1003 }
1004}
1005
1006static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1007 MachineBasicBlock::iterator E,
1008 SmallSet<unsigned,4> &Redefs,
1009 const TargetRegisterInfo *TRI) {
1010 while (I != E) {
1011 UpdatePredRedefs(I, Redefs, TRI);
1012 ++I;
1013 }
1014}
1015
Evan Chengb6665f62007-06-04 06:47:22 +00001016/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenga6b4f432007-05-21 22:22:58 +00001017///
Evan Chenge882fca2007-06-16 09:34:52 +00001018bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenga6b4f432007-05-21 22:22:58 +00001019 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1020 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1021 BBInfo *CvtBBI = &TrueBBI;
1022 BBInfo *NextBBI = &FalseBBI;
Evan Chenga13aa952007-05-23 07:23:16 +00001023
Owen Anderson44eb65c2008-08-14 22:49:33 +00001024 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chenge882fca2007-06-16 09:34:52 +00001025 if (Kind == ICSimpleFalse)
Evan Chengb5a06902007-06-01 20:29:21 +00001026 std::swap(CvtBBI, NextBBI);
Evan Chenga2acf842007-06-15 21:18:05 +00001027
Evan Chenga1a87872007-06-18 08:37:25 +00001028 if (CvtBBI->IsDone ||
1029 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Chenga2acf842007-06-15 21:18:05 +00001030 // Something has changed. It's no longer safe to predicate this block.
Evan Chenga2acf842007-06-15 21:18:05 +00001031 BBI.IsAnalyzed = false;
1032 CvtBBI->IsAnalyzed = false;
1033 return false;
Evan Chengb5a06902007-06-01 20:29:21 +00001034 }
Evan Chenga13aa952007-05-23 07:23:16 +00001035
Evan Chenge882fca2007-06-16 09:34:52 +00001036 if (Kind == ICSimpleFalse)
Dan Gohman279c22e2008-10-21 03:29:32 +00001037 if (TII->ReverseBranchCondition(Cond))
1038 assert(false && "Unable to reverse branch condition!");
Evan Chenga2acf842007-06-15 21:18:05 +00001039
Bob Wilson54eee522010-06-19 05:33:57 +00001040 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001041 // predicated instructions.
1042 SmallSet<unsigned, 4> Redefs;
1043 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1044 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1045
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001046 if (CvtBBI->BB->pred_size() > 1) {
1047 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson9c4856a2009-05-13 23:25:24 +00001048 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001049 // the entry block.
Evan Cheng46df4eb2010-06-16 07:35:02 +00001050 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001051 } else {
Evan Cheng46df4eb2010-06-16 07:35:02 +00001052 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Evan Chenga6b4f432007-05-21 22:22:58 +00001053
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001054 // Merge converted block into entry block.
1055 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1056 MergeBlocks(BBI, *CvtBBI);
1057 }
Evan Chengd4de6d92007-06-07 02:12:15 +00001058
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001059 bool IterIfcvt = true;
Evan Cheng7e75ba82007-06-08 22:01:07 +00001060 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc8ed9ba2007-05-29 22:31:16 +00001061 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001062 BBI.HasFallThrough = false;
Evan Chengac5f1422007-06-08 09:36:04 +00001063 // Now ifcvt'd block will look like this:
1064 // BB:
1065 // ...
1066 // t, f = cmp
1067 // if t op
1068 // b BBf
1069 //
1070 // We cannot further ifcvt this block because the unconditional branch
1071 // will have to be predicated on the new condition, that will not be
1072 // available if cmp executes.
1073 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001074 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001075
Evan Cheng7e75ba82007-06-08 22:01:07 +00001076 RemoveExtraEdges(BBI);
1077
Evan Chenga13aa952007-05-23 07:23:16 +00001078 // Update block info. BB can be iteratively if-converted.
Evan Cheng9618bca2007-06-11 22:26:22 +00001079 if (!IterIfcvt)
1080 BBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001081 InvalidatePreds(BBI.BB);
Evan Cheng9618bca2007-06-11 22:26:22 +00001082 CvtBBI->IsDone = true;
Evan Chenga6b4f432007-05-21 22:22:58 +00001083
1084 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001085 return true;
1086}
1087
Evan Chengd6ddc302007-05-16 21:54:37 +00001088/// IfConvertTriangle - If convert a triangle sub-CFG.
1089///
Evan Chenge882fca2007-06-16 09:34:52 +00001090bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenga13aa952007-05-23 07:23:16 +00001091 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001092 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1093 BBInfo *CvtBBI = &TrueBBI;
1094 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings3bf91252010-06-17 22:43:56 +00001095 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001096
Owen Anderson44eb65c2008-08-14 22:49:33 +00001097 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chenge882fca2007-06-16 09:34:52 +00001098 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001099 std::swap(CvtBBI, NextBBI);
Evan Chenga2acf842007-06-15 21:18:05 +00001100
Evan Chenga1a87872007-06-18 08:37:25 +00001101 if (CvtBBI->IsDone ||
1102 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Chenga2acf842007-06-15 21:18:05 +00001103 // Something has changed. It's no longer safe to predicate this block.
Evan Chenga2acf842007-06-15 21:18:05 +00001104 BBI.IsAnalyzed = false;
1105 CvtBBI->IsAnalyzed = false;
1106 return false;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001107 }
Evan Chenga2acf842007-06-15 21:18:05 +00001108
Evan Chenge882fca2007-06-16 09:34:52 +00001109 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman279c22e2008-10-21 03:29:32 +00001110 if (TII->ReverseBranchCondition(Cond))
1111 assert(false && "Unable to reverse branch condition!");
Evan Chenga2acf842007-06-15 21:18:05 +00001112
Evan Chenge882fca2007-06-16 09:34:52 +00001113 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman279c22e2008-10-21 03:29:32 +00001114 if (ReverseBranchCondition(*CvtBBI)) {
1115 // BB has been changed, modify its predecessors (except for this
1116 // one) so they don't get ifcvt'ed based on bad intel.
1117 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1118 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1119 MachineBasicBlock *PBB = *PI;
1120 if (PBB == BBI.BB)
1121 continue;
1122 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1123 if (PBBI.IsEnqueued) {
1124 PBBI.IsAnalyzed = false;
1125 PBBI.IsEnqueued = false;
1126 }
Evan Chengbc198ee2007-06-14 23:34:09 +00001127 }
Evan Chengcc8fb462007-06-12 23:54:05 +00001128 }
1129 }
Evan Cheng8c529382007-06-01 07:41:07 +00001130
Bob Wilson54eee522010-06-19 05:33:57 +00001131 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001132 // predicated instructions.
1133 SmallSet<unsigned, 4> Redefs;
1134 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1135 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1136
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001137 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
Bob Wilson8eab75f2010-06-29 00:55:23 +00001138 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001139 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson9c4856a2009-05-13 23:25:24 +00001140 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001141 // the entry block.
Evan Cheng46df4eb2010-06-16 07:35:02 +00001142 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001143 } else {
1144 // Predicate the 'true' block after removing its branch.
1145 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Cheng46df4eb2010-06-16 07:35:02 +00001146 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Evan Chenga6b4f432007-05-21 22:22:58 +00001147
Evan Chengc4047a82007-06-18 22:44:57 +00001148 // Now merge the entry of the triangle with the true block.
1149 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson8eab75f2010-06-29 00:55:23 +00001150 MergeBlocks(BBI, *CvtBBI, false);
Evan Chengc4047a82007-06-18 22:44:57 +00001151 }
1152
Evan Chengb6665f62007-06-04 06:47:22 +00001153 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng8ed680c2007-06-05 01:31:40 +00001154 if (HasEarlyExit) {
Owen Anderson44eb65c2008-08-14 22:49:33 +00001155 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1156 CvtBBI->BrCond.end());
Evan Cheng8c529382007-06-01 07:41:07 +00001157 if (TII->ReverseBranchCondition(RevCond))
1158 assert(false && "Unable to reverse branch condition!");
Stuart Hastings3bf91252010-06-17 22:43:56 +00001159 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
Evan Chengc4047a82007-06-18 22:44:57 +00001160 BBI.BB->addSuccessor(CvtBBI->FalseBB);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001161 }
Evan Chengac5f1422007-06-08 09:36:04 +00001162
1163 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson9c4856a2009-05-13 23:25:24 +00001164 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Chengf5305f92007-06-05 00:07:37 +00001165 bool FalseBBDead = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001166 bool IterIfcvt = true;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001167 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengf4769612007-06-07 08:13:00 +00001168 if (!isFallThrough) {
1169 // Only merge them if the true block does not fallthrough to the false
1170 // block. By not merging them, we make it possible to iteratively
1171 // ifcvt the blocks.
Evan Chenga1a87872007-06-18 08:37:25 +00001172 if (!HasEarlyExit &&
1173 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001174 MergeBlocks(BBI, *NextBBI);
Evan Chengf4769612007-06-07 08:13:00 +00001175 FalseBBDead = true;
Evan Chengf4769612007-06-07 08:13:00 +00001176 } else {
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001177 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1178 BBI.HasFallThrough = false;
Evan Chengf4769612007-06-07 08:13:00 +00001179 }
Evan Chengac5f1422007-06-08 09:36:04 +00001180 // Mixed predicated and unpredicated code. This cannot be iteratively
1181 // predicated.
1182 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001183 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001184
Evan Cheng7e75ba82007-06-08 22:01:07 +00001185 RemoveExtraEdges(BBI);
Evan Chenga6b4f432007-05-21 22:22:58 +00001186
Evan Chenga13aa952007-05-23 07:23:16 +00001187 // Update block info. BB can be iteratively if-converted.
Bob Wilson92fffe02010-06-15 22:18:54 +00001188 if (!IterIfcvt)
Evan Cheng9618bca2007-06-11 22:26:22 +00001189 BBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001190 InvalidatePreds(BBI.BB);
Evan Cheng9618bca2007-06-11 22:26:22 +00001191 CvtBBI->IsDone = true;
Evan Chengf5305f92007-06-05 00:07:37 +00001192 if (FalseBBDead)
Evan Cheng9618bca2007-06-11 22:26:22 +00001193 NextBBI->IsDone = true;
Evan Chenga6b4f432007-05-21 22:22:58 +00001194
1195 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001196 return true;
Evan Cheng4e654852007-05-16 02:00:57 +00001197}
1198
Evan Chengd6ddc302007-05-16 21:54:37 +00001199/// IfConvertDiamond - If convert a diamond sub-CFG.
1200///
Evan Chenga1a87872007-06-18 08:37:25 +00001201bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1202 unsigned NumDups1, unsigned NumDups2) {
Evan Chengb6665f62007-06-04 06:47:22 +00001203 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Chengcf6cc112007-05-18 18:14:37 +00001204 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chenge882fca2007-06-16 09:34:52 +00001205 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson9c4856a2009-05-13 23:25:24 +00001206 // True block must fall through or end with an unanalyzable terminator.
Evan Chenge882fca2007-06-16 09:34:52 +00001207 if (!TailBB) {
Evan Chenga1a87872007-06-18 08:37:25 +00001208 if (blockAlwaysFallThrough(TrueBBI))
1209 TailBB = FalseBBI.TrueBB;
1210 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Cheng4e654852007-05-16 02:00:57 +00001211 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001212
Evan Chenga1a87872007-06-18 08:37:25 +00001213 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1214 TrueBBI.BB->pred_size() > 1 ||
1215 FalseBBI.BB->pred_size() > 1) {
1216 // Something has changed. It's no longer safe to predicate these blocks.
1217 BBI.IsAnalyzed = false;
1218 TrueBBI.IsAnalyzed = false;
1219 FalseBBI.IsAnalyzed = false;
1220 return false;
Evan Chenga6b4f432007-05-21 22:22:58 +00001221 }
Evan Chenga1a87872007-06-18 08:37:25 +00001222
Bob Wilson8eab75f2010-06-29 00:55:23 +00001223 // Put the predicated instructions from the 'true' block before the
1224 // instructions from the 'false' block, unless the true block would clobber
1225 // the predicate, in which case, do the opposite.
Evan Cheng993fc952007-06-05 23:46:14 +00001226 BBInfo *BBI1 = &TrueBBI;
1227 BBInfo *BBI2 = &FalseBBI;
Owen Anderson44eb65c2008-08-14 22:49:33 +00001228 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman279c22e2008-10-21 03:29:32 +00001229 if (TII->ReverseBranchCondition(RevCond))
1230 assert(false && "Unable to reverse branch condition!");
Owen Anderson44eb65c2008-08-14 22:49:33 +00001231 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1232 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Chenge7052132007-06-06 00:57:55 +00001233
Evan Chenge882fca2007-06-16 09:34:52 +00001234 // Figure out the more profitable ordering.
1235 bool DoSwap = false;
1236 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1237 DoSwap = true;
1238 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Chengc4047a82007-06-18 22:44:57 +00001239 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Chenge882fca2007-06-16 09:34:52 +00001240 DoSwap = true;
Evan Chenge882fca2007-06-16 09:34:52 +00001241 }
1242 if (DoSwap) {
Evan Chenge7052132007-06-06 00:57:55 +00001243 std::swap(BBI1, BBI2);
1244 std::swap(Cond1, Cond2);
Evan Chenge7052132007-06-06 00:57:55 +00001245 }
Evan Cheng993fc952007-06-05 23:46:14 +00001246
Evan Chenga1a87872007-06-18 08:37:25 +00001247 // Remove the conditional branch from entry to the blocks.
1248 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1249
Jim Grosbach135ec502010-06-25 22:02:28 +00001250 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001251 // predicated instructions.
1252 SmallSet<unsigned, 4> Redefs;
1253 InitPredRedefs(BBI1->BB, Redefs, TRI);
1254
Evan Chenga1a87872007-06-18 08:37:25 +00001255 // Remove the duplicated instructions at the beginnings of both paths.
1256 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1257 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbachc834f412010-06-14 21:30:32 +00001258 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1259 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1260 // Skip dbg_value instructions
1261 while (DI1 != DIE1 && DI1->isDebugValue())
1262 ++DI1;
1263 while (DI2 != DIE2 && DI2->isDebugValue())
1264 ++DI2;
Evan Chenga1a87872007-06-18 08:37:25 +00001265 BBI1->NonPredSize -= NumDups1;
1266 BBI2->NonPredSize -= NumDups1;
Jim Grosbachd459f452010-06-28 20:26:00 +00001267
1268 // Skip past the dups on each side separately since there may be
1269 // differing dbg_value entries.
1270 for (unsigned i = 0; i < NumDups1; ++DI1) {
1271 if (!DI1->isDebugValue())
1272 ++i;
1273 }
Jim Grosbach9f054f02010-06-25 23:05:46 +00001274 while (NumDups1 != 0) {
Evan Chenga1a87872007-06-18 08:37:25 +00001275 ++DI2;
Jim Grosbachd459f452010-06-28 20:26:00 +00001276 if (!DI2->isDebugValue())
1277 --NumDups1;
Evan Chenga1a87872007-06-18 08:37:25 +00001278 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001279
1280 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
Evan Chenga1a87872007-06-18 08:37:25 +00001281 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1282 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1283
Evan Cheng993fc952007-06-05 23:46:14 +00001284 // Predicate the 'true' block after removing its branch.
1285 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
Evan Chenga1a87872007-06-18 08:37:25 +00001286 DI1 = BBI1->BB->end();
Jim Grosbachc834f412010-06-14 21:30:32 +00001287 for (unsigned i = 0; i != NumDups2; ) {
1288 // NumDups2 only counted non-dbg_value instructions, so this won't
1289 // run off the head of the list.
1290 assert (DI1 != BBI1->BB->begin());
Evan Chenga1a87872007-06-18 08:37:25 +00001291 --DI1;
Jim Grosbachc834f412010-06-14 21:30:32 +00001292 // skip dbg_value instructions
1293 if (!DI1->isDebugValue())
1294 ++i;
1295 }
Evan Chenga1a87872007-06-18 08:37:25 +00001296 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng46df4eb2010-06-16 07:35:02 +00001297 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
Evan Cheng993fc952007-06-05 23:46:14 +00001298
Evan Cheng993fc952007-06-05 23:46:14 +00001299 // Predicate the 'false' block.
Evan Chenga1a87872007-06-18 08:37:25 +00001300 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1301 DI2 = BBI2->BB->end();
1302 while (NumDups2 != 0) {
Jim Grosbachc834f412010-06-14 21:30:32 +00001303 // NumDups2 only counted non-dbg_value instructions, so this won't
1304 // run off the head of the list.
1305 assert (DI2 != BBI2->BB->begin());
Evan Chenga1a87872007-06-18 08:37:25 +00001306 --DI2;
Jim Grosbachc834f412010-06-14 21:30:32 +00001307 // skip dbg_value instructions
1308 if (!DI2->isDebugValue())
1309 --NumDups2;
Evan Chenga1a87872007-06-18 08:37:25 +00001310 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001311 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
Evan Cheng993fc952007-06-05 23:46:14 +00001312
Evan Chengc4047a82007-06-18 22:44:57 +00001313 // Merge the true block into the entry of the diamond.
Bob Wilson8eab75f2010-06-29 00:55:23 +00001314 MergeBlocks(BBI, *BBI1, TailBB == 0);
1315 MergeBlocks(BBI, *BBI2, TailBB == 0);
Evan Chenge7052132007-06-06 00:57:55 +00001316
Bob Wilson9c4856a2009-05-13 23:25:24 +00001317 // If the if-converted block falls through or unconditionally branches into
1318 // the tail block, and the tail block does not have other predecessors, then
Evan Chenga1a87872007-06-18 08:37:25 +00001319 // fold the tail block in as well. Otherwise, unless it falls through to the
1320 // tail, add a unconditional branch to it.
1321 if (TailBB) {
Evan Chenge882fca2007-06-16 09:34:52 +00001322 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
Bob Wilson8eab75f2010-06-29 00:55:23 +00001323 bool CanMergeTail = !TailBBI.HasFallThrough;
1324 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1325 // check if there are any other predecessors besides those.
1326 unsigned NumPreds = TailBB->pred_size();
1327 if (NumPreds > 1)
1328 CanMergeTail = false;
1329 else if (NumPreds == 1 && CanMergeTail) {
1330 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1331 if (*PI != BBI1->BB && *PI != BBI2->BB)
1332 CanMergeTail = false;
1333 }
1334 if (CanMergeTail) {
Evan Chengc4047a82007-06-18 22:44:57 +00001335 MergeBlocks(BBI, TailBBI);
Evan Chenga1a87872007-06-18 08:37:25 +00001336 TailBBI.IsDone = true;
1337 } else {
Bob Wilson8eab75f2010-06-29 00:55:23 +00001338 BBI.BB->addSuccessor(TailBB);
Evan Chengc4047a82007-06-18 22:44:57 +00001339 InsertUncondBranch(BBI.BB, TailBB, TII);
1340 BBI.HasFallThrough = false;
Evan Chenga1a87872007-06-18 08:37:25 +00001341 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001342 }
1343
Bob Wilson8eab75f2010-06-29 00:55:23 +00001344 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1345 // which can happen here if TailBB is unanalyzable and is merged, so
1346 // explicitly remove BBI1 and BBI2 as successors.
1347 BBI.BB->removeSuccessor(BBI1->BB);
1348 BBI.BB->removeSuccessor(BBI2->BB);
Evan Cheng7e75ba82007-06-08 22:01:07 +00001349 RemoveExtraEdges(BBI);
1350
Evan Cheng993fc952007-06-05 23:46:14 +00001351 // Update block info.
Evan Cheng9618bca2007-06-11 22:26:22 +00001352 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001353 InvalidatePreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +00001354
1355 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001356 return true;
Evan Cheng4e654852007-05-16 02:00:57 +00001357}
1358
Evan Chenga1a87872007-06-18 08:37:25 +00001359/// PredicateBlock - Predicate instructions from the start of the block to the
1360/// specified end with the specified condition.
Evan Chenga13aa952007-05-23 07:23:16 +00001361void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Chenga1a87872007-06-18 08:37:25 +00001362 MachineBasicBlock::iterator E,
Evan Cheng46df4eb2010-06-16 07:35:02 +00001363 SmallVectorImpl<MachineOperand> &Cond,
1364 SmallSet<unsigned, 4> &Redefs) {
Evan Chenga1a87872007-06-18 08:37:25 +00001365 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbach870c8052010-06-04 23:01:26 +00001366 if (I->isDebugValue() || TII->isPredicated(I))
Evan Chenga13aa952007-05-23 07:23:16 +00001367 continue;
Evan Chengb6665f62007-06-04 06:47:22 +00001368 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwinf3689232009-07-12 20:07:01 +00001369#ifndef NDEBUG
David Greene083b7ff2010-01-04 22:02:01 +00001370 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwinf3689232009-07-12 20:07:01 +00001371#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001372 llvm_unreachable(0);
Evan Chengd6ddc302007-05-16 21:54:37 +00001373 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001374
Bob Wilson54eee522010-06-19 05:33:57 +00001375 // If the predicated instruction now redefines a register as the result of
Evan Cheng46df4eb2010-06-16 07:35:02 +00001376 // if-conversion, add an implicit kill.
1377 UpdatePredRedefs(I, Redefs, TRI, true);
Evan Cheng4e654852007-05-16 02:00:57 +00001378 }
Evan Chenga13aa952007-05-23 07:23:16 +00001379
Evan Cheng2acdbcc2007-06-08 19:17:12 +00001380 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1381
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001382 BBI.IsAnalyzed = false;
1383 BBI.NonPredSize = 0;
1384
Dan Gohmanfe601042010-06-22 15:08:57 +00001385 ++NumIfConvBBs;
Evan Chengb6665f62007-06-04 06:47:22 +00001386}
1387
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001388/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1389/// the destination block. Skip end of block branches if IgnoreBr is true.
1390void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +00001391 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng46df4eb2010-06-16 07:35:02 +00001392 SmallSet<unsigned, 4> &Redefs,
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001393 bool IgnoreBr) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001394 MachineFunction &MF = *ToBBI.BB->getParent();
1395
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001396 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1397 E = FromBBI.BB->end(); I != E; ++I) {
Evan Chenge837dea2011-06-28 19:10:37 +00001398 const MCInstrDesc &MCID = I->getDesc();
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001399 // Do not copy the end of the block branches.
Evan Chenge837dea2011-06-28 19:10:37 +00001400 if (IgnoreBr && MCID.isBranch())
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001401 break;
1402
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001403 MachineInstr *MI = MF.CloneMachineInstr(I);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001404 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilson2ad40d32010-10-26 00:02:21 +00001405 ToBBI.NonPredSize++;
Evan Cheng8239daf2010-11-03 00:45:17 +00001406 unsigned ExtraPredCost = 0;
1407 unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I, &ExtraPredCost);
1408 if (NumCycles > 1)
1409 ToBBI.ExtraCost += NumCycles-1;
1410 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001411
Bob Wilsonf50e9522010-06-18 17:07:23 +00001412 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001413 if (!TII->PredicateInstruction(MI, Cond)) {
Torok Edwinf3689232009-07-12 20:07:01 +00001414#ifndef NDEBUG
David Greene083b7ff2010-01-04 22:02:01 +00001415 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwinf3689232009-07-12 20:07:01 +00001416#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001417 llvm_unreachable(0);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001418 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001419 }
1420
Bob Wilson54eee522010-06-19 05:33:57 +00001421 // If the predicated instruction now redefines a register as the result of
Evan Cheng46df4eb2010-06-16 07:35:02 +00001422 // if-conversion, add an implicit kill.
1423 UpdatePredRedefs(MI, Redefs, TRI, true);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001424 }
1425
Bob Wilson8eab75f2010-06-29 00:55:23 +00001426 if (!IgnoreBr) {
1427 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1428 FromBBI.BB->succ_end());
1429 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1430 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
Evan Chengc4047a82007-06-18 22:44:57 +00001431
Bob Wilson8eab75f2010-06-29 00:55:23 +00001432 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1433 MachineBasicBlock *Succ = Succs[i];
1434 // Fallthrough edge can't be transferred.
1435 if (Succ == FallThrough)
1436 continue;
1437 ToBBI.BB->addSuccessor(Succ);
1438 }
Evan Chengc4047a82007-06-18 22:44:57 +00001439 }
1440
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001441 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1442 std::back_inserter(ToBBI.Predicate));
1443 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1444
1445 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1446 ToBBI.IsAnalyzed = false;
1447
Dan Gohmanfe601042010-06-22 15:08:57 +00001448 ++NumDupBBs;
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001449}
1450
Evan Cheng86cbfea2007-05-18 00:20:58 +00001451/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson8eab75f2010-06-29 00:55:23 +00001452/// This will leave FromBB as an empty block, so remove all of its
1453/// successor edges except for the fall-through edge. If AddEdges is true,
1454/// i.e., when FromBBI's branch is being moved, add those successor edges to
1455/// ToBBI.
1456void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng86cbfea2007-05-18 00:20:58 +00001457 ToBBI.BB->splice(ToBBI.BB->end(),
1458 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +00001459
Evan Chengd4de6d92007-06-07 02:12:15 +00001460 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1461 FromBBI.BB->succ_end());
Evan Cheng7e75ba82007-06-08 22:01:07 +00001462 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001463 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
Evan Chengb6665f62007-06-04 06:47:22 +00001464
Evan Chengd4de6d92007-06-07 02:12:15 +00001465 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1466 MachineBasicBlock *Succ = Succs[i];
Evan Cheng7e75ba82007-06-08 22:01:07 +00001467 // Fallthrough edge can't be transferred.
Evan Chengd4de6d92007-06-07 02:12:15 +00001468 if (Succ == FallThrough)
1469 continue;
1470 FromBBI.BB->removeSuccessor(Succ);
Bob Wilson8eab75f2010-06-29 00:55:23 +00001471 if (AddEdges)
1472 ToBBI.BB->addSuccessor(Succ);
Evan Chengd4de6d92007-06-07 02:12:15 +00001473 }
1474
Bob Wilson9c4856a2009-05-13 23:25:24 +00001475 // Now FromBBI always falls through to the next block!
Bob Wilson8308e8f2009-05-13 23:48:58 +00001476 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng7e75ba82007-06-08 22:01:07 +00001477 FromBBI.BB->addSuccessor(NBB);
1478
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001479 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1480 std::back_inserter(ToBBI.Predicate));
1481 FromBBI.Predicate.clear();
1482
Evan Chenga13aa952007-05-23 07:23:16 +00001483 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilson2ad40d32010-10-26 00:02:21 +00001484 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Cheng8239daf2010-11-03 00:45:17 +00001485 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chenga13aa952007-05-23 07:23:16 +00001486 FromBBI.NonPredSize = 0;
Bob Wilson2ad40d32010-10-26 00:02:21 +00001487 FromBBI.ExtraCost = 0;
Evan Cheng8239daf2010-11-03 00:45:17 +00001488 FromBBI.ExtraCost2 = 0;
Evan Cheng7a655472007-06-06 10:16:17 +00001489
Evan Cheng9618bca2007-06-11 22:26:22 +00001490 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001491 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng86ff2962007-06-14 20:28:52 +00001492 ToBBI.IsAnalyzed = false;
1493 FromBBI.IsAnalyzed = false;
Evan Cheng4e654852007-05-16 02:00:57 +00001494}