blob: 5c2a73b75aa0918e5a0a30771dd873a698feef94 [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 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;
158
Evan Cheng4e654852007-05-16 02:00:57 +0000159 bool MadeChange;
Owen Anderson13bbe4b2009-06-24 23:41:44 +0000160 int FnNum;
Evan Cheng4e654852007-05-16 02:00:57 +0000161 public:
162 static char ID;
Owen Anderson081c34b2010-10-19 17:21:58 +0000163 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
164 initializeIfConverterPass(*PassRegistry::getPassRegistry());
165 }
Jakub Staszak990f78d2011-08-03 22:34:43 +0000166
Owen Anderson7571ee72010-09-28 20:42:15 +0000167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Jakub Staszak990f78d2011-08-03 22:34:43 +0000168 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson7571ee72010-09-28 20:42:15 +0000169 MachineFunctionPass::getAnalysisUsage(AU);
170 }
Evan Cheng4e654852007-05-16 02:00:57 +0000171
172 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chengb3dd2642008-06-04 09:15:51 +0000173 virtual const char *getPassName() const { return "If Converter"; }
Evan Cheng4e654852007-05-16 02:00:57 +0000174
175 private:
Evan Chengb6665f62007-06-04 06:47:22 +0000176 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersone3cc84a2010-10-01 22:45:50 +0000177 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000178 const BranchProbability &Prediction) const;
Evan Chengac5f1422007-06-08 09:36:04 +0000179 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000180 bool FalseBranch, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000181 const BranchProbability &Prediction) const;
Evan Chenga1a87872007-06-18 08:37:25 +0000182 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
183 unsigned &Dups1, unsigned &Dups2) const;
Evan Chengac5f1422007-06-08 09:36:04 +0000184 void ScanInstructions(BBInfo &BBI);
Evan Chenge882fca2007-06-16 09:34:52 +0000185 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
186 std::vector<IfcvtToken*> &Tokens);
Owen Anderson44eb65c2008-08-14 22:49:33 +0000187 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Chengac5f1422007-06-08 09:36:04 +0000188 bool isTriangle = false, bool RevBranch = false);
Bob Wilson6fb124b2010-06-15 18:57:15 +0000189 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Evan Chenga1a87872007-06-18 08:37:25 +0000190 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng7e75ba82007-06-08 22:01:07 +0000191 void RemoveExtraEdges(BBInfo &BBI);
Evan Chenge882fca2007-06-16 09:34:52 +0000192 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
193 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Chenga1a87872007-06-18 08:37:25 +0000194 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
195 unsigned NumDups1, unsigned NumDups2);
Evan Chenga13aa952007-05-23 07:23:16 +0000196 void PredicateBlock(BBInfo &BBI,
Evan Chenga1a87872007-06-18 08:37:25 +0000197 MachineBasicBlock::iterator E,
Evan Cheng46df4eb2010-06-16 07:35:02 +0000198 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng8787c5f2011-12-19 22:01:30 +0000199 SmallSet<unsigned, 4> &Redefs,
200 SmallSet<unsigned, 4> *LaterRedefs = 0);
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000201 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +0000202 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng46df4eb2010-06-16 07:35:02 +0000203 SmallSet<unsigned, 4> &Redefs,
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000204 bool IgnoreBr = false);
Bob Wilson8eab75f2010-06-29 00:55:23 +0000205 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng5f702182007-06-01 00:12:12 +0000206
Evan Cheng8239daf2010-11-03 00:45:17 +0000207 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
208 unsigned Cycle, unsigned Extra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000209 const BranchProbability &Prediction) const {
Evan Cheng8239daf2010-11-03 00:45:17 +0000210 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000211 Prediction);
Evan Cheng13151432010-06-25 22:42:03 +0000212 }
213
Evan Cheng8239daf2010-11-03 00:45:17 +0000214 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
215 unsigned TCycle, unsigned TExtra,
216 MachineBasicBlock &FBB,
217 unsigned FCycle, unsigned FExtra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000218 const BranchProbability &Prediction) const {
Evan Cheng8239daf2010-11-03 00:45:17 +0000219 return TCycle > 0 && FCycle > 0 &&
220 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000221 Prediction);
Evan Chenga1a87872007-06-18 08:37:25 +0000222 }
223
Evan Chengd4de6d92007-06-07 02:12:15 +0000224 // blockAlwaysFallThrough - Block ends without a terminator.
225 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Evan Cheng9618bca2007-06-11 22:26:22 +0000226 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
Evan Cheng7a655472007-06-06 10:16:17 +0000227 }
228
Evan Chenge882fca2007-06-16 09:34:52 +0000229 // IfcvtTokenCmp - Used to sort if-conversion candidates.
230 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
Evan Chenga1a87872007-06-18 08:37:25 +0000231 int Incr1 = (C1->Kind == ICDiamond)
232 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
233 int Incr2 = (C2->Kind == ICDiamond)
234 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
235 if (Incr1 > Incr2)
Evan Chenge882fca2007-06-16 09:34:52 +0000236 return true;
Evan Chenga1a87872007-06-18 08:37:25 +0000237 else if (Incr1 == Incr2) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000238 // Favors subsumption.
239 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
Evan Chenge882fca2007-06-16 09:34:52 +0000240 return true;
Bob Wilson9c4856a2009-05-13 23:25:24 +0000241 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Chenge882fca2007-06-16 09:34:52 +0000242 // Favors diamond over triangle, etc.
243 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
244 return true;
245 else if (C1->Kind == C2->Kind)
246 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
247 }
248 }
249 return false;
Evan Cheng5f702182007-06-01 00:12:12 +0000250 }
Evan Cheng4e654852007-05-16 02:00:57 +0000251 };
Evan Chenge882fca2007-06-16 09:34:52 +0000252
Evan Cheng4e654852007-05-16 02:00:57 +0000253 char IfConverter::ID = 0;
254}
255
Owen Anderson2ab36d32010-10-12 19:48:12 +0000256INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak990f78d2011-08-03 22:34:43 +0000257INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000258INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilsona5971032009-10-28 20:46:46 +0000259
260FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
Evan Cheng4e654852007-05-16 02:00:57 +0000261
262bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng86cbfea2007-05-18 00:20:58 +0000263 TLI = MF.getTarget().getTargetLowering();
Evan Cheng4e654852007-05-16 02:00:57 +0000264 TII = MF.getTarget().getInstrInfo();
Evan Cheng46df4eb2010-06-16 07:35:02 +0000265 TRI = MF.getTarget().getRegisterInfo();
Jakub Staszak990f78d2011-08-03 22:34:43 +0000266 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Cheng3ef1c872010-09-10 01:29:16 +0000267 InstrItins = MF.getTarget().getInstrItineraryData();
Evan Cheng4e654852007-05-16 02:00:57 +0000268 if (!TII) return false;
269
Evan Cheng86050dc2010-06-18 23:09:54 +0000270 // Tail merge tend to expose more if-conversion opportunities.
Evan Chengcbc988b2011-05-12 00:56:58 +0000271 BranchFolder BF(true, false);
Evan Cheng86050dc2010-06-18 23:09:54 +0000272 bool BFChange = BF.OptimizeFunction(MF, TII,
273 MF.getTarget().getRegisterInfo(),
274 getAnalysisIfAvailable<MachineModuleInfo>());
275
David Greene083b7ff2010-01-04 22:02:01 +0000276 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Bill Wendling44ff7942009-08-22 20:11:17 +0000277 << MF.getFunction()->getName() << "\'");
Evan Chengedf48962007-06-08 19:10:51 +0000278
279 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene083b7ff2010-01-04 22:02:01 +0000280 DEBUG(dbgs() << " skipped\n");
Evan Chengedf48962007-06-08 19:10:51 +0000281 return false;
282 }
David Greene083b7ff2010-01-04 22:02:01 +0000283 DEBUG(dbgs() << "\n");
Evan Cheng5f702182007-06-01 00:12:12 +0000284
Evan Cheng4e654852007-05-16 02:00:57 +0000285 MF.RenumberBlocks();
Evan Cheng5f702182007-06-01 00:12:12 +0000286 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Cheng4e654852007-05-16 02:00:57 +0000287
Evan Chenge882fca2007-06-16 09:34:52 +0000288 std::vector<IfcvtToken*> Tokens;
Evan Cheng47d25022007-05-18 01:55:58 +0000289 MadeChange = false;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000290 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
291 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
292 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000293 // Do an initial analysis for each basic block and find all the potential
294 // candidates to perform if-conversion.
Bob Wilson6fb124b2010-06-15 18:57:15 +0000295 bool Change = false;
296 AnalyzeBlocks(MF, Tokens);
Evan Chenge882fca2007-06-16 09:34:52 +0000297 while (!Tokens.empty()) {
298 IfcvtToken *Token = Tokens.back();
299 Tokens.pop_back();
300 BBInfo &BBI = Token->BBI;
301 IfcvtKind Kind = Token->Kind;
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000302 unsigned NumDups = Token->NumDups;
Duncan Sands20d629c2008-11-04 18:05:30 +0000303 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000304
305 delete Token;
Evan Chengb6665f62007-06-04 06:47:22 +0000306
Evan Cheng9618bca2007-06-11 22:26:22 +0000307 // If the block has been evicted out of the queue or it has already been
308 // marked dead (due to it being predicated), then skip it.
Evan Chenge882fca2007-06-16 09:34:52 +0000309 if (BBI.IsDone)
310 BBI.IsEnqueued = false;
311 if (!BBI.IsEnqueued)
Evan Cheng9618bca2007-06-11 22:26:22 +0000312 continue;
Evan Chenge882fca2007-06-16 09:34:52 +0000313
Evan Cheng86ff2962007-06-14 20:28:52 +0000314 BBI.IsEnqueued = false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000315
Evan Chengb6665f62007-06-04 06:47:22 +0000316 bool RetVal = false;
Evan Chenge882fca2007-06-16 09:34:52 +0000317 switch (Kind) {
Evan Chenga13aa952007-05-23 07:23:16 +0000318 default: assert(false && "Unexpected!");
319 break;
Evan Chengb6665f62007-06-04 06:47:22 +0000320 case ICSimple:
Evan Chengcb78d672007-06-06 01:12:44 +0000321 case ICSimpleFalse: {
Evan Chenge882fca2007-06-16 09:34:52 +0000322 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000323 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson92fffe02010-06-15 22:18:54 +0000324 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
325 " false" : "")
Bill Wendling44ff7942009-08-22 20:11:17 +0000326 << "): BB#" << BBI.BB->getNumber() << " ("
327 << ((Kind == ICSimpleFalse)
328 ? BBI.FalseBB->getNumber()
329 : BBI.TrueBB->getNumber()) << ") ");
Evan Chenge882fca2007-06-16 09:34:52 +0000330 RetVal = IfConvertSimple(BBI, Kind);
David Greene083b7ff2010-01-04 22:02:01 +0000331 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +0000332 if (RetVal) {
Dan Gohmanfe601042010-06-22 15:08:57 +0000333 if (isFalse) ++NumSimpleFalse;
334 else ++NumSimple;
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +0000335 }
Evan Chengb6665f62007-06-04 06:47:22 +0000336 break;
Evan Chengcb78d672007-06-06 01:12:44 +0000337 }
Evan Chenga13aa952007-05-23 07:23:16 +0000338 case ICTriangle:
Evan Chengcc8fb462007-06-12 23:54:05 +0000339 case ICTriangleRev:
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000340 case ICTriangleFalse:
Reid Spencera9bf49c2007-06-10 00:19:17 +0000341 case ICTriangleFRev: {
Evan Chenge882fca2007-06-16 09:34:52 +0000342 bool isFalse = Kind == ICTriangleFalse;
343 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Chengcc8fb462007-06-12 23:54:05 +0000344 if (DisableTriangle && !isFalse && !isRev) break;
345 if (DisableTriangleR && !isFalse && isRev) break;
346 if (DisableTriangleF && isFalse && !isRev) break;
347 if (DisableTriangleFR && isFalse && isRev) break;
David Greene083b7ff2010-01-04 22:02:01 +0000348 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000349 if (isFalse)
David Greene083b7ff2010-01-04 22:02:01 +0000350 DEBUG(dbgs() << " false");
Evan Chengcc8fb462007-06-12 23:54:05 +0000351 if (isRev)
David Greene083b7ff2010-01-04 22:02:01 +0000352 DEBUG(dbgs() << " rev");
353 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendling44ff7942009-08-22 20:11:17 +0000354 << BBI.TrueBB->getNumber() << ",F:"
355 << BBI.FalseBB->getNumber() << ") ");
Evan Chenge882fca2007-06-16 09:34:52 +0000356 RetVal = IfConvertTriangle(BBI, Kind);
David Greene083b7ff2010-01-04 22:02:01 +0000357 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000358 if (RetVal) {
Evan Chengcc8fb462007-06-12 23:54:05 +0000359 if (isFalse) {
Dan Gohmanfe601042010-06-22 15:08:57 +0000360 if (isRev) ++NumTriangleFRev;
361 else ++NumTriangleFalse;
Evan Chengcc8fb462007-06-12 23:54:05 +0000362 } else {
Dan Gohmanfe601042010-06-22 15:08:57 +0000363 if (isRev) ++NumTriangleRev;
364 else ++NumTriangle;
Evan Chengcc8fb462007-06-12 23:54:05 +0000365 }
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000366 }
Evan Chenga13aa952007-05-23 07:23:16 +0000367 break;
Reid Spencera9bf49c2007-06-10 00:19:17 +0000368 }
Evan Chenge882fca2007-06-16 09:34:52 +0000369 case ICDiamond: {
Evan Chengedf48962007-06-08 19:10:51 +0000370 if (DisableDiamond) break;
David Greene083b7ff2010-01-04 22:02:01 +0000371 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendling44ff7942009-08-22 20:11:17 +0000372 << BBI.TrueBB->getNumber() << ",F:"
373 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000374 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene083b7ff2010-01-04 22:02:01 +0000375 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanfe601042010-06-22 15:08:57 +0000376 if (RetVal) ++NumDiamonds;
Evan Chenga13aa952007-05-23 07:23:16 +0000377 break;
378 }
Evan Chenge882fca2007-06-16 09:34:52 +0000379 }
380
Evan Chengb6665f62007-06-04 06:47:22 +0000381 Change |= RetVal;
Evan Chengedf48962007-06-08 19:10:51 +0000382
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000383 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
384 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
385 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chengedf48962007-06-08 19:10:51 +0000386 break;
Evan Cheng4e654852007-05-16 02:00:57 +0000387 }
Evan Chenga13aa952007-05-23 07:23:16 +0000388
Evan Chenga13aa952007-05-23 07:23:16 +0000389 if (!Change)
390 break;
Evan Chengb6665f62007-06-04 06:47:22 +0000391 MadeChange |= Change;
Evan Cheng4e654852007-05-16 02:00:57 +0000392 }
Evan Cheng47d25022007-05-18 01:55:58 +0000393
Evan Chenge882fca2007-06-16 09:34:52 +0000394 // Delete tokens in case of early exit.
395 while (!Tokens.empty()) {
396 IfcvtToken *Token = Tokens.back();
397 Tokens.pop_back();
398 delete Token;
399 }
400
401 Tokens.clear();
Evan Cheng47d25022007-05-18 01:55:58 +0000402 BBAnalysis.clear();
403
Evan Cheng6a5e2832010-06-18 22:17:13 +0000404 if (MadeChange && IfCvtBranchFold) {
Evan Chengcbc988b2011-05-12 00:56:58 +0000405 BranchFolder BF(false, false);
Evan Cheng030a0a02009-09-04 07:47:40 +0000406 BF.OptimizeFunction(MF, TII,
407 MF.getTarget().getRegisterInfo(),
408 getAnalysisIfAvailable<MachineModuleInfo>());
409 }
410
Evan Cheng86050dc2010-06-18 23:09:54 +0000411 MadeChange |= BFChange;
Evan Cheng4e654852007-05-16 02:00:57 +0000412 return MadeChange;
413}
414
Evan Chenge882fca2007-06-16 09:34:52 +0000415/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
416/// its 'true' successor.
Evan Cheng4e654852007-05-16 02:00:57 +0000417static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng86cbfea2007-05-18 00:20:58 +0000418 MachineBasicBlock *TrueBB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000419 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
420 E = BB->succ_end(); SI != E; ++SI) {
421 MachineBasicBlock *SuccBB = *SI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000422 if (SuccBB != TrueBB)
Evan Cheng4e654852007-05-16 02:00:57 +0000423 return SuccBB;
424 }
425 return NULL;
426}
427
Evan Chenge882fca2007-06-16 09:34:52 +0000428/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson9c4856a2009-05-13 23:25:24 +0000429/// branch. Swap block's 'true' and 'false' successors.
Evan Chengb6665f62007-06-04 06:47:22 +0000430bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings3bf91252010-06-17 22:43:56 +0000431 DebugLoc dl; // FIXME: this is nowhere
Evan Chengb6665f62007-06-04 06:47:22 +0000432 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
433 TII->RemoveBranch(*BBI.BB);
Stuart Hastings3bf91252010-06-17 22:43:56 +0000434 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Chengb6665f62007-06-04 06:47:22 +0000435 std::swap(BBI.TrueBB, BBI.FalseBB);
436 return true;
437 }
438 return false;
439}
440
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000441/// getNextBlock - Returns the next block in the function blocks ordering. If
442/// it is the end, returns NULL.
443static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
444 MachineFunction::iterator I = BB;
445 MachineFunction::iterator E = BB->getParent()->end();
446 if (++I == E)
447 return NULL;
448 return I;
449}
450
Evan Chengac5f1422007-06-08 09:36:04 +0000451/// ValidSimple - Returns true if the 'true' block (along with its
Evan Chenge882fca2007-06-16 09:34:52 +0000452/// predecessor) forms a valid simple shape for ifcvt. It also returns the
453/// number of instructions that the ifcvt would need to duplicate if performed
454/// in Dups.
Owen Anderson7571ee72010-09-28 20:42:15 +0000455bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000456 const BranchProbability &Prediction) const {
Evan Chenge882fca2007-06-16 09:34:52 +0000457 Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000458 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000459 return false;
460
Evan Cheng9ffd3402007-06-19 21:45:13 +0000461 if (TrueBBI.IsBrAnalyzable)
462 return false;
463
Evan Chenga2acf842007-06-15 21:18:05 +0000464 if (TrueBBI.BB->pred_size() > 1) {
465 if (TrueBBI.CannotBeCopied ||
Owen Anderson7571ee72010-09-28 20:42:15 +0000466 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000467 Prediction))
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000468 return false;
Evan Chenge882fca2007-06-16 09:34:52 +0000469 Dups = TrueBBI.NonPredSize;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000470 }
471
Evan Cheng9ffd3402007-06-19 21:45:13 +0000472 return true;
Evan Cheng7a655472007-06-06 10:16:17 +0000473}
474
Evan Chengac5f1422007-06-08 09:36:04 +0000475/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000476/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Chenge882fca2007-06-16 09:34:52 +0000477/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson92fffe02010-06-15 22:18:54 +0000478/// branches to the 'false' block rather than the other way around. It also
Evan Chenge882fca2007-06-16 09:34:52 +0000479/// returns the number of instructions that the ifcvt would need to duplicate
480/// if performed in 'Dups'.
Evan Chengac5f1422007-06-08 09:36:04 +0000481bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000482 bool FalseBranch, unsigned &Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000483 const BranchProbability &Prediction) const {
Evan Chenge882fca2007-06-16 09:34:52 +0000484 Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000485 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000486 return false;
487
Evan Chenga2acf842007-06-15 21:18:05 +0000488 if (TrueBBI.BB->pred_size() > 1) {
489 if (TrueBBI.CannotBeCopied)
490 return false;
491
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000492 unsigned Size = TrueBBI.NonPredSize;
Evan Chenge882fca2007-06-16 09:34:52 +0000493 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman30359592008-01-29 13:02:09 +0000494 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson9c4856a2009-05-13 23:25:24 +0000495 // Ends with an unconditional branch. It will be removed.
Evan Chenge882fca2007-06-16 09:34:52 +0000496 --Size;
497 else {
498 MachineBasicBlock *FExit = FalseBranch
499 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
500 if (FExit)
501 // Require a conditional branch
502 ++Size;
503 }
504 }
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000505 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000506 return false;
Evan Chenge882fca2007-06-16 09:34:52 +0000507 Dups = Size;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000508 }
Evan Chengd4de6d92007-06-07 02:12:15 +0000509
Evan Chengac5f1422007-06-08 09:36:04 +0000510 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
511 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Evan Chengd4de6d92007-06-07 02:12:15 +0000512 MachineFunction::iterator I = TrueBBI.BB;
513 if (++I == TrueBBI.BB->getParent()->end())
514 return false;
Evan Chengac5f1422007-06-08 09:36:04 +0000515 TExit = I;
Evan Chengd4de6d92007-06-07 02:12:15 +0000516 }
Evan Chengac5f1422007-06-08 09:36:04 +0000517 return TExit && TExit == FalseBBI.BB;
Evan Chengd4de6d92007-06-07 02:12:15 +0000518}
519
Evan Chengac5f1422007-06-08 09:36:04 +0000520/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000521/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Chenga1a87872007-06-18 08:37:25 +0000522bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
523 unsigned &Dups1, unsigned &Dups2) const {
524 Dups1 = Dups2 = 0;
525 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
526 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000527 return false;
528
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000529 MachineBasicBlock *TT = TrueBBI.TrueBB;
530 MachineBasicBlock *FT = FalseBBI.TrueBB;
531
532 if (!TT && blockAlwaysFallThrough(TrueBBI))
533 TT = getNextBlock(TrueBBI.BB);
534 if (!FT && blockAlwaysFallThrough(FalseBBI))
535 FT = getNextBlock(FalseBBI.BB);
536 if (TT != FT)
537 return false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000538 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000539 return false;
Evan Chengc4047a82007-06-18 22:44:57 +0000540 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
541 return false;
542
543 // FIXME: Allow true block to have an early exit?
544 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
545 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Chenga1a87872007-06-18 08:37:25 +0000546 return false;
547
Bob Wilson7c730e72010-10-26 00:02:24 +0000548 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach66f360e2010-06-07 21:28:55 +0000549 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
550 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilson7c730e72010-10-26 00:02:24 +0000551 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
552 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
553 while (TIB != TIE && FIB != FIE) {
Evan Chenga9934dc2010-06-18 21:52:57 +0000554 // Skip dbg_value instructions. These do not count.
Bob Wilson7c730e72010-10-26 00:02:24 +0000555 if (TIB->isDebugValue()) {
556 while (TIB != TIE && TIB->isDebugValue())
557 ++TIB;
558 if (TIB == TIE)
Evan Chenga9934dc2010-06-18 21:52:57 +0000559 break;
560 }
Bob Wilson7c730e72010-10-26 00:02:24 +0000561 if (FIB->isDebugValue()) {
562 while (FIB != FIE && FIB->isDebugValue())
563 ++FIB;
564 if (FIB == FIE)
Evan Chenga9934dc2010-06-18 21:52:57 +0000565 break;
566 }
Bob Wilson7c730e72010-10-26 00:02:24 +0000567 if (!TIB->isIdenticalTo(FIB))
568 break;
569 ++Dups1;
570 ++TIB;
571 ++FIB;
572 }
573
574 // Now, in preparation for counting duplicate instructions at the ends of the
575 // blocks, move the end iterators up past any branch instructions.
576 while (TIE != TIB) {
577 --TIE;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000578 if (!TIE->isBranch())
Bob Wilson7c730e72010-10-26 00:02:24 +0000579 break;
580 }
581 while (FIE != FIB) {
582 --FIE;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000583 if (!FIE->isBranch())
Bob Wilson7c730e72010-10-26 00:02:24 +0000584 break;
585 }
586
587 // If Dups1 includes all of a block, then don't count duplicate
588 // instructions at the end of the blocks.
589 if (TIB == TIE || FIB == FIE)
590 return true;
591
592 // Count duplicate instructions at the ends of the blocks.
593 while (TIE != TIB && FIE != FIB) {
594 // Skip dbg_value instructions. These do not count.
595 if (TIE->isDebugValue()) {
596 while (TIE != TIB && TIE->isDebugValue())
597 --TIE;
598 if (TIE == TIB)
599 break;
600 }
601 if (FIE->isDebugValue()) {
602 while (FIE != FIB && FIE->isDebugValue())
603 --FIE;
604 if (FIE == FIB)
605 break;
606 }
607 if (!TIE->isIdenticalTo(FIE))
Evan Chenga1a87872007-06-18 08:37:25 +0000608 break;
609 ++Dups2;
Bob Wilson7c730e72010-10-26 00:02:24 +0000610 --TIE;
611 --FIE;
Evan Chenga1a87872007-06-18 08:37:25 +0000612 }
613
614 return true;
Evan Chengd4de6d92007-06-07 02:12:15 +0000615}
616
Evan Cheng9618bca2007-06-11 22:26:22 +0000617/// ScanInstructions - Scan all the instructions in the block to determine if
618/// the block is predicable. In most cases, that means all the instructions
Chris Lattner69244302008-01-07 01:56:04 +0000619/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng9618bca2007-06-11 22:26:22 +0000620/// instruction which can clobber a predicate (e.g. condition code register).
621/// If so, the block is not predicable unless it's the last instruction.
622void IfConverter::ScanInstructions(BBInfo &BBI) {
623 if (BBI.IsDone)
624 return;
625
Evan Chengd2c5eb82007-07-06 23:24:39 +0000626 bool AlreadyPredicated = BBI.Predicate.size() > 0;
Evan Cheng9618bca2007-06-11 22:26:22 +0000627 // First analyze the end of BB branches.
Evan Chengb7c908b2007-06-14 21:26:08 +0000628 BBI.TrueBB = BBI.FalseBB = NULL;
Evan Cheng9618bca2007-06-11 22:26:22 +0000629 BBI.BrCond.clear();
630 BBI.IsBrAnalyzable =
631 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
632 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
633
634 if (BBI.BrCond.size()) {
635 // No false branch. This BB must end with a conditional branch and a
636 // fallthrough.
637 if (!BBI.FalseBB)
Bob Wilson92fffe02010-06-15 22:18:54 +0000638 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Cheng2077e182009-06-15 21:24:34 +0000639 if (!BBI.FalseBB) {
640 // Malformed bcc? True and false blocks are the same?
641 BBI.IsUnpredicable = true;
642 return;
643 }
Evan Cheng9618bca2007-06-11 22:26:22 +0000644 }
645
646 // Then scan all the instructions.
647 BBI.NonPredSize = 0;
Bob Wilson2ad40d32010-10-26 00:02:21 +0000648 BBI.ExtraCost = 0;
Evan Cheng8239daf2010-11-03 00:45:17 +0000649 BBI.ExtraCost2 = 0;
Evan Cheng9618bca2007-06-11 22:26:22 +0000650 BBI.ClobbersPred = false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000651 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
652 I != E; ++I) {
Jim Grosbach870c8052010-06-04 23:01:26 +0000653 if (I->isDebugValue())
654 continue;
655
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000656 if (I->isNotDuplicable())
Evan Chenga2acf842007-06-15 21:18:05 +0000657 BBI.CannotBeCopied = true;
658
Evan Cheng9618bca2007-06-11 22:26:22 +0000659 bool isPredicated = TII->isPredicated(I);
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000660 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
Evan Cheng9618bca2007-06-11 22:26:22 +0000661
Evan Chengd2c5eb82007-07-06 23:24:39 +0000662 if (!isCondBr) {
Evan Cheng3ef1c872010-09-10 01:29:16 +0000663 if (!isPredicated) {
Bob Wilson2ad40d32010-10-26 00:02:21 +0000664 BBI.NonPredSize++;
Evan Cheng8239daf2010-11-03 00:45:17 +0000665 unsigned ExtraPredCost = 0;
666 unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I,
667 &ExtraPredCost);
668 if (NumCycles > 1)
669 BBI.ExtraCost += NumCycles-1;
670 BBI.ExtraCost2 += ExtraPredCost;
Evan Cheng3ef1c872010-09-10 01:29:16 +0000671 } else if (!AlreadyPredicated) {
Evan Chengd2c5eb82007-07-06 23:24:39 +0000672 // FIXME: This instruction is already predicated before the
673 // if-conversion pass. It's probably something like a conditional move.
674 // Mark this block unpredicable for now.
675 BBI.IsUnpredicable = true;
676 return;
677 }
Evan Chengd2c5eb82007-07-06 23:24:39 +0000678 }
Evan Cheng9618bca2007-06-11 22:26:22 +0000679
680 if (BBI.ClobbersPred && !isPredicated) {
681 // Predicate modification instruction should end the block (except for
682 // already predicated instructions and end of block branches).
683 if (isCondBr) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000684 // A conditional branch is not predicable, but it may be eliminated.
Evan Cheng9618bca2007-06-11 22:26:22 +0000685 continue;
686 }
687
688 // Predicate may have been modified, the subsequent (currently)
Evan Chengd2c5eb82007-07-06 23:24:39 +0000689 // unpredicated instructions cannot be correctly predicated.
Evan Cheng9618bca2007-06-11 22:26:22 +0000690 BBI.IsUnpredicable = true;
691 return;
692 }
693
Evan Cheng11ce02d2007-07-10 17:50:43 +0000694 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
695 // still potentially predicable.
696 std::vector<MachineOperand> PredDefs;
697 if (TII->DefinesPredicate(I, PredDefs))
Evan Cheng9618bca2007-06-11 22:26:22 +0000698 BBI.ClobbersPred = true;
699
Evan Chenge54cb162009-11-21 06:20:26 +0000700 if (!TII->isPredicable(I)) {
Evan Cheng9618bca2007-06-11 22:26:22 +0000701 BBI.IsUnpredicable = true;
702 return;
703 }
704 }
705}
706
707/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
708/// predicated by the specified predicate.
709bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +0000710 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng9618bca2007-06-11 22:26:22 +0000711 bool isTriangle, bool RevBranch) {
Evan Chenge882fca2007-06-16 09:34:52 +0000712 // If the block is dead or unpredicable, then it cannot be predicated.
713 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng9618bca2007-06-11 22:26:22 +0000714 return false;
715
Evan Cheng9618bca2007-06-11 22:26:22 +0000716 // If it is already predicated, check if its predicate subsumes the new
717 // predicate.
718 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
719 return false;
720
721 if (BBI.BrCond.size()) {
722 if (!isTriangle)
723 return false;
724
Bob Wilson9c4856a2009-05-13 23:25:24 +0000725 // Test predicate subsumption.
Owen Anderson44eb65c2008-08-14 22:49:33 +0000726 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
727 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng9618bca2007-06-11 22:26:22 +0000728 if (RevBranch) {
729 if (TII->ReverseBranchCondition(Cond))
730 return false;
731 }
732 if (TII->ReverseBranchCondition(RevPred) ||
733 !TII->SubsumesPredicate(Cond, RevPred))
734 return false;
735 }
736
737 return true;
738}
739
Evan Chengac5f1422007-06-08 09:36:04 +0000740/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Chengcf6cc112007-05-18 18:14:37 +0000741/// the specified block. Record its successors and whether it looks like an
742/// if-conversion candidate.
Evan Chenge882fca2007-06-16 09:34:52 +0000743IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
744 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng4e654852007-05-16 02:00:57 +0000745 BBInfo &BBI = BBAnalysis[BB->getNumber()];
746
Evan Cheng9618bca2007-06-11 22:26:22 +0000747 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
748 return BBI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000749
Evan Cheng9618bca2007-06-11 22:26:22 +0000750 BBI.BB = BB;
751 BBI.IsBeingAnalyzed = true;
Evan Cheng9618bca2007-06-11 22:26:22 +0000752
753 ScanInstructions(BBI);
754
Jakub Staszak2b33f4c2011-07-10 02:00:16 +0000755 // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
756 // considered for ifcvt anymore.
757 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
Evan Cheng9618bca2007-06-11 22:26:22 +0000758 BBI.IsBeingAnalyzed = false;
759 BBI.IsAnalyzed = true;
760 return BBI;
Evan Cheng7a655472007-06-06 10:16:17 +0000761 }
762
Evan Cheng9618bca2007-06-11 22:26:22 +0000763 // Do not ifcvt if either path is a back edge to the entry block.
764 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
765 BBI.IsBeingAnalyzed = false;
766 BBI.IsAnalyzed = true;
767 return BBI;
768 }
769
Evan Cheng2077e182009-06-15 21:24:34 +0000770 // Do not ifcvt if true and false fallthrough blocks are the same.
771 if (!BBI.FalseBB) {
772 BBI.IsBeingAnalyzed = false;
773 BBI.IsAnalyzed = true;
774 return BBI;
775 }
776
Evan Chenge882fca2007-06-16 09:34:52 +0000777 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
778 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
Evan Cheng9618bca2007-06-11 22:26:22 +0000779
780 if (TrueBBI.IsDone && FalseBBI.IsDone) {
781 BBI.IsBeingAnalyzed = false;
782 BBI.IsAnalyzed = true;
783 return BBI;
784 }
785
Owen Anderson44eb65c2008-08-14 22:49:33 +0000786 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chengb6665f62007-06-04 06:47:22 +0000787 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
Evan Chengac5f1422007-06-08 09:36:04 +0000788
Evan Chenge882fca2007-06-16 09:34:52 +0000789 unsigned Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000790 unsigned Dups2 = 0;
Evan Chenge882fca2007-06-16 09:34:52 +0000791 bool TNeedSub = TrueBBI.Predicate.size() > 0;
792 bool FNeedSub = FalseBBI.Predicate.size() > 0;
793 bool Enqueued = false;
Benjamin Kramer6406d002010-09-29 22:38:50 +0000794
Jakub Staszak990f78d2011-08-03 22:34:43 +0000795 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
796
Evan Chenga1a87872007-06-18 08:37:25 +0000797 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000798 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
Evan Cheng8239daf2010-11-03 00:45:17 +0000799 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
Bob Wilson2ad40d32010-10-26 00:02:21 +0000800 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Cheng8239daf2010-11-03 00:45:17 +0000801 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000802 Prediction) &&
Evan Chengac5f1422007-06-08 09:36:04 +0000803 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
804 FeasibilityAnalysis(FalseBBI, RevCond)) {
Evan Cheng4e654852007-05-16 02:00:57 +0000805 // Diamond:
806 // EBB
807 // / \_
808 // | |
809 // TBB FBB
810 // \ /
Evan Cheng86cbfea2007-05-18 00:20:58 +0000811 // TailBB
Evan Cheng993fc952007-06-05 23:46:14 +0000812 // Note TailBB can be empty.
Evan Chenga1a87872007-06-18 08:37:25 +0000813 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
814 Dups2));
Evan Chenge882fca2007-06-16 09:34:52 +0000815 Enqueued = true;
816 }
817
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000818 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000819 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000820 TrueBBI.ExtraCost2, Prediction) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000821 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
822 // Triangle:
823 // EBB
824 // | \_
825 // | |
826 // | TBB
827 // | /
828 // FBB
829 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
830 Enqueued = true;
831 }
Bob Wilson92fffe02010-06-15 22:18:54 +0000832
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000833 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000834 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000835 TrueBBI.ExtraCost2, Prediction) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000836 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
837 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
838 Enqueued = true;
839 }
840
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000841 if (ValidSimple(TrueBBI, Dups, Prediction) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000842 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000843 TrueBBI.ExtraCost2, Prediction) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000844 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
845 // Simple (split, no rejoin):
846 // EBB
847 // | \_
848 // | |
849 // | TBB---> exit
Bob Wilson92fffe02010-06-15 22:18:54 +0000850 // |
Evan Chenge882fca2007-06-16 09:34:52 +0000851 // FBB
852 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
853 Enqueued = true;
854 }
855
856 if (CanRevCond) {
857 // Try the other path...
Owen Andersone3cc84a2010-10-01 22:45:50 +0000858 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000859 Prediction.getCompl()) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000860 MeetIfcvtSizeLimit(*FalseBBI.BB,
861 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000862 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000863 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
864 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
865 Enqueued = true;
866 }
867
Owen Andersone3cc84a2010-10-01 22:45:50 +0000868 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000869 Prediction.getCompl()) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000870 MeetIfcvtSizeLimit(*FalseBBI.BB,
871 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000872 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000873 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
874 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
875 Enqueued = true;
876 }
877
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000878 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000879 MeetIfcvtSizeLimit(*FalseBBI.BB,
880 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszakf81b7f62011-07-10 02:58:07 +0000881 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000882 FeasibilityAnalysis(FalseBBI, RevCond)) {
883 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
884 Enqueued = true;
Evan Chengb6665f62007-06-04 06:47:22 +0000885 }
Evan Cheng4e654852007-05-16 02:00:57 +0000886 }
Evan Cheng4e654852007-05-16 02:00:57 +0000887
Evan Chenge882fca2007-06-16 09:34:52 +0000888 BBI.IsEnqueued = Enqueued;
Evan Cheng9618bca2007-06-11 22:26:22 +0000889 BBI.IsBeingAnalyzed = false;
890 BBI.IsAnalyzed = true;
891 return BBI;
Evan Chengcf6cc112007-05-18 18:14:37 +0000892}
893
Evan Cheng82582102007-05-30 19:49:19 +0000894/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilson6fb124b2010-06-15 18:57:15 +0000895/// candidates.
896void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Chenge882fca2007-06-16 09:34:52 +0000897 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng309db7c2011-04-27 19:32:43 +0000898 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
899 MachineBasicBlock *BB = I;
900 AnalyzeBlock(BB, Tokens);
Evan Cheng4e654852007-05-16 02:00:57 +0000901 }
Evan Cheng82582102007-05-30 19:49:19 +0000902
Evan Cheng5f702182007-06-01 00:12:12 +0000903 // Sort to favor more complex ifcvt scheme.
Evan Chenge882fca2007-06-16 09:34:52 +0000904 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Cheng4e654852007-05-16 02:00:57 +0000905}
906
Evan Cheng7e75ba82007-06-08 22:01:07 +0000907/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
908/// that all the intervening blocks are empty (given BB can fall through to its
909/// next block).
910static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Cheng46df4eb2010-06-16 07:35:02 +0000911 MachineFunction::iterator PI = BB;
912 MachineFunction::iterator I = llvm::next(PI);
Evan Chengc53ef582007-06-05 07:05:25 +0000913 MachineFunction::iterator TI = ToBB;
914 MachineFunction::iterator E = BB->getParent()->end();
Evan Cheng46df4eb2010-06-16 07:35:02 +0000915 while (I != TI) {
916 // Check isSuccessor to avoid case where the next block is empty, but
917 // it's not a successor.
918 if (I == E || !I->empty() || !PI->isSuccessor(I))
Evan Chengb6665f62007-06-04 06:47:22 +0000919 return false;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000920 PI = I++;
921 }
Evan Chengb6665f62007-06-04 06:47:22 +0000922 return true;
Evan Chenga6b4f432007-05-21 22:22:58 +0000923}
924
Evan Chenga1a87872007-06-18 08:37:25 +0000925/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
926/// to determine if it can be if-converted. If predecessor is already enqueued,
927/// dequeue it!
928void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Evan Chenga13aa952007-05-23 07:23:16 +0000929 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
930 E = BB->pred_end(); PI != E; ++PI) {
931 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
Evan Chengbc198ee2007-06-14 23:34:09 +0000932 if (PBBI.IsDone || PBBI.BB == BB)
Evan Chenge37e2432007-06-14 23:13:19 +0000933 continue;
Evan Chengbc198ee2007-06-14 23:34:09 +0000934 PBBI.IsAnalyzed = false;
935 PBBI.IsEnqueued = false;
Evan Chenga13aa952007-05-23 07:23:16 +0000936 }
937}
938
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000939/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
940///
941static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
942 const TargetInstrInfo *TII) {
Stuart Hastings3bf91252010-06-17 22:43:56 +0000943 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman1501cdb2008-08-22 16:07:55 +0000944 SmallVector<MachineOperand, 0> NoCond;
Stuart Hastings3bf91252010-06-17 22:43:56 +0000945 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000946}
947
Evan Cheng7e75ba82007-06-08 22:01:07 +0000948/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
949/// successors.
950void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
951 MachineBasicBlock *TBB = NULL, *FBB = NULL;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000952 SmallVector<MachineOperand, 4> Cond;
Evan Chengc4047a82007-06-18 22:44:57 +0000953 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
954 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng7e75ba82007-06-08 22:01:07 +0000955}
956
Evan Cheng46df4eb2010-06-16 07:35:02 +0000957/// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
958/// modeled as read + write (sort like two-address instructions). These
959/// routines track register liveness and add implicit uses to if-converted
960/// instructions to conform to the model.
961static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
962 const TargetRegisterInfo *TRI) {
963 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
964 E = BB->livein_end(); I != E; ++I) {
965 unsigned Reg = *I;
966 Redefs.insert(Reg);
967 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
968 *Subreg; ++Subreg)
969 Redefs.insert(*Subreg);
970 }
971}
972
973static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
974 const TargetRegisterInfo *TRI,
975 bool AddImpUse = false) {
976 SmallVector<unsigned, 4> Defs;
977 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
978 const MachineOperand &MO = MI->getOperand(i);
979 if (!MO.isReg())
980 continue;
981 unsigned Reg = MO.getReg();
982 if (!Reg)
983 continue;
984 if (MO.isDef())
985 Defs.push_back(Reg);
986 else if (MO.isKill()) {
987 Redefs.erase(Reg);
988 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
989 Redefs.erase(*SR);
990 }
991 }
992 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
993 unsigned Reg = Defs[i];
994 if (Redefs.count(Reg)) {
995 if (AddImpUse)
996 // Treat predicated update as read + write.
997 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
Jim Grosbach135ec502010-06-25 22:02:28 +0000998 true/*IsImp*/,false/*IsKill*/));
Evan Cheng46df4eb2010-06-16 07:35:02 +0000999 } else {
1000 Redefs.insert(Reg);
1001 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1002 Redefs.insert(*SR);
1003 }
1004 }
1005}
1006
1007static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1008 MachineBasicBlock::iterator E,
1009 SmallSet<unsigned,4> &Redefs,
1010 const TargetRegisterInfo *TRI) {
1011 while (I != E) {
1012 UpdatePredRedefs(I, Redefs, TRI);
1013 ++I;
1014 }
1015}
1016
Evan Chengb6665f62007-06-04 06:47:22 +00001017/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenga6b4f432007-05-21 22:22:58 +00001018///
Evan Chenge882fca2007-06-16 09:34:52 +00001019bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenga6b4f432007-05-21 22:22:58 +00001020 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1021 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1022 BBInfo *CvtBBI = &TrueBBI;
1023 BBInfo *NextBBI = &FalseBBI;
Evan Chenga13aa952007-05-23 07:23:16 +00001024
Owen Anderson44eb65c2008-08-14 22:49:33 +00001025 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chenge882fca2007-06-16 09:34:52 +00001026 if (Kind == ICSimpleFalse)
Evan Chengb5a06902007-06-01 20:29:21 +00001027 std::swap(CvtBBI, NextBBI);
Evan Chenga2acf842007-06-15 21:18:05 +00001028
Evan Chenga1a87872007-06-18 08:37:25 +00001029 if (CvtBBI->IsDone ||
1030 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Chenga2acf842007-06-15 21:18:05 +00001031 // Something has changed. It's no longer safe to predicate this block.
Evan Chenga2acf842007-06-15 21:18:05 +00001032 BBI.IsAnalyzed = false;
1033 CvtBBI->IsAnalyzed = false;
1034 return false;
Evan Chengb5a06902007-06-01 20:29:21 +00001035 }
Evan Chenga13aa952007-05-23 07:23:16 +00001036
Evan Chenge882fca2007-06-16 09:34:52 +00001037 if (Kind == ICSimpleFalse)
Dan Gohman279c22e2008-10-21 03:29:32 +00001038 if (TII->ReverseBranchCondition(Cond))
1039 assert(false && "Unable to reverse branch condition!");
Evan Chenga2acf842007-06-15 21:18:05 +00001040
Bob Wilson54eee522010-06-19 05:33:57 +00001041 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001042 // predicated instructions.
1043 SmallSet<unsigned, 4> Redefs;
1044 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1045 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1046
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001047 if (CvtBBI->BB->pred_size() > 1) {
1048 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson9c4856a2009-05-13 23:25:24 +00001049 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001050 // the entry block.
Evan Cheng46df4eb2010-06-16 07:35:02 +00001051 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001052 } else {
Evan Cheng46df4eb2010-06-16 07:35:02 +00001053 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Evan Chenga6b4f432007-05-21 22:22:58 +00001054
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001055 // Merge converted block into entry block.
1056 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1057 MergeBlocks(BBI, *CvtBBI);
1058 }
Evan Chengd4de6d92007-06-07 02:12:15 +00001059
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001060 bool IterIfcvt = true;
Evan Cheng7e75ba82007-06-08 22:01:07 +00001061 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc8ed9ba2007-05-29 22:31:16 +00001062 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001063 BBI.HasFallThrough = false;
Evan Chengac5f1422007-06-08 09:36:04 +00001064 // Now ifcvt'd block will look like this:
1065 // BB:
1066 // ...
1067 // t, f = cmp
1068 // if t op
1069 // b BBf
1070 //
1071 // We cannot further ifcvt this block because the unconditional branch
1072 // will have to be predicated on the new condition, that will not be
1073 // available if cmp executes.
1074 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001075 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001076
Evan Cheng7e75ba82007-06-08 22:01:07 +00001077 RemoveExtraEdges(BBI);
1078
Evan Chenga13aa952007-05-23 07:23:16 +00001079 // Update block info. BB can be iteratively if-converted.
Evan Cheng9618bca2007-06-11 22:26:22 +00001080 if (!IterIfcvt)
1081 BBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001082 InvalidatePreds(BBI.BB);
Evan Cheng9618bca2007-06-11 22:26:22 +00001083 CvtBBI->IsDone = true;
Evan Chenga6b4f432007-05-21 22:22:58 +00001084
1085 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001086 return true;
1087}
1088
Evan Chengd6ddc302007-05-16 21:54:37 +00001089/// IfConvertTriangle - If convert a triangle sub-CFG.
1090///
Evan Chenge882fca2007-06-16 09:34:52 +00001091bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenga13aa952007-05-23 07:23:16 +00001092 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001093 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1094 BBInfo *CvtBBI = &TrueBBI;
1095 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings3bf91252010-06-17 22:43:56 +00001096 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001097
Owen Anderson44eb65c2008-08-14 22:49:33 +00001098 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chenge882fca2007-06-16 09:34:52 +00001099 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001100 std::swap(CvtBBI, NextBBI);
Evan Chenga2acf842007-06-15 21:18:05 +00001101
Evan Chenga1a87872007-06-18 08:37:25 +00001102 if (CvtBBI->IsDone ||
1103 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Chenga2acf842007-06-15 21:18:05 +00001104 // Something has changed. It's no longer safe to predicate this block.
Evan Chenga2acf842007-06-15 21:18:05 +00001105 BBI.IsAnalyzed = false;
1106 CvtBBI->IsAnalyzed = false;
1107 return false;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001108 }
Evan Chenga2acf842007-06-15 21:18:05 +00001109
Evan Chenge882fca2007-06-16 09:34:52 +00001110 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman279c22e2008-10-21 03:29:32 +00001111 if (TII->ReverseBranchCondition(Cond))
1112 assert(false && "Unable to reverse branch condition!");
Evan Chenga2acf842007-06-15 21:18:05 +00001113
Evan Chenge882fca2007-06-16 09:34:52 +00001114 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman279c22e2008-10-21 03:29:32 +00001115 if (ReverseBranchCondition(*CvtBBI)) {
1116 // BB has been changed, modify its predecessors (except for this
1117 // one) so they don't get ifcvt'ed based on bad intel.
1118 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1119 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1120 MachineBasicBlock *PBB = *PI;
1121 if (PBB == BBI.BB)
1122 continue;
1123 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1124 if (PBBI.IsEnqueued) {
1125 PBBI.IsAnalyzed = false;
1126 PBBI.IsEnqueued = false;
1127 }
Evan Chengbc198ee2007-06-14 23:34:09 +00001128 }
Evan Chengcc8fb462007-06-12 23:54:05 +00001129 }
1130 }
Evan Cheng8c529382007-06-01 07:41:07 +00001131
Bob Wilson54eee522010-06-19 05:33:57 +00001132 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001133 // predicated instructions.
1134 SmallSet<unsigned, 4> Redefs;
1135 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1136 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1137
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001138 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
Bob Wilson8eab75f2010-06-29 00:55:23 +00001139 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001140 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson9c4856a2009-05-13 23:25:24 +00001141 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001142 // the entry block.
Evan Cheng46df4eb2010-06-16 07:35:02 +00001143 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001144 } else {
1145 // Predicate the 'true' block after removing its branch.
1146 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Cheng46df4eb2010-06-16 07:35:02 +00001147 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Evan Chenga6b4f432007-05-21 22:22:58 +00001148
Evan Chengc4047a82007-06-18 22:44:57 +00001149 // Now merge the entry of the triangle with the true block.
1150 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson8eab75f2010-06-29 00:55:23 +00001151 MergeBlocks(BBI, *CvtBBI, false);
Evan Chengc4047a82007-06-18 22:44:57 +00001152 }
1153
Evan Chengb6665f62007-06-04 06:47:22 +00001154 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng8ed680c2007-06-05 01:31:40 +00001155 if (HasEarlyExit) {
Owen Anderson44eb65c2008-08-14 22:49:33 +00001156 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1157 CvtBBI->BrCond.end());
Evan Cheng8c529382007-06-01 07:41:07 +00001158 if (TII->ReverseBranchCondition(RevCond))
1159 assert(false && "Unable to reverse branch condition!");
Stuart Hastings3bf91252010-06-17 22:43:56 +00001160 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
Evan Chengc4047a82007-06-18 22:44:57 +00001161 BBI.BB->addSuccessor(CvtBBI->FalseBB);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001162 }
Evan Chengac5f1422007-06-08 09:36:04 +00001163
1164 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson9c4856a2009-05-13 23:25:24 +00001165 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Chengf5305f92007-06-05 00:07:37 +00001166 bool FalseBBDead = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001167 bool IterIfcvt = true;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001168 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengf4769612007-06-07 08:13:00 +00001169 if (!isFallThrough) {
1170 // Only merge them if the true block does not fallthrough to the false
1171 // block. By not merging them, we make it possible to iteratively
1172 // ifcvt the blocks.
Evan Chenga1a87872007-06-18 08:37:25 +00001173 if (!HasEarlyExit &&
1174 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001175 MergeBlocks(BBI, *NextBBI);
Evan Chengf4769612007-06-07 08:13:00 +00001176 FalseBBDead = true;
Evan Chengf4769612007-06-07 08:13:00 +00001177 } else {
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001178 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1179 BBI.HasFallThrough = false;
Evan Chengf4769612007-06-07 08:13:00 +00001180 }
Evan Chengac5f1422007-06-08 09:36:04 +00001181 // Mixed predicated and unpredicated code. This cannot be iteratively
1182 // predicated.
1183 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001184 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001185
Evan Cheng7e75ba82007-06-08 22:01:07 +00001186 RemoveExtraEdges(BBI);
Evan Chenga6b4f432007-05-21 22:22:58 +00001187
Evan Chenga13aa952007-05-23 07:23:16 +00001188 // Update block info. BB can be iteratively if-converted.
Bob Wilson92fffe02010-06-15 22:18:54 +00001189 if (!IterIfcvt)
Evan Cheng9618bca2007-06-11 22:26:22 +00001190 BBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001191 InvalidatePreds(BBI.BB);
Evan Cheng9618bca2007-06-11 22:26:22 +00001192 CvtBBI->IsDone = true;
Evan Chengf5305f92007-06-05 00:07:37 +00001193 if (FalseBBDead)
Evan Cheng9618bca2007-06-11 22:26:22 +00001194 NextBBI->IsDone = true;
Evan Chenga6b4f432007-05-21 22:22:58 +00001195
1196 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001197 return true;
Evan Cheng4e654852007-05-16 02:00:57 +00001198}
1199
Evan Chengd6ddc302007-05-16 21:54:37 +00001200/// IfConvertDiamond - If convert a diamond sub-CFG.
1201///
Evan Chenga1a87872007-06-18 08:37:25 +00001202bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1203 unsigned NumDups1, unsigned NumDups2) {
Evan Chengb6665f62007-06-04 06:47:22 +00001204 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Chengcf6cc112007-05-18 18:14:37 +00001205 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chenge882fca2007-06-16 09:34:52 +00001206 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson9c4856a2009-05-13 23:25:24 +00001207 // True block must fall through or end with an unanalyzable terminator.
Evan Chenge882fca2007-06-16 09:34:52 +00001208 if (!TailBB) {
Evan Chenga1a87872007-06-18 08:37:25 +00001209 if (blockAlwaysFallThrough(TrueBBI))
1210 TailBB = FalseBBI.TrueBB;
1211 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Cheng4e654852007-05-16 02:00:57 +00001212 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001213
Evan Chenga1a87872007-06-18 08:37:25 +00001214 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1215 TrueBBI.BB->pred_size() > 1 ||
1216 FalseBBI.BB->pred_size() > 1) {
1217 // Something has changed. It's no longer safe to predicate these blocks.
1218 BBI.IsAnalyzed = false;
1219 TrueBBI.IsAnalyzed = false;
1220 FalseBBI.IsAnalyzed = false;
1221 return false;
Evan Chenga6b4f432007-05-21 22:22:58 +00001222 }
Evan Chenga1a87872007-06-18 08:37:25 +00001223
Bob Wilson8eab75f2010-06-29 00:55:23 +00001224 // Put the predicated instructions from the 'true' block before the
1225 // instructions from the 'false' block, unless the true block would clobber
1226 // the predicate, in which case, do the opposite.
Evan Cheng993fc952007-06-05 23:46:14 +00001227 BBInfo *BBI1 = &TrueBBI;
1228 BBInfo *BBI2 = &FalseBBI;
Owen Anderson44eb65c2008-08-14 22:49:33 +00001229 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman279c22e2008-10-21 03:29:32 +00001230 if (TII->ReverseBranchCondition(RevCond))
1231 assert(false && "Unable to reverse branch condition!");
Owen Anderson44eb65c2008-08-14 22:49:33 +00001232 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1233 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Chenge7052132007-06-06 00:57:55 +00001234
Evan Chenge882fca2007-06-16 09:34:52 +00001235 // Figure out the more profitable ordering.
1236 bool DoSwap = false;
1237 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1238 DoSwap = true;
1239 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Chengc4047a82007-06-18 22:44:57 +00001240 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Chenge882fca2007-06-16 09:34:52 +00001241 DoSwap = true;
Evan Chenge882fca2007-06-16 09:34:52 +00001242 }
1243 if (DoSwap) {
Evan Chenge7052132007-06-06 00:57:55 +00001244 std::swap(BBI1, BBI2);
1245 std::swap(Cond1, Cond2);
Evan Chenge7052132007-06-06 00:57:55 +00001246 }
Evan Cheng993fc952007-06-05 23:46:14 +00001247
Evan Chenga1a87872007-06-18 08:37:25 +00001248 // Remove the conditional branch from entry to the blocks.
1249 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1250
Jim Grosbach135ec502010-06-25 22:02:28 +00001251 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001252 // predicated instructions.
1253 SmallSet<unsigned, 4> Redefs;
1254 InitPredRedefs(BBI1->BB, Redefs, TRI);
1255
Evan Chenga1a87872007-06-18 08:37:25 +00001256 // Remove the duplicated instructions at the beginnings of both paths.
1257 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1258 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbachc834f412010-06-14 21:30:32 +00001259 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1260 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1261 // Skip dbg_value instructions
1262 while (DI1 != DIE1 && DI1->isDebugValue())
1263 ++DI1;
1264 while (DI2 != DIE2 && DI2->isDebugValue())
1265 ++DI2;
Evan Chenga1a87872007-06-18 08:37:25 +00001266 BBI1->NonPredSize -= NumDups1;
1267 BBI2->NonPredSize -= NumDups1;
Jim Grosbachd459f452010-06-28 20:26:00 +00001268
1269 // Skip past the dups on each side separately since there may be
1270 // differing dbg_value entries.
1271 for (unsigned i = 0; i < NumDups1; ++DI1) {
1272 if (!DI1->isDebugValue())
1273 ++i;
1274 }
Jim Grosbach9f054f02010-06-25 23:05:46 +00001275 while (NumDups1 != 0) {
Evan Chenga1a87872007-06-18 08:37:25 +00001276 ++DI2;
Jim Grosbachd459f452010-06-28 20:26:00 +00001277 if (!DI2->isDebugValue())
1278 --NumDups1;
Evan Chenga1a87872007-06-18 08:37:25 +00001279 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001280
1281 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
Evan Chenga1a87872007-06-18 08:37:25 +00001282 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1283 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1284
Evan Cheng8787c5f2011-12-19 22:01:30 +00001285 // Remove branch from 'true' block and remove duplicated instructions.
Evan Cheng993fc952007-06-05 23:46:14 +00001286 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
Evan Chenga1a87872007-06-18 08:37:25 +00001287 DI1 = BBI1->BB->end();
Jim Grosbachc834f412010-06-14 21:30:32 +00001288 for (unsigned i = 0; i != NumDups2; ) {
1289 // NumDups2 only counted non-dbg_value instructions, so this won't
1290 // run off the head of the list.
1291 assert (DI1 != BBI1->BB->begin());
Evan Chenga1a87872007-06-18 08:37:25 +00001292 --DI1;
Jim Grosbachc834f412010-06-14 21:30:32 +00001293 // skip dbg_value instructions
1294 if (!DI1->isDebugValue())
1295 ++i;
1296 }
Evan Chenga1a87872007-06-18 08:37:25 +00001297 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng993fc952007-06-05 23:46:14 +00001298
Evan Cheng8787c5f2011-12-19 22:01:30 +00001299 // Remove 'false' block branch and find the last instruction to predicate.
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 Cheng8787c5f2011-12-19 22:01:30 +00001311
1312 // Remember which registers would later be defined by the false block.
1313 // This allows us not to predicate instructions in the true block that would
1314 // later be re-defined. That is, rather than
1315 // subeq r0, r1, #1
1316 // addne r0, r1, #1
1317 // generate:
1318 // sub r0, r1, #1
1319 // addne r0, r1, #1
1320 SmallSet<unsigned, 4> RedefsByFalse;
1321 SmallSet<unsigned, 4> ExtUses;
1322 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1323 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1324 if (FI->isDebugValue())
1325 continue;
1326 SmallVector<unsigned, 4> Defs;
1327 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1328 const MachineOperand &MO = FI->getOperand(i);
1329 if (!MO.isReg())
1330 continue;
1331 unsigned Reg = MO.getReg();
1332 if (!Reg)
1333 continue;
1334 if (MO.isDef()) {
1335 Defs.push_back(Reg);
1336 } else if (!RedefsByFalse.count(Reg)) {
1337 // These are defined before ctrl flow reach the 'false' instructions.
1338 // They cannot be modified by the 'true' instructions.
1339 ExtUses.insert(Reg);
1340 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1341 ExtUses.insert(*SR);
1342 }
1343 }
1344
1345 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1346 unsigned Reg = Defs[i];
1347 if (!ExtUses.count(Reg)) {
1348 RedefsByFalse.insert(Reg);
1349 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1350 RedefsByFalse.insert(*SR);
1351 }
1352 }
1353 }
1354 }
1355
1356 // Predicate the 'true' block.
1357 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs, &RedefsByFalse);
1358
1359 // Predicate the 'false' block.
Evan Cheng46df4eb2010-06-16 07:35:02 +00001360 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
Evan Cheng993fc952007-06-05 23:46:14 +00001361
Evan Chengc4047a82007-06-18 22:44:57 +00001362 // Merge the true block into the entry of the diamond.
Bob Wilson8eab75f2010-06-29 00:55:23 +00001363 MergeBlocks(BBI, *BBI1, TailBB == 0);
1364 MergeBlocks(BBI, *BBI2, TailBB == 0);
Evan Chenge7052132007-06-06 00:57:55 +00001365
Bob Wilson9c4856a2009-05-13 23:25:24 +00001366 // If the if-converted block falls through or unconditionally branches into
1367 // the tail block, and the tail block does not have other predecessors, then
Evan Chenga1a87872007-06-18 08:37:25 +00001368 // fold the tail block in as well. Otherwise, unless it falls through to the
1369 // tail, add a unconditional branch to it.
1370 if (TailBB) {
Pete Cooper9c58aa742011-11-04 23:49:14 +00001371 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Bob Wilson8eab75f2010-06-29 00:55:23 +00001372 bool CanMergeTail = !TailBBI.HasFallThrough;
1373 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1374 // check if there are any other predecessors besides those.
1375 unsigned NumPreds = TailBB->pred_size();
1376 if (NumPreds > 1)
1377 CanMergeTail = false;
1378 else if (NumPreds == 1 && CanMergeTail) {
1379 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1380 if (*PI != BBI1->BB && *PI != BBI2->BB)
1381 CanMergeTail = false;
1382 }
1383 if (CanMergeTail) {
Evan Chengc4047a82007-06-18 22:44:57 +00001384 MergeBlocks(BBI, TailBBI);
Evan Chenga1a87872007-06-18 08:37:25 +00001385 TailBBI.IsDone = true;
1386 } else {
Bob Wilson8eab75f2010-06-29 00:55:23 +00001387 BBI.BB->addSuccessor(TailBB);
Evan Chengc4047a82007-06-18 22:44:57 +00001388 InsertUncondBranch(BBI.BB, TailBB, TII);
1389 BBI.HasFallThrough = false;
Evan Chenga1a87872007-06-18 08:37:25 +00001390 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001391 }
1392
Bob Wilson8eab75f2010-06-29 00:55:23 +00001393 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1394 // which can happen here if TailBB is unanalyzable and is merged, so
1395 // explicitly remove BBI1 and BBI2 as successors.
1396 BBI.BB->removeSuccessor(BBI1->BB);
1397 BBI.BB->removeSuccessor(BBI2->BB);
Evan Cheng7e75ba82007-06-08 22:01:07 +00001398 RemoveExtraEdges(BBI);
1399
Evan Cheng993fc952007-06-05 23:46:14 +00001400 // Update block info.
Evan Cheng9618bca2007-06-11 22:26:22 +00001401 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001402 InvalidatePreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +00001403
1404 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001405 return true;
Evan Cheng4e654852007-05-16 02:00:57 +00001406}
1407
Evan Cheng8787c5f2011-12-19 22:01:30 +00001408static bool MaySpeculate(const MachineInstr *MI,
1409 SmallSet<unsigned, 4> &LaterRedefs,
1410 const TargetInstrInfo *TII) {
1411 bool SawStore = true;
1412 if (!MI->isSafeToMove(TII, 0, SawStore))
1413 return false;
1414
1415 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1416 const MachineOperand &MO = MI->getOperand(i);
1417 if (!MO.isReg())
1418 continue;
1419 unsigned Reg = MO.getReg();
1420 if (!Reg)
1421 continue;
1422 if (MO.isDef() && !LaterRedefs.count(Reg))
1423 return false;
1424 }
1425
1426 return true;
1427}
1428
Evan Chenga1a87872007-06-18 08:37:25 +00001429/// PredicateBlock - Predicate instructions from the start of the block to the
1430/// specified end with the specified condition.
Evan Chenga13aa952007-05-23 07:23:16 +00001431void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Chenga1a87872007-06-18 08:37:25 +00001432 MachineBasicBlock::iterator E,
Evan Cheng46df4eb2010-06-16 07:35:02 +00001433 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng8787c5f2011-12-19 22:01:30 +00001434 SmallSet<unsigned, 4> &Redefs,
1435 SmallSet<unsigned, 4> *LaterRedefs) {
1436 bool AnyUnpred = false;
1437 bool MaySpec = LaterRedefs != 0;
Evan Chenga1a87872007-06-18 08:37:25 +00001438 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbach870c8052010-06-04 23:01:26 +00001439 if (I->isDebugValue() || TII->isPredicated(I))
Evan Chenga13aa952007-05-23 07:23:16 +00001440 continue;
Evan Cheng8787c5f2011-12-19 22:01:30 +00001441 // It may be possible not to predicate an instruction if it's the 'true'
1442 // side of a diamond and the 'false' side may re-define the instruction's
1443 // defs.
1444 if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
1445 AnyUnpred = true;
1446 continue;
1447 }
1448 // If any instruction is predicated, then every instruction after it must
1449 // be predicated.
1450 MaySpec = false;
Evan Chengb6665f62007-06-04 06:47:22 +00001451 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwinf3689232009-07-12 20:07:01 +00001452#ifndef NDEBUG
David Greene083b7ff2010-01-04 22:02:01 +00001453 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwinf3689232009-07-12 20:07:01 +00001454#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001455 llvm_unreachable(0);
Evan Chengd6ddc302007-05-16 21:54:37 +00001456 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001457
Bob Wilson54eee522010-06-19 05:33:57 +00001458 // If the predicated instruction now redefines a register as the result of
Evan Cheng46df4eb2010-06-16 07:35:02 +00001459 // if-conversion, add an implicit kill.
1460 UpdatePredRedefs(I, Redefs, TRI, true);
Evan Cheng4e654852007-05-16 02:00:57 +00001461 }
Evan Chenga13aa952007-05-23 07:23:16 +00001462
Evan Cheng2acdbcc2007-06-08 19:17:12 +00001463 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1464
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001465 BBI.IsAnalyzed = false;
1466 BBI.NonPredSize = 0;
1467
Dan Gohmanfe601042010-06-22 15:08:57 +00001468 ++NumIfConvBBs;
Evan Cheng8787c5f2011-12-19 22:01:30 +00001469 if (AnyUnpred)
1470 ++NumUnpred;
Evan Chengb6665f62007-06-04 06:47:22 +00001471}
1472
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001473/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1474/// the destination block. Skip end of block branches if IgnoreBr is true.
1475void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +00001476 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng46df4eb2010-06-16 07:35:02 +00001477 SmallSet<unsigned, 4> &Redefs,
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001478 bool IgnoreBr) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001479 MachineFunction &MF = *ToBBI.BB->getParent();
1480
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001481 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1482 E = FromBBI.BB->end(); I != E; ++I) {
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001483 // Do not copy the end of the block branches.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001484 if (IgnoreBr && I->isBranch())
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001485 break;
1486
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001487 MachineInstr *MI = MF.CloneMachineInstr(I);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001488 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilson2ad40d32010-10-26 00:02:21 +00001489 ToBBI.NonPredSize++;
Evan Cheng8239daf2010-11-03 00:45:17 +00001490 unsigned ExtraPredCost = 0;
1491 unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I, &ExtraPredCost);
1492 if (NumCycles > 1)
1493 ToBBI.ExtraCost += NumCycles-1;
1494 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001495
Bob Wilsonf50e9522010-06-18 17:07:23 +00001496 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001497 if (!TII->PredicateInstruction(MI, Cond)) {
Torok Edwinf3689232009-07-12 20:07:01 +00001498#ifndef NDEBUG
David Greene083b7ff2010-01-04 22:02:01 +00001499 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwinf3689232009-07-12 20:07:01 +00001500#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001501 llvm_unreachable(0);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001502 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001503 }
1504
Bob Wilson54eee522010-06-19 05:33:57 +00001505 // If the predicated instruction now redefines a register as the result of
Evan Cheng46df4eb2010-06-16 07:35:02 +00001506 // if-conversion, add an implicit kill.
1507 UpdatePredRedefs(MI, Redefs, TRI, true);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001508 }
1509
Bob Wilson8eab75f2010-06-29 00:55:23 +00001510 if (!IgnoreBr) {
1511 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1512 FromBBI.BB->succ_end());
1513 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1514 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
Evan Chengc4047a82007-06-18 22:44:57 +00001515
Bob Wilson8eab75f2010-06-29 00:55:23 +00001516 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1517 MachineBasicBlock *Succ = Succs[i];
1518 // Fallthrough edge can't be transferred.
1519 if (Succ == FallThrough)
1520 continue;
1521 ToBBI.BB->addSuccessor(Succ);
1522 }
Evan Chengc4047a82007-06-18 22:44:57 +00001523 }
1524
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001525 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1526 std::back_inserter(ToBBI.Predicate));
1527 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1528
1529 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1530 ToBBI.IsAnalyzed = false;
1531
Dan Gohmanfe601042010-06-22 15:08:57 +00001532 ++NumDupBBs;
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001533}
1534
Evan Cheng86cbfea2007-05-18 00:20:58 +00001535/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson8eab75f2010-06-29 00:55:23 +00001536/// This will leave FromBB as an empty block, so remove all of its
1537/// successor edges except for the fall-through edge. If AddEdges is true,
1538/// i.e., when FromBBI's branch is being moved, add those successor edges to
1539/// ToBBI.
1540void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng86cbfea2007-05-18 00:20:58 +00001541 ToBBI.BB->splice(ToBBI.BB->end(),
1542 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +00001543
Evan Chengd4de6d92007-06-07 02:12:15 +00001544 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1545 FromBBI.BB->succ_end());
Evan Cheng7e75ba82007-06-08 22:01:07 +00001546 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001547 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
Evan Chengb6665f62007-06-04 06:47:22 +00001548
Evan Chengd4de6d92007-06-07 02:12:15 +00001549 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1550 MachineBasicBlock *Succ = Succs[i];
Evan Cheng7e75ba82007-06-08 22:01:07 +00001551 // Fallthrough edge can't be transferred.
Evan Chengd4de6d92007-06-07 02:12:15 +00001552 if (Succ == FallThrough)
1553 continue;
1554 FromBBI.BB->removeSuccessor(Succ);
Bob Wilson8eab75f2010-06-29 00:55:23 +00001555 if (AddEdges)
1556 ToBBI.BB->addSuccessor(Succ);
Evan Chengd4de6d92007-06-07 02:12:15 +00001557 }
1558
Bob Wilson9c4856a2009-05-13 23:25:24 +00001559 // Now FromBBI always falls through to the next block!
Bob Wilson8308e8f2009-05-13 23:48:58 +00001560 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng7e75ba82007-06-08 22:01:07 +00001561 FromBBI.BB->addSuccessor(NBB);
1562
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001563 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1564 std::back_inserter(ToBBI.Predicate));
1565 FromBBI.Predicate.clear();
1566
Evan Chenga13aa952007-05-23 07:23:16 +00001567 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilson2ad40d32010-10-26 00:02:21 +00001568 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Cheng8239daf2010-11-03 00:45:17 +00001569 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chenga13aa952007-05-23 07:23:16 +00001570 FromBBI.NonPredSize = 0;
Bob Wilson2ad40d32010-10-26 00:02:21 +00001571 FromBBI.ExtraCost = 0;
Evan Cheng8239daf2010-11-03 00:45:17 +00001572 FromBBI.ExtraCost2 = 0;
Evan Cheng7a655472007-06-06 10:16:17 +00001573
Evan Cheng9618bca2007-06-11 22:26:22 +00001574 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001575 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng86ff2962007-06-14 20:28:52 +00001576 ToBBI.IsAnalyzed = false;
1577 FromBBI.IsAnalyzed = false;
Evan Cheng4e654852007-05-16 02:00:57 +00001578}