blob: 1302ec2cd2166ad4e498a096e1bd2d41b6c6073f [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//
5// This file was developed by the Evan Cheng and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
15#include "llvm/Function.h"
Evan Cheng4e654852007-05-16 02:00:57 +000016#include "llvm/CodeGen/Passes.h"
17#include "llvm/CodeGen/MachineModuleInfo.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng86cbfea2007-05-18 00:20:58 +000020#include "llvm/Target/TargetLowering.h"
Evan Cheng4e654852007-05-16 02:00:57 +000021#include "llvm/Target/TargetMachine.h"
Evan Chengedf48962007-06-08 19:10:51 +000022#include "llvm/Support/CommandLine.h"
Evan Cheng4e654852007-05-16 02:00:57 +000023#include "llvm/Support/Debug.h"
Evan Cheng36489bb2007-05-18 19:26:33 +000024#include "llvm/ADT/DepthFirstIterator.h"
Evan Cheng4e654852007-05-16 02:00:57 +000025#include "llvm/ADT/Statistic.h"
26using namespace llvm;
27
Evan Chengedf48962007-06-08 19:10:51 +000028namespace {
29 // Hidden options for help debugging.
30 cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
31 cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
32 cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
33 cl::opt<bool> DisableSimple("disable-ifcvt-simple",
34 cl::init(false), cl::Hidden);
35 cl::opt<bool> DisableSimpleFalse("disable-ifcvt-simple-false",
36 cl::init(false), cl::Hidden);
37 cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
38 cl::init(false), cl::Hidden);
39 cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
40 cl::init(false), cl::Hidden);
41}
42
Evan Chengb6665f62007-06-04 06:47:22 +000043STATISTIC(NumSimple, "Number of simple if-conversions performed");
44STATISTIC(NumSimpleRev, "Number of simple (reversed) if-conversions performed");
45STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
46STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
Evan Cheng4e654852007-05-16 02:00:57 +000047STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
48
49namespace {
50 class IfConverter : public MachineFunctionPass {
51 enum BBICKind {
Evan Chenga13aa952007-05-23 07:23:16 +000052 ICNotAnalyzed, // BB has not been analyzed.
53 ICReAnalyze, // BB must be re-analyzed.
Evan Cheng4e654852007-05-16 02:00:57 +000054 ICNotClassfied, // BB data valid, but not classified.
Evan Chengb6665f62007-06-04 06:47:22 +000055 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
56 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Chenga6b4f432007-05-21 22:22:58 +000057 ICTriangle, // BB is entry of a triangle sub-CFG.
58 ICDiamond, // BB is entry of a diamond sub-CFG.
59 ICChild, // BB is part of the sub-CFG that'll be predicated.
Evan Cheng7a655472007-06-06 10:16:17 +000060 ICDead // BB cannot be if-converted again.
Evan Cheng4e654852007-05-16 02:00:57 +000061 };
62
63 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
64 /// if-conversion feasibility analysis. This includes results from
65 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng86cbfea2007-05-18 00:20:58 +000066 /// classification, and common tail block of its successors (if it's a
Evan Chengcf6cc112007-05-18 18:14:37 +000067 /// diamond shape), its size, whether it's predicable, and whether any
68 /// instruction can clobber the 'would-be' predicate.
Evan Chenga13aa952007-05-23 07:23:16 +000069 ///
70 /// Kind - Type of block. See BBICKind.
71 /// NonPredSize - Number of non-predicated instructions.
Evan Chengb6665f62007-06-04 06:47:22 +000072 /// IsAnalyzable - True if AnalyzeBranch() returns false.
Evan Cheng7a655472007-06-06 10:16:17 +000073 /// ModifyPredicate - True if BB would modify the predicate (e.g. has
74 /// cmp, call, etc.)
Evan Chenga13aa952007-05-23 07:23:16 +000075 /// BB - Corresponding MachineBasicBlock.
76 /// TrueBB / FalseBB- See AnalyzeBranch().
77 /// BrCond - Conditions for end of block conditional branches.
78 /// Predicate - Predicate used in the BB.
Evan Cheng4e654852007-05-16 02:00:57 +000079 struct BBInfo {
80 BBICKind Kind;
Evan Chenga13aa952007-05-23 07:23:16 +000081 unsigned NonPredSize;
Evan Chengb6665f62007-06-04 06:47:22 +000082 bool IsAnalyzable;
Evan Chengd4de6d92007-06-07 02:12:15 +000083 bool hasFallThrough;
Evan Chenga13aa952007-05-23 07:23:16 +000084 bool ModifyPredicate;
Evan Cheng86cbfea2007-05-18 00:20:58 +000085 MachineBasicBlock *BB;
86 MachineBasicBlock *TrueBB;
87 MachineBasicBlock *FalseBB;
88 MachineBasicBlock *TailBB;
Evan Chenga13aa952007-05-23 07:23:16 +000089 std::vector<MachineOperand> BrCond;
90 std::vector<MachineOperand> Predicate;
Evan Chengb6665f62007-06-04 06:47:22 +000091 BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0),
Evan Chengd4de6d92007-06-07 02:12:15 +000092 IsAnalyzable(false), hasFallThrough(false),
93 ModifyPredicate(false),
Evan Chenga6b4f432007-05-21 22:22:58 +000094 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
Evan Cheng4e654852007-05-16 02:00:57 +000095 };
96
Evan Cheng82582102007-05-30 19:49:19 +000097 /// Roots - Basic blocks that do not have successors. These are the starting
98 /// points of Graph traversal.
99 std::vector<MachineBasicBlock*> Roots;
100
Evan Cheng4e654852007-05-16 02:00:57 +0000101 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
102 /// basic block number.
103 std::vector<BBInfo> BBAnalysis;
104
Evan Cheng86cbfea2007-05-18 00:20:58 +0000105 const TargetLowering *TLI;
Evan Cheng4e654852007-05-16 02:00:57 +0000106 const TargetInstrInfo *TII;
107 bool MadeChange;
108 public:
109 static char ID;
110 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
111
112 virtual bool runOnMachineFunction(MachineFunction &MF);
113 virtual const char *getPassName() const { return "If converter"; }
114
115 private:
Evan Chengb6665f62007-06-04 06:47:22 +0000116 bool ReverseBranchCondition(BBInfo &BBI);
Evan Chengac5f1422007-06-08 09:36:04 +0000117 bool ValidSimple(BBInfo &TrueBBI) const;
118 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
119 bool FalseBranch = false) const;
Evan Chengd4de6d92007-06-07 02:12:15 +0000120 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
Evan Chengac5f1422007-06-08 09:36:04 +0000121 void ScanInstructions(BBInfo &BBI);
122 void AnalyzeBlock(MachineBasicBlock *BB);
123 bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
124 bool isTriangle = false, bool RevBranch = false);
Evan Cheng82582102007-05-30 19:49:19 +0000125 bool AttemptRestructuring(BBInfo &BBI);
126 bool AnalyzeBlocks(MachineFunction &MF,
Evan Chenga13aa952007-05-23 07:23:16 +0000127 std::vector<BBInfo*> &Candidates);
Evan Cheng82582102007-05-30 19:49:19 +0000128 void ReTryPreds(MachineBasicBlock *BB);
Evan Cheng7e75ba82007-06-08 22:01:07 +0000129 void RemoveExtraEdges(BBInfo &BBI);
Evan Chengb6665f62007-06-04 06:47:22 +0000130 bool IfConvertSimple(BBInfo &BBI);
Evan Cheng4e654852007-05-16 02:00:57 +0000131 bool IfConvertTriangle(BBInfo &BBI);
Evan Chengcf6cc112007-05-18 18:14:37 +0000132 bool IfConvertDiamond(BBInfo &BBI);
Evan Chenga13aa952007-05-23 07:23:16 +0000133 void PredicateBlock(BBInfo &BBI,
Evan Cheng4e654852007-05-16 02:00:57 +0000134 std::vector<MachineOperand> &Cond,
135 bool IgnoreTerm = false);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000136 void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
Evan Cheng5f702182007-06-01 00:12:12 +0000137
Evan Chengd4de6d92007-06-07 02:12:15 +0000138 // blockAlwaysFallThrough - Block ends without a terminator.
139 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Evan Cheng7a655472007-06-06 10:16:17 +0000140 return BBI.IsAnalyzable && BBI.TrueBB == NULL;
141 }
142
Evan Cheng5f702182007-06-01 00:12:12 +0000143 // IfcvtCandidateCmp - Used to sort if-conversion candidates.
144 static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
145 // Favor diamond over triangle, etc.
146 return (unsigned)C1->Kind < (unsigned)C2->Kind;
147 }
Evan Cheng4e654852007-05-16 02:00:57 +0000148 };
149 char IfConverter::ID = 0;
150}
151
152FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
153
154bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng86cbfea2007-05-18 00:20:58 +0000155 TLI = MF.getTarget().getTargetLowering();
Evan Cheng4e654852007-05-16 02:00:57 +0000156 TII = MF.getTarget().getInstrInfo();
157 if (!TII) return false;
158
Evan Chengedf48962007-06-08 19:10:51 +0000159 static int FnNum = -1;
160 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'"
161 << MF.getFunction()->getName() << "\'";
162
163 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
164 DOUT << " skipped\n";
165 return false;
166 }
167 DOUT << "\n";
Evan Cheng5f702182007-06-01 00:12:12 +0000168
Evan Cheng4e654852007-05-16 02:00:57 +0000169 MF.RenumberBlocks();
Evan Cheng5f702182007-06-01 00:12:12 +0000170 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Cheng4e654852007-05-16 02:00:57 +0000171
Evan Cheng82582102007-05-30 19:49:19 +0000172 // Look for root nodes, i.e. blocks without successors.
173 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
174 if (I->succ_size() == 0)
175 Roots.push_back(I);
176
Evan Cheng7f8ff8a2007-05-18 19:32:08 +0000177 std::vector<BBInfo*> Candidates;
Evan Cheng47d25022007-05-18 01:55:58 +0000178 MadeChange = false;
Evan Chengedf48962007-06-08 19:10:51 +0000179 while (IfCvtLimit == -1 || (int)NumIfConvBBs < IfCvtLimit) {
Evan Chenga13aa952007-05-23 07:23:16 +0000180 // Do an intial analysis for each basic block and finding all the potential
181 // candidates to perform if-convesion.
Evan Chengb6665f62007-06-04 06:47:22 +0000182 bool Change = AnalyzeBlocks(MF, Candidates);
Evan Chenga13aa952007-05-23 07:23:16 +0000183 while (!Candidates.empty()) {
184 BBInfo &BBI = *Candidates.back();
185 Candidates.pop_back();
Evan Chengb6665f62007-06-04 06:47:22 +0000186
187 bool RetVal = false;
Evan Chenga13aa952007-05-23 07:23:16 +0000188 switch (BBI.Kind) {
189 default: assert(false && "Unexpected!");
190 break;
Evan Cheng5f702182007-06-01 00:12:12 +0000191 case ICReAnalyze:
Evan Chengf5305f92007-06-05 00:07:37 +0000192 // One or more of 'children' have been modified, abort!
193 case ICDead:
194 // Block has been already been if-converted, abort!
Evan Cheng5f702182007-06-01 00:12:12 +0000195 break;
Evan Chengb6665f62007-06-04 06:47:22 +0000196 case ICSimple:
Evan Chengcb78d672007-06-06 01:12:44 +0000197 case ICSimpleFalse: {
198 bool isRev = BBI.Kind == ICSimpleFalse;
Evan Chengedf48962007-06-08 19:10:51 +0000199 if ((isRev && DisableSimpleFalse) || (!isRev && DisableSimple)) break;
Evan Chengb6665f62007-06-04 06:47:22 +0000200 DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
Evan Cheng7a655472007-06-06 10:16:17 +0000201 << "): BB#" << BBI.BB->getNumber() << " ("
202 << ((BBI.Kind == ICSimpleFalse)
203 ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
Evan Chengb6665f62007-06-04 06:47:22 +0000204 RetVal = IfConvertSimple(BBI);
205 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
206 if (RetVal)
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000207 if (isRev) NumSimpleRev++;
208 else NumSimple++;
Evan Chengb6665f62007-06-04 06:47:22 +0000209 break;
Evan Chengcb78d672007-06-06 01:12:44 +0000210 }
Evan Chenga13aa952007-05-23 07:23:16 +0000211 case ICTriangle:
Evan Chengedf48962007-06-08 19:10:51 +0000212 if (DisableTriangle) break;
Evan Cheng7a655472007-06-06 10:16:17 +0000213 DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << " (T:"
214 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
215 << ") ";
Evan Chengb6665f62007-06-04 06:47:22 +0000216 RetVal = IfConvertTriangle(BBI);
217 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
218 if (RetVal) NumTriangle++;
Evan Chenga13aa952007-05-23 07:23:16 +0000219 break;
220 case ICDiamond:
Evan Chengedf48962007-06-08 19:10:51 +0000221 if (DisableDiamond) break;
Evan Cheng7a655472007-06-06 10:16:17 +0000222 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
223 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
224 if (BBI.TailBB)
225 DOUT << "," << BBI.TailBB->getNumber() ;
226 DOUT << ") ";
Evan Chengb6665f62007-06-04 06:47:22 +0000227 RetVal = IfConvertDiamond(BBI);
228 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
229 if (RetVal) NumDiamonds++;
Evan Chenga13aa952007-05-23 07:23:16 +0000230 break;
231 }
Evan Chengb6665f62007-06-04 06:47:22 +0000232 Change |= RetVal;
Evan Chengedf48962007-06-08 19:10:51 +0000233
234 if (IfCvtLimit != -1 && (int)NumIfConvBBs > IfCvtLimit)
235 break;
Evan Cheng4e654852007-05-16 02:00:57 +0000236 }
Evan Chenga13aa952007-05-23 07:23:16 +0000237
Evan Chenga13aa952007-05-23 07:23:16 +0000238 if (!Change)
239 break;
Evan Chengb6665f62007-06-04 06:47:22 +0000240 MadeChange |= Change;
Evan Cheng4e654852007-05-16 02:00:57 +0000241 }
Evan Cheng47d25022007-05-18 01:55:58 +0000242
Evan Cheng82582102007-05-30 19:49:19 +0000243 Roots.clear();
Evan Cheng47d25022007-05-18 01:55:58 +0000244 BBAnalysis.clear();
245
Evan Cheng4e654852007-05-16 02:00:57 +0000246 return MadeChange;
247}
248
249static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng86cbfea2007-05-18 00:20:58 +0000250 MachineBasicBlock *TrueBB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000251 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
252 E = BB->succ_end(); SI != E; ++SI) {
253 MachineBasicBlock *SuccBB = *SI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000254 if (SuccBB != TrueBB)
Evan Cheng4e654852007-05-16 02:00:57 +0000255 return SuccBB;
256 }
257 return NULL;
258}
259
Evan Chengb6665f62007-06-04 06:47:22 +0000260bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
261 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
262 TII->RemoveBranch(*BBI.BB);
263 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
264 std::swap(BBI.TrueBB, BBI.FalseBB);
265 return true;
266 }
267 return false;
268}
269
Evan Chengac5f1422007-06-08 09:36:04 +0000270/// ValidSimple - Returns true if the 'true' block (along with its
271/// predecessor) forms a valid simple shape for ifcvt.
272bool IfConverter::ValidSimple(BBInfo &TrueBBI) const {
273 return !blockAlwaysFallThrough(TrueBBI) &&
274 TrueBBI.BrCond.size() == 0 && TrueBBI.BB->pred_size() == 1;
Evan Cheng7a655472007-06-06 10:16:17 +0000275}
276
Evan Chengac5f1422007-06-08 09:36:04 +0000277/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000278/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Chengac5f1422007-06-08 09:36:04 +0000279bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
280 bool FalseBranch) const {
Evan Chengd4de6d92007-06-07 02:12:15 +0000281 if (TrueBBI.BB->pred_size() != 1)
282 return false;
283
Evan Chengac5f1422007-06-08 09:36:04 +0000284 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
285 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Evan Chengd4de6d92007-06-07 02:12:15 +0000286 MachineFunction::iterator I = TrueBBI.BB;
287 if (++I == TrueBBI.BB->getParent()->end())
288 return false;
Evan Chengac5f1422007-06-08 09:36:04 +0000289 TExit = I;
Evan Chengd4de6d92007-06-07 02:12:15 +0000290 }
Evan Chengac5f1422007-06-08 09:36:04 +0000291 return TExit && TExit == FalseBBI.BB;
Evan Chengd4de6d92007-06-07 02:12:15 +0000292}
293
Evan Chengac5f1422007-06-08 09:36:04 +0000294/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000295/// with their common predecessor) forms a valid diamond shape for ifcvt.
296bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
Evan Chengac5f1422007-06-08 09:36:04 +0000297 // FIXME: Also look for fallthrough
Evan Chengd4de6d92007-06-07 02:12:15 +0000298 return (TrueBBI.TrueBB == FalseBBI.TrueBB &&
299 TrueBBI.BB->pred_size() == 1 &&
300 FalseBBI.BB->pred_size() == 1 &&
Evan Chengd4de6d92007-06-07 02:12:15 +0000301 !TrueBBI.FalseBB && !FalseBBI.FalseBB);
302}
303
Evan Chengac5f1422007-06-08 09:36:04 +0000304/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Chengcf6cc112007-05-18 18:14:37 +0000305/// the specified block. Record its successors and whether it looks like an
306/// if-conversion candidate.
Evan Chengac5f1422007-06-08 09:36:04 +0000307void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000308 BBInfo &BBI = BBAnalysis[BB->getNumber()];
309
Evan Chengf5305f92007-06-05 00:07:37 +0000310 if (BBI.Kind == ICReAnalyze) {
Evan Chengb6665f62007-06-04 06:47:22 +0000311 BBI.BrCond.clear();
Evan Chengf5305f92007-06-05 00:07:37 +0000312 BBI.TrueBB = BBI.FalseBB = NULL;
313 } else {
Evan Chenga13aa952007-05-23 07:23:16 +0000314 if (BBI.Kind != ICNotAnalyzed)
315 return; // Already analyzed.
316 BBI.BB = BB;
317 BBI.NonPredSize = std::distance(BB->begin(), BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +0000318 }
Evan Cheng86cbfea2007-05-18 00:20:58 +0000319
Evan Cheng4bec8ae2007-05-25 00:59:01 +0000320 // Look for 'root' of a simple (non-nested) triangle or diamond.
321 BBI.Kind = ICNotClassfied;
Evan Chengb6665f62007-06-04 06:47:22 +0000322 BBI.IsAnalyzable =
323 !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Evan Chengd4de6d92007-06-07 02:12:15 +0000324 BBI.hasFallThrough = BBI.IsAnalyzable && BBI.FalseBB == NULL;
325 // Unanalyable or ends with fallthrough or unconditional branch.
Evan Chengb6665f62007-06-04 06:47:22 +0000326 if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
Evan Cheng4bec8ae2007-05-25 00:59:01 +0000327 return;
Evan Chenge0043172007-06-05 20:38:42 +0000328 // Do not ifcvt if either path is a back edge to the entry block.
329 if (BBI.TrueBB == BB || BBI.FalseBB == BB)
330 return;
Evan Cheng4bec8ae2007-05-25 00:59:01 +0000331
Evan Chengac5f1422007-06-08 09:36:04 +0000332 AnalyzeBlock(BBI.TrueBB);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000333 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Chengd6ddc302007-05-16 21:54:37 +0000334
335 // No false branch. This BB must end with a conditional branch and a
336 // fallthrough.
Evan Cheng86cbfea2007-05-18 00:20:58 +0000337 if (!BBI.FalseBB)
338 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
339 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
Evan Chengc5d05ef2007-05-16 05:11:10 +0000340
Evan Chengac5f1422007-06-08 09:36:04 +0000341 AnalyzeBlock(BBI.FalseBB);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000342 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng7a655472007-06-06 10:16:17 +0000343
344 // If both paths are dead, then forget about it.
345 if (TrueBBI.Kind == ICDead && FalseBBI.Kind == ICDead) {
346 BBI.Kind = ICDead;
347 return;
348 }
349
Evan Chengb6665f62007-06-04 06:47:22 +0000350 // Look for more opportunities to if-convert a triangle. Try to restructure
351 // the CFG to form a triangle with the 'false' path.
352 std::vector<MachineOperand> RevCond(BBI.BrCond);
353 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
Evan Chengac5f1422007-06-08 09:36:04 +0000354
355 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
356 !(TrueBBI.ModifyPredicate && FalseBBI.ModifyPredicate) &&
357 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
358 FeasibilityAnalysis(FalseBBI, RevCond)) {
Evan Cheng4e654852007-05-16 02:00:57 +0000359 // Diamond:
360 // EBB
361 // / \_
362 // | |
363 // TBB FBB
364 // \ /
Evan Cheng86cbfea2007-05-18 00:20:58 +0000365 // TailBB
Evan Cheng993fc952007-06-05 23:46:14 +0000366 // Note TailBB can be empty.
Evan Chenga6b4f432007-05-21 22:22:58 +0000367 BBI.Kind = ICDiamond;
368 TrueBBI.Kind = FalseBBI.Kind = ICChild;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000369 BBI.TailBB = TrueBBI.TrueBB;
Evan Chengb6665f62007-06-04 06:47:22 +0000370 } else {
371 // FIXME: Consider duplicating if BB is small.
Evan Chengac5f1422007-06-08 09:36:04 +0000372 if (ValidTriangle(TrueBBI, FalseBBI) &&
373 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
374 // Triangle:
375 // EBB
376 // | \_
377 // | |
378 // | TBB
379 // | /
380 // FBB
381 BBI.Kind = ICTriangle;
382 TrueBBI.Kind = ICChild;
383 } else if (ValidSimple(TrueBBI) &&
384 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
385 // Simple (split, no rejoin):
386 // EBB
387 // | \_
388 // | |
389 // | TBB---> exit
390 // |
391 // FBB
392 BBI.Kind = ICSimple;
393 TrueBBI.Kind = ICChild;
394 } else if (CanRevCond) {
Evan Chenge7052132007-06-06 00:57:55 +0000395 // Try the other path...
Evan Chengac5f1422007-06-08 09:36:04 +0000396 if (ValidTriangle(FalseBBI, TrueBBI) &&
397 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
398 // Reverse 'true' and 'false' paths.
399 ReverseBranchCondition(BBI);
400 BBI.Kind = ICTriangle;
401 FalseBBI.Kind = ICChild;
402 } else if (ValidTriangle(FalseBBI, TrueBBI, true) &&
403 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
404 ReverseBranchCondition(FalseBBI);
405 ReverseBranchCondition(BBI);
406 BBI.Kind = ICTriangle;
407 FalseBBI.Kind = ICChild;
408 } else if (ValidSimple(FalseBBI) &&
409 FeasibilityAnalysis(FalseBBI, RevCond)) {
410 BBI.Kind = ICSimpleFalse;
411 FalseBBI.Kind = ICChild;
Evan Chengb6665f62007-06-04 06:47:22 +0000412 }
413 }
Evan Cheng4e654852007-05-16 02:00:57 +0000414 }
415 return;
416}
417
Evan Chengcf6cc112007-05-18 18:14:37 +0000418/// FeasibilityAnalysis - Determine if the block is predicable. In most
419/// cases, that means all the instructions in the block has M_PREDICABLE flag.
420/// Also checks if the block contains any instruction which can clobber a
421/// predicate (e.g. condition code register). If so, the block is not
Evan Chengac5f1422007-06-08 09:36:04 +0000422/// predicable unless it's the last instruction.
Evan Chengb6665f62007-06-04 06:47:22 +0000423bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Evan Chengac5f1422007-06-08 09:36:04 +0000424 std::vector<MachineOperand> &Pred,
425 bool isTriangle, bool RevBranch) {
Evan Chengb6665f62007-06-04 06:47:22 +0000426 // If the block is dead, or it is going to be the entry block of a sub-CFG
427 // that will be if-converted, then it cannot be predicated.
428 if (BBI.Kind != ICNotAnalyzed &&
429 BBI.Kind != ICNotClassfied &&
430 BBI.Kind != ICChild)
431 return false;
432
433 // Check predication threshold.
Evan Chenga13aa952007-05-23 07:23:16 +0000434 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
Evan Chengb6665f62007-06-04 06:47:22 +0000435 return false;
436
437 // If it is already predicated, check if its predicate subsumes the new
438 // predicate.
Evan Chengac5f1422007-06-08 09:36:04 +0000439 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
Evan Chengb6665f62007-06-04 06:47:22 +0000440 return false;
Evan Chengcf6cc112007-05-18 18:14:37 +0000441
Evan Chengac5f1422007-06-08 09:36:04 +0000442 bool SeenPredMod = false;
443 bool SeenCondBr = false;
Evan Chengcf6cc112007-05-18 18:14:37 +0000444 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
445 I != E; ++I) {
Evan Chengac5f1422007-06-08 09:36:04 +0000446 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
447 if (SeenPredMod) {
448 // Predicate modification instruction should end the block (except for
449 // already predicated instructions and end of block branches).
450 if (!TII->isPredicated(I)) {
451 // This is the 'true' block of a triangle, i.e. its 'true' block is
452 // the same as the 'false' block of the entry. So false positive
453 // is ok.
454 if (isTriangle && !SeenCondBr && BBI.IsAnalyzable &&
455 (TID->Flags & M_BRANCH_FLAG) != 0 &&
456 (TID->Flags & M_BARRIER_FLAG) == 0) {
457 // This is the first conditional branch, test predicate subsumsion.
458 std::vector<MachineOperand> RevPred(Pred);
459 std::vector<MachineOperand> Cond(BBI.BrCond);
460 if (RevBranch) {
461 if (TII->ReverseBranchCondition(Cond))
462 return false;
463 }
464 if (TII->ReverseBranchCondition(RevPred) ||
465 !TII->SubsumesPredicate(Cond, RevPred))
466 return false;
467 SeenCondBr = true;
468 continue; // Conditional branches is not predicable.
469 }
470 return false;
471 }
472 }
473
474 if (TID->Flags & M_CLOBBERS_PRED) {
475 BBI.ModifyPredicate = true;
476 SeenPredMod = true;
477 }
478
Evan Chengcf6cc112007-05-18 18:14:37 +0000479 if (!I->isPredicable())
Evan Chengb6665f62007-06-04 06:47:22 +0000480 return false;
Evan Chengcf6cc112007-05-18 18:14:37 +0000481 }
482
Evan Chengb6665f62007-06-04 06:47:22 +0000483 return true;
Evan Chengcf6cc112007-05-18 18:14:37 +0000484}
485
Evan Cheng82582102007-05-30 19:49:19 +0000486/// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
487/// expose more if-conversion opportunities. e.g.
488///
489/// cmp
490/// b le BB1
491/// / \____
492/// / |
493/// cmp |
494/// b eq BB1 |
495/// / \____ |
496/// / \ |
497/// BB1
498/// ==>
499///
500/// cmp
501/// b eq BB1
502/// / \____
503/// / |
504/// cmp |
505/// b le BB1 |
506/// / \____ |
507/// / \ |
508/// BB1
509bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
510 return false;
511}
512
513/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
514/// candidates. It returns true if any CFG restructuring is done to expose more
515/// if-conversion opportunities.
516bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Chenga13aa952007-05-23 07:23:16 +0000517 std::vector<BBInfo*> &Candidates) {
Evan Cheng82582102007-05-30 19:49:19 +0000518 bool Change = false;
Evan Cheng36489bb2007-05-18 19:26:33 +0000519 std::set<MachineBasicBlock*> Visited;
Evan Cheng82582102007-05-30 19:49:19 +0000520 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
521 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
522 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
523 MachineBasicBlock *BB = *I;
Evan Chengac5f1422007-06-08 09:36:04 +0000524 AnalyzeBlock(BB);
Evan Cheng82582102007-05-30 19:49:19 +0000525 BBInfo &BBI = BBAnalysis[BB->getNumber()];
526 switch (BBI.Kind) {
Evan Chengb6665f62007-06-04 06:47:22 +0000527 case ICSimple:
528 case ICSimpleFalse:
Evan Cheng82582102007-05-30 19:49:19 +0000529 case ICTriangle:
530 case ICDiamond:
531 Candidates.push_back(&BBI);
532 break;
533 default:
534 Change |= AttemptRestructuring(BBI);
535 break;
536 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000537 }
Evan Cheng4e654852007-05-16 02:00:57 +0000538 }
Evan Cheng82582102007-05-30 19:49:19 +0000539
Evan Cheng5f702182007-06-01 00:12:12 +0000540 // Sort to favor more complex ifcvt scheme.
541 std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
542
Evan Cheng82582102007-05-30 19:49:19 +0000543 return Change;
Evan Cheng4e654852007-05-16 02:00:57 +0000544}
545
Evan Cheng7e75ba82007-06-08 22:01:07 +0000546/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
547/// that all the intervening blocks are empty (given BB can fall through to its
548/// next block).
549static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Chengb6665f62007-06-04 06:47:22 +0000550 MachineFunction::iterator I = BB;
Evan Chengc53ef582007-06-05 07:05:25 +0000551 MachineFunction::iterator TI = ToBB;
552 MachineFunction::iterator E = BB->getParent()->end();
553 while (++I != TI)
554 if (I == E || !I->empty())
Evan Chengb6665f62007-06-04 06:47:22 +0000555 return false;
556 return true;
Evan Chenga6b4f432007-05-21 22:22:58 +0000557}
558
Evan Cheng7e75ba82007-06-08 22:01:07 +0000559/// getNextBlock - Returns the next block in the function blocks ordering. If
560/// it is the end, returns NULL.
561static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
562 MachineFunction::iterator I = BB;
563 MachineFunction::iterator E = BB->getParent()->end();
564 if (++I == E)
565 return NULL;
566 return I;
567}
568
Evan Cheng82582102007-05-30 19:49:19 +0000569/// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
Evan Chenga13aa952007-05-23 07:23:16 +0000570/// to determine if it can be if-converted.
Evan Cheng82582102007-05-30 19:49:19 +0000571void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
Evan Chenga13aa952007-05-23 07:23:16 +0000572 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
573 E = BB->pred_end(); PI != E; ++PI) {
574 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
Evan Cheng7e75ba82007-06-08 22:01:07 +0000575 if (PBBI.Kind == ICNotClassfied)
576 PBBI.Kind = ICReAnalyze;
Evan Chenga13aa952007-05-23 07:23:16 +0000577 }
578}
579
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000580/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
581///
582static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
583 const TargetInstrInfo *TII) {
584 std::vector<MachineOperand> NoCond;
585 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
586}
587
Evan Cheng7e75ba82007-06-08 22:01:07 +0000588/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
589/// successors.
590void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
591 MachineBasicBlock *TBB = NULL, *FBB = NULL;
592 std::vector<MachineOperand> Cond;
593 bool isAnalyzable = !TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond);
594 bool CanFallthrough = isAnalyzable && (TBB == NULL || FBB == NULL);
595 if (BBI.TrueBB && BBI.BB->isSuccessor(BBI.TrueBB))
596 if (!(BBI.TrueBB == TBB || BBI.TrueBB == FBB ||
597 (CanFallthrough && getNextBlock(BBI.BB) == BBI.TrueBB)))
598 BBI.BB->removeSuccessor(BBI.TrueBB);
599 if (BBI.FalseBB && BBI.BB->isSuccessor(BBI.FalseBB))
600 if (!(BBI.FalseBB == TBB || BBI.FalseBB == FBB ||
601 (CanFallthrough && getNextBlock(BBI.BB) == BBI.FalseBB)))
602 BBI.BB->removeSuccessor(BBI.FalseBB);
603}
604
Evan Chengb6665f62007-06-04 06:47:22 +0000605/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenga6b4f432007-05-21 22:22:58 +0000606///
Evan Chengb6665f62007-06-04 06:47:22 +0000607bool IfConverter::IfConvertSimple(BBInfo &BBI) {
Evan Chenga6b4f432007-05-21 22:22:58 +0000608 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
609 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
610 BBInfo *CvtBBI = &TrueBBI;
611 BBInfo *NextBBI = &FalseBBI;
Evan Chenga13aa952007-05-23 07:23:16 +0000612
Evan Chengb6665f62007-06-04 06:47:22 +0000613 std::vector<MachineOperand> Cond(BBI.BrCond);
Evan Cheng7a655472007-06-06 10:16:17 +0000614 if (BBI.Kind == ICSimpleFalse) {
Evan Chengb5a06902007-06-01 20:29:21 +0000615 std::swap(CvtBBI, NextBBI);
Evan Chengb6665f62007-06-04 06:47:22 +0000616 TII->ReverseBranchCondition(Cond);
Evan Chengb5a06902007-06-01 20:29:21 +0000617 }
Evan Chenga13aa952007-05-23 07:23:16 +0000618
Evan Chengb6665f62007-06-04 06:47:22 +0000619 PredicateBlock(*CvtBBI, Cond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000620
Evan Cheng7e75ba82007-06-08 22:01:07 +0000621 // Merge converted block into entry block.
Evan Chenga13aa952007-05-23 07:23:16 +0000622 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000623 MergeBlocks(BBI, *CvtBBI);
Evan Chengd4de6d92007-06-07 02:12:15 +0000624
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000625 bool IterIfcvt = true;
Evan Cheng7e75ba82007-06-08 22:01:07 +0000626 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000627 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Chengd4de6d92007-06-07 02:12:15 +0000628 BBI.hasFallThrough = false;
Evan Chengac5f1422007-06-08 09:36:04 +0000629 // Now ifcvt'd block will look like this:
630 // BB:
631 // ...
632 // t, f = cmp
633 // if t op
634 // b BBf
635 //
636 // We cannot further ifcvt this block because the unconditional branch
637 // will have to be predicated on the new condition, that will not be
638 // available if cmp executes.
639 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000640 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000641
Evan Cheng7e75ba82007-06-08 22:01:07 +0000642 RemoveExtraEdges(BBI);
643
Evan Chenga13aa952007-05-23 07:23:16 +0000644 // Update block info. BB can be iteratively if-converted.
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000645 if (IterIfcvt)
646 BBI.Kind = ICReAnalyze;
Evan Cheng7a655472007-06-06 10:16:17 +0000647 else
648 BBI.Kind = ICDead;
Evan Cheng82582102007-05-30 19:49:19 +0000649 ReTryPreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000650 CvtBBI->Kind = ICDead;
651
652 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +0000653 return true;
654}
655
Evan Chengd6ddc302007-05-16 21:54:37 +0000656/// IfConvertTriangle - If convert a triangle sub-CFG.
657///
Evan Cheng4e654852007-05-16 02:00:57 +0000658bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
Evan Chenga13aa952007-05-23 07:23:16 +0000659 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng8c529382007-06-01 07:41:07 +0000660
Evan Chenga6b4f432007-05-21 22:22:58 +0000661 // Predicate the 'true' block after removing its branch.
Evan Chenga13aa952007-05-23 07:23:16 +0000662 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
663 PredicateBlock(TrueBBI, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000664
Evan Chengb6665f62007-06-04 06:47:22 +0000665 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng8ed680c2007-06-05 01:31:40 +0000666 bool HasEarlyExit = TrueBBI.FalseBB != NULL;
667 if (HasEarlyExit) {
Evan Cheng8c529382007-06-01 07:41:07 +0000668 std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
669 if (TII->ReverseBranchCondition(RevCond))
670 assert(false && "Unable to reverse branch condition!");
671 TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
672 }
673
Evan Chengac5f1422007-06-08 09:36:04 +0000674 // Now merge the entry of the triangle with the true block.
675 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
676 MergeBlocks(BBI, TrueBBI);
677
678 // Merge in the 'false' block if the 'false' block has no other
679 // predecessors. Otherwise, add a unconditional branch from to 'false'.
Evan Chenga6b4f432007-05-21 22:22:58 +0000680 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chengf5305f92007-06-05 00:07:37 +0000681 bool FalseBBDead = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000682 bool IterIfcvt = true;
Evan Cheng7e75ba82007-06-08 22:01:07 +0000683 bool isFallThrough = canFallThroughTo(BBI.BB, FalseBBI.BB);
Evan Chengf4769612007-06-07 08:13:00 +0000684 if (!isFallThrough) {
685 // Only merge them if the true block does not fallthrough to the false
686 // block. By not merging them, we make it possible to iteratively
687 // ifcvt the blocks.
Evan Chengac5f1422007-06-08 09:36:04 +0000688 if (!HasEarlyExit && FalseBBI.BB->pred_size() == 1) {
689 MergeBlocks(BBI, FalseBBI);
Evan Chengf4769612007-06-07 08:13:00 +0000690 FalseBBDead = true;
Evan Chengf4769612007-06-07 08:13:00 +0000691 } else {
Evan Chengac5f1422007-06-08 09:36:04 +0000692 InsertUncondBranch(BBI.BB, FalseBBI.BB, TII);
Evan Chengf4769612007-06-07 08:13:00 +0000693 TrueBBI.hasFallThrough = false;
Evan Chengf4769612007-06-07 08:13:00 +0000694 }
Evan Chengac5f1422007-06-08 09:36:04 +0000695 // Mixed predicated and unpredicated code. This cannot be iteratively
696 // predicated.
697 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000698 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000699
Evan Cheng7e75ba82007-06-08 22:01:07 +0000700 RemoveExtraEdges(BBI);
Evan Chenga6b4f432007-05-21 22:22:58 +0000701
Evan Chenga13aa952007-05-23 07:23:16 +0000702 // Update block info. BB can be iteratively if-converted.
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000703 if (IterIfcvt)
704 BBI.Kind = ICReAnalyze;
Evan Cheng7a655472007-06-06 10:16:17 +0000705 else
706 BBI.Kind = ICDead;
Evan Cheng82582102007-05-30 19:49:19 +0000707 ReTryPreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000708 TrueBBI.Kind = ICDead;
Evan Chengf5305f92007-06-05 00:07:37 +0000709 if (FalseBBDead)
710 FalseBBI.Kind = ICDead;
Evan Chenga6b4f432007-05-21 22:22:58 +0000711
712 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +0000713 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000714}
715
Evan Chengd6ddc302007-05-16 21:54:37 +0000716/// IfConvertDiamond - If convert a diamond sub-CFG.
717///
Evan Cheng4e654852007-05-16 02:00:57 +0000718bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
Evan Chengb6665f62007-06-04 06:47:22 +0000719 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Chengcf6cc112007-05-18 18:14:37 +0000720 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chengcf6cc112007-05-18 18:14:37 +0000721
Evan Chenga6b4f432007-05-21 22:22:58 +0000722 SmallVector<MachineInstr*, 2> Dups;
Evan Chengb6665f62007-06-04 06:47:22 +0000723 if (!BBI.TailBB) {
724 // No common merge block. Check if the terminators (e.g. return) are
725 // the same or predicable.
726 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
727 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
728 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
729 if (TT->isIdenticalTo(FT))
730 Dups.push_back(TT); // Will erase these later.
731 else if (!TT->isPredicable() && !FT->isPredicable())
732 return false; // Can't if-convert. Abort!
733 ++TT;
734 ++FT;
Evan Chengcf6cc112007-05-18 18:14:37 +0000735 }
Evan Chengcf6cc112007-05-18 18:14:37 +0000736
Evan Chengb6665f62007-06-04 06:47:22 +0000737 // One of the two pathes have more terminators, make sure they are
738 // all predicable.
739 while (TT != BBI.TrueBB->end()) {
740 if (!TT->isPredicable()) {
741 return false; // Can't if-convert. Abort!
Evan Cheng4e654852007-05-16 02:00:57 +0000742 }
Evan Chengb6665f62007-06-04 06:47:22 +0000743 ++TT;
744 }
745 while (FT != BBI.FalseBB->end()) {
746 if (!FT->isPredicable()) {
747 return false; // Can't if-convert. Abort!
748 }
749 ++FT;
Evan Cheng4e654852007-05-16 02:00:57 +0000750 }
Evan Cheng4e654852007-05-16 02:00:57 +0000751 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000752
Evan Chenga6b4f432007-05-21 22:22:58 +0000753 // Remove the duplicated instructions from the 'true' block.
754 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
755 Dups[i]->eraseFromParent();
Evan Chenga13aa952007-05-23 07:23:16 +0000756 --TrueBBI.NonPredSize;
Evan Chenga6b4f432007-05-21 22:22:58 +0000757 }
758
Evan Chenga6b4f432007-05-21 22:22:58 +0000759 // Merge the 'true' and 'false' blocks by copying the instructions
760 // from the 'false' block to the 'true' block. That is, unless the true
761 // block would clobber the predicate, in that case, do the opposite.
Evan Cheng993fc952007-06-05 23:46:14 +0000762 BBInfo *BBI1 = &TrueBBI;
763 BBInfo *BBI2 = &FalseBBI;
Evan Chengb6665f62007-06-04 06:47:22 +0000764 std::vector<MachineOperand> RevCond(BBI.BrCond);
765 TII->ReverseBranchCondition(RevCond);
Evan Cheng993fc952007-06-05 23:46:14 +0000766 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
767 std::vector<MachineOperand> *Cond2 = &RevCond;
Evan Cheng993fc952007-06-05 23:46:14 +0000768 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
769 // Either the block fallthrough to another block or it ends with a
770 // return. If it's the former, add a branch to its successor.
771 bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
Evan Chenge7052132007-06-06 00:57:55 +0000772 bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
773
774 if ((TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate) ||
775 (!TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate &&
776 NeedBr1 && !NeedBr2)) {
777 std::swap(BBI1, BBI2);
778 std::swap(Cond1, Cond2);
779 std::swap(NeedBr1, NeedBr2);
780 }
Evan Cheng993fc952007-06-05 23:46:14 +0000781
782 // Predicate the 'true' block after removing its branch.
783 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
784 PredicateBlock(*BBI1, *Cond1);
785
786 // Add an early exit branch if needed.
787 if (NeedBr1)
788 TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
789
790 // Predicate the 'false' block.
791 PredicateBlock(*BBI2, *Cond2, true);
792
793 // Add an unconditional branch from 'false' to to 'false' successor if it
794 // will not be the fallthrough block.
Evan Chengd4de6d92007-06-07 02:12:15 +0000795 if (NeedBr2 && !NeedBr1) {
796 // If BBI2 isn't going to be merged in, then the existing fallthrough
797 // or branch is fine.
Evan Cheng7e75ba82007-06-08 22:01:07 +0000798 if (!canFallThroughTo(BBI.BB, *BBI2->BB->succ_begin())) {
Evan Chengd4de6d92007-06-07 02:12:15 +0000799 InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
800 BBI2->hasFallThrough = false;
801 }
802 }
Evan Cheng993fc952007-06-05 23:46:14 +0000803
804 // Keep them as two separate blocks if there is an early exit.
805 if (!NeedBr1)
806 MergeBlocks(*BBI1, *BBI2);
Evan Cheng993fc952007-06-05 23:46:14 +0000807
Evan Chenga6b4f432007-05-21 22:22:58 +0000808 // Remove the conditional branch from entry to the blocks.
Evan Chenga13aa952007-05-23 07:23:16 +0000809 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000810
Evan Cheng993fc952007-06-05 23:46:14 +0000811 // Merge the combined block into the entry of the diamond.
812 MergeBlocks(BBI, *BBI1);
Evan Chenga6b4f432007-05-21 22:22:58 +0000813
Evan Chenge7052132007-06-06 00:57:55 +0000814 // 'True' and 'false' aren't combined, see if we need to add a unconditional
815 // branch to the 'false' block.
Evan Cheng7e75ba82007-06-08 22:01:07 +0000816 if (NeedBr1 && !canFallThroughTo(BBI.BB, BBI2->BB)) {
Evan Chengd4de6d92007-06-07 02:12:15 +0000817 InsertUncondBranch(BBI.BB, BBI2->BB, TII);
818 BBI1->hasFallThrough = false;
819 }
Evan Chenge7052132007-06-06 00:57:55 +0000820
Evan Cheng58fbb9f2007-05-29 23:37:20 +0000821 // If the if-converted block fallthrough or unconditionally branch into the
822 // tail block, and the tail block does not have other predecessors, then
Evan Chenga6b4f432007-05-21 22:22:58 +0000823 // fold the tail block in as well.
Evan Cheng993fc952007-06-05 23:46:14 +0000824 BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
Evan Cheng58fbb9f2007-05-29 23:37:20 +0000825 if (BBI.TailBB &&
Evan Chengf15d44c2007-05-31 20:53:33 +0000826 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
Evan Chenga13aa952007-05-23 07:23:16 +0000827 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000828 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
829 MergeBlocks(*CvtBBI, TailBBI);
830 TailBBI.Kind = ICDead;
831 }
832
Evan Cheng7e75ba82007-06-08 22:01:07 +0000833 RemoveExtraEdges(BBI);
834
Evan Cheng993fc952007-06-05 23:46:14 +0000835 // Update block info.
Evan Cheng7a655472007-06-06 10:16:17 +0000836 BBI.Kind = ICDead;
Evan Chenga6b4f432007-05-21 22:22:58 +0000837 TrueBBI.Kind = ICDead;
838 FalseBBI.Kind = ICDead;
839
840 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +0000841 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000842}
843
Evan Cheng4e654852007-05-16 02:00:57 +0000844/// PredicateBlock - Predicate every instruction in the block with the specified
845/// condition. If IgnoreTerm is true, skip over all terminator instructions.
Evan Chenga13aa952007-05-23 07:23:16 +0000846void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng4e654852007-05-16 02:00:57 +0000847 std::vector<MachineOperand> &Cond,
848 bool IgnoreTerm) {
Evan Chenga13aa952007-05-23 07:23:16 +0000849 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
Evan Cheng4e654852007-05-16 02:00:57 +0000850 I != E; ++I) {
Evan Chengb6665f62007-06-04 06:47:22 +0000851 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
Evan Cheng4e654852007-05-16 02:00:57 +0000852 continue;
Evan Chengb6665f62007-06-04 06:47:22 +0000853 if (TII->isPredicated(I))
Evan Chenga13aa952007-05-23 07:23:16 +0000854 continue;
Evan Chengb6665f62007-06-04 06:47:22 +0000855 if (!TII->PredicateInstruction(I, Cond)) {
Evan Chengfe57a7e2007-06-01 00:55:26 +0000856 cerr << "Unable to predicate " << *I << "!\n";
Evan Chengd6ddc302007-05-16 21:54:37 +0000857 abort();
858 }
Evan Cheng4e654852007-05-16 02:00:57 +0000859 }
Evan Chenga13aa952007-05-23 07:23:16 +0000860
861 BBI.NonPredSize = 0;
Evan Cheng2acdbcc2007-06-08 19:17:12 +0000862 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
863
Evan Chengb6665f62007-06-04 06:47:22 +0000864 NumIfConvBBs++;
865}
866
Evan Cheng86cbfea2007-05-18 00:20:58 +0000867/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Evan Cheng4e654852007-05-16 02:00:57 +0000868///
Evan Cheng86cbfea2007-05-18 00:20:58 +0000869void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
870 ToBBI.BB->splice(ToBBI.BB->end(),
871 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +0000872
Evan Chengb6665f62007-06-04 06:47:22 +0000873 // Redirect all branches to FromBB to ToBB.
Evan Chenga1a9f402007-06-05 22:03:53 +0000874 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
875 FromBBI.BB->pred_end());
Evan Chengd4de6d92007-06-07 02:12:15 +0000876 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
877 MachineBasicBlock *Pred = Preds[i];
878 if (Pred == ToBBI.BB)
879 continue;
880 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
881 }
882
883 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
884 FromBBI.BB->succ_end());
Evan Cheng7e75ba82007-06-08 22:01:07 +0000885 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
886 MachineBasicBlock *FallThrough = FromBBI.hasFallThrough ? NBB : NULL;
Evan Chengb6665f62007-06-04 06:47:22 +0000887
Evan Chengd4de6d92007-06-07 02:12:15 +0000888 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
889 MachineBasicBlock *Succ = Succs[i];
Evan Cheng7e75ba82007-06-08 22:01:07 +0000890 // Fallthrough edge can't be transferred.
Evan Chengd4de6d92007-06-07 02:12:15 +0000891 if (Succ == FallThrough)
892 continue;
893 FromBBI.BB->removeSuccessor(Succ);
894 if (!ToBBI.BB->isSuccessor(Succ))
895 ToBBI.BB->addSuccessor(Succ);
896 }
897
Evan Cheng7e75ba82007-06-08 22:01:07 +0000898 // Now FromBBI always fall through to the next block!
899 if (NBB)
900 FromBBI.BB->addSuccessor(NBB);
901
Evan Chenga13aa952007-05-23 07:23:16 +0000902 ToBBI.NonPredSize += FromBBI.NonPredSize;
903 FromBBI.NonPredSize = 0;
Evan Cheng7a655472007-06-06 10:16:17 +0000904
905 ToBBI.ModifyPredicate |= FromBBI.ModifyPredicate;
Evan Chengd4de6d92007-06-07 02:12:15 +0000906 ToBBI.hasFallThrough = FromBBI.hasFallThrough;
Evan Cheng2acdbcc2007-06-08 19:17:12 +0000907
908 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
909 std::back_inserter(ToBBI.Predicate));
910 FromBBI.Predicate.clear();
Evan Cheng4e654852007-05-16 02:00:57 +0000911}