blob: c5e4ef7c9d2c752febbd1af1688d916603163a56 [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
14#define DEBUG_TYPE "ifconversion"
15#include "llvm/CodeGen/Passes.h"
16#include "llvm/CodeGen/MachineModuleInfo.h"
17#include "llvm/CodeGen/MachineFunctionPass.h"
18#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng86cbfea2007-05-18 00:20:58 +000019#include "llvm/Target/TargetLowering.h"
Evan Cheng4e654852007-05-16 02:00:57 +000020#include "llvm/Target/TargetMachine.h"
21#include "llvm/Support/Debug.h"
Evan Cheng36489bb2007-05-18 19:26:33 +000022#include "llvm/ADT/DepthFirstIterator.h"
Evan Cheng4e654852007-05-16 02:00:57 +000023#include "llvm/ADT/Statistic.h"
24using namespace llvm;
25
26STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
27
28namespace {
29 class IfConverter : public MachineFunctionPass {
30 enum BBICKind {
Evan Chenga13aa952007-05-23 07:23:16 +000031 ICNotAnalyzed, // BB has not been analyzed.
32 ICReAnalyze, // BB must be re-analyzed.
Evan Cheng4e654852007-05-16 02:00:57 +000033 ICNotClassfied, // BB data valid, but not classified.
Evan Chenga6b4f432007-05-21 22:22:58 +000034 ICEarlyExit, // BB is entry of an early-exit sub-CFG.
35 ICTriangle, // BB is entry of a triangle sub-CFG.
36 ICDiamond, // BB is entry of a diamond sub-CFG.
37 ICChild, // BB is part of the sub-CFG that'll be predicated.
38 ICDead // BB has been converted and merged, it's now dead.
Evan Cheng4e654852007-05-16 02:00:57 +000039 };
40
41 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
42 /// if-conversion feasibility analysis. This includes results from
43 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng86cbfea2007-05-18 00:20:58 +000044 /// classification, and common tail block of its successors (if it's a
Evan Chengcf6cc112007-05-18 18:14:37 +000045 /// diamond shape), its size, whether it's predicable, and whether any
46 /// instruction can clobber the 'would-be' predicate.
Evan Chenga13aa952007-05-23 07:23:16 +000047 ///
48 /// Kind - Type of block. See BBICKind.
49 /// NonPredSize - Number of non-predicated instructions.
50 /// isPredicable - Is it predicable. (FIXME: Remove.)
51 /// hasEarlyExit - Ends with a return, indirect jump or br to jumptable.
52 /// ModifyPredicate - FIXME: Not used right now. True if BB would modify
53 /// the predicate (e.g. has cmp, call, etc.)
54 /// BB - Corresponding MachineBasicBlock.
55 /// TrueBB / FalseBB- See AnalyzeBranch().
56 /// BrCond - Conditions for end of block conditional branches.
57 /// Predicate - Predicate used in the BB.
Evan Cheng4e654852007-05-16 02:00:57 +000058 struct BBInfo {
59 BBICKind Kind;
Evan Chenga13aa952007-05-23 07:23:16 +000060 unsigned NonPredSize;
Evan Chengcf6cc112007-05-18 18:14:37 +000061 bool isPredicable;
Evan Chenga6b4f432007-05-21 22:22:58 +000062 bool hasEarlyExit;
Evan Chenga13aa952007-05-23 07:23:16 +000063 bool ModifyPredicate;
Evan Cheng86cbfea2007-05-18 00:20:58 +000064 MachineBasicBlock *BB;
65 MachineBasicBlock *TrueBB;
66 MachineBasicBlock *FalseBB;
67 MachineBasicBlock *TailBB;
Evan Chenga13aa952007-05-23 07:23:16 +000068 std::vector<MachineOperand> BrCond;
69 std::vector<MachineOperand> Predicate;
70 BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0), isPredicable(false),
71 hasEarlyExit(false), ModifyPredicate(false),
Evan Chenga6b4f432007-05-21 22:22:58 +000072 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
Evan Cheng4e654852007-05-16 02:00:57 +000073 };
74
75 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
76 /// basic block number.
77 std::vector<BBInfo> BBAnalysis;
78
Evan Cheng86cbfea2007-05-18 00:20:58 +000079 const TargetLowering *TLI;
Evan Cheng4e654852007-05-16 02:00:57 +000080 const TargetInstrInfo *TII;
81 bool MadeChange;
82 public:
83 static char ID;
84 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
85
86 virtual bool runOnMachineFunction(MachineFunction &MF);
87 virtual const char *getPassName() const { return "If converter"; }
88
89 private:
Evan Chengcf6cc112007-05-18 18:14:37 +000090 void StructuralAnalysis(MachineBasicBlock *BB);
Evan Chenga13aa952007-05-23 07:23:16 +000091 void FeasibilityAnalysis(BBInfo &BBI,
92 std::vector<MachineOperand> &Cond);
93 void AnalyzeBlocks(MachineFunction &MF,
94 std::vector<BBInfo*> &Candidates);
95 void InvalidatePreds(MachineBasicBlock *BB);
Evan Chenga6b4f432007-05-21 22:22:58 +000096 bool IfConvertEarlyExit(BBInfo &BBI);
Evan Cheng4e654852007-05-16 02:00:57 +000097 bool IfConvertTriangle(BBInfo &BBI);
Evan Chengcf6cc112007-05-18 18:14:37 +000098 bool IfConvertDiamond(BBInfo &BBI);
Evan Chenga13aa952007-05-23 07:23:16 +000099 void PredicateBlock(BBInfo &BBI,
Evan Cheng4e654852007-05-16 02:00:57 +0000100 std::vector<MachineOperand> &Cond,
101 bool IgnoreTerm = false);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000102 void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
Evan Cheng4e654852007-05-16 02:00:57 +0000103 };
104 char IfConverter::ID = 0;
105}
106
107FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
108
109bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng86cbfea2007-05-18 00:20:58 +0000110 TLI = MF.getTarget().getTargetLowering();
Evan Cheng4e654852007-05-16 02:00:57 +0000111 TII = MF.getTarget().getInstrInfo();
112 if (!TII) return false;
113
Evan Cheng4e654852007-05-16 02:00:57 +0000114 MF.RenumberBlocks();
115 unsigned NumBBs = MF.getNumBlockIDs();
116 BBAnalysis.resize(NumBBs);
117
Evan Cheng7f8ff8a2007-05-18 19:32:08 +0000118 std::vector<BBInfo*> Candidates;
Evan Cheng47d25022007-05-18 01:55:58 +0000119 MadeChange = false;
Evan Chenga13aa952007-05-23 07:23:16 +0000120 while (true) {
121 bool Change = false;
122
123 // Do an intial analysis for each basic block and finding all the potential
124 // candidates to perform if-convesion.
125 AnalyzeBlocks(MF, Candidates);
126 while (!Candidates.empty()) {
127 BBInfo &BBI = *Candidates.back();
128 Candidates.pop_back();
129 switch (BBI.Kind) {
130 default: assert(false && "Unexpected!");
131 break;
132 case ICEarlyExit:
133 Change |= IfConvertEarlyExit(BBI);
134 break;
135 case ICTriangle:
136 Change |= IfConvertTriangle(BBI);
137 break;
138 case ICDiamond:
139 Change |= IfConvertDiamond(BBI);
140 break;
141 }
Evan Cheng4e654852007-05-16 02:00:57 +0000142 }
Evan Chenga13aa952007-05-23 07:23:16 +0000143
144 MadeChange |= Change;
145 if (!Change)
146 break;
Evan Cheng4e654852007-05-16 02:00:57 +0000147 }
Evan Cheng47d25022007-05-18 01:55:58 +0000148
149 BBAnalysis.clear();
150
Evan Cheng4e654852007-05-16 02:00:57 +0000151 return MadeChange;
152}
153
154static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng86cbfea2007-05-18 00:20:58 +0000155 MachineBasicBlock *TrueBB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000156 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
157 E = BB->succ_end(); SI != E; ++SI) {
158 MachineBasicBlock *SuccBB = *SI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000159 if (SuccBB != TrueBB)
Evan Cheng4e654852007-05-16 02:00:57 +0000160 return SuccBB;
161 }
162 return NULL;
163}
164
Evan Chengcf6cc112007-05-18 18:14:37 +0000165/// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
166/// the specified block. Record its successors and whether it looks like an
167/// if-conversion candidate.
168void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000169 BBInfo &BBI = BBAnalysis[BB->getNumber()];
170
Evan Chenga13aa952007-05-23 07:23:16 +0000171 if (BBI.Kind != ICReAnalyze) {
172 if (BBI.Kind != ICNotAnalyzed)
173 return; // Already analyzed.
174 BBI.BB = BB;
175 BBI.NonPredSize = std::distance(BB->begin(), BB->end());
Evan Cheng4e654852007-05-16 02:00:57 +0000176
Evan Chenga13aa952007-05-23 07:23:16 +0000177 // Look for 'root' of a simple (non-nested) triangle or diamond.
178 BBI.Kind = ICNotClassfied;
179 bool CanAnalyze = !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB,
180 BBI.BrCond);
181 // Does it end with a return, indirect jump, or jumptable branch?
182 BBI.hasEarlyExit = TII->BlockHasNoFallThrough(*BB) && !BBI.TrueBB;
183 if (!CanAnalyze || !BBI.TrueBB || BBI.BrCond.size() == 0)
184 return;
185 }
Evan Cheng86cbfea2007-05-18 00:20:58 +0000186
187 // Not a candidate if 'true' block is going to be if-converted.
Evan Chengcf6cc112007-05-18 18:14:37 +0000188 StructuralAnalysis(BBI.TrueBB);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000189 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
190 if (TrueBBI.Kind != ICNotClassfied)
Evan Cheng4e654852007-05-16 02:00:57 +0000191 return;
Evan Chengd6ddc302007-05-16 21:54:37 +0000192
Evan Cheng47d25022007-05-18 01:55:58 +0000193 // TODO: Only handle very simple cases for now.
Evan Chenga13aa952007-05-23 07:23:16 +0000194 if (TrueBBI.FalseBB || TrueBBI.BrCond.size())
Evan Cheng47d25022007-05-18 01:55:58 +0000195 return;
196
Evan Chengd6ddc302007-05-16 21:54:37 +0000197 // No false branch. This BB must end with a conditional branch and a
198 // fallthrough.
Evan Cheng86cbfea2007-05-18 00:20:58 +0000199 if (!BBI.FalseBB)
200 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
201 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
Evan Chengc5d05ef2007-05-16 05:11:10 +0000202
Evan Cheng86cbfea2007-05-18 00:20:58 +0000203 // Not a candidate if 'false' block is going to be if-converted.
Evan Chengcf6cc112007-05-18 18:14:37 +0000204 StructuralAnalysis(BBI.FalseBB);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000205 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
206 if (FalseBBI.Kind != ICNotClassfied)
Evan Cheng4e654852007-05-16 02:00:57 +0000207 return;
208
209 // TODO: Only handle very simple cases for now.
Evan Chenga13aa952007-05-23 07:23:16 +0000210 if (FalseBBI.FalseBB || FalseBBI.BrCond.size())
Evan Cheng4e654852007-05-16 02:00:57 +0000211 return;
212
Evan Chenga6b4f432007-05-21 22:22:58 +0000213 unsigned TrueNumPreds = BBI.TrueBB->pred_size();
214 unsigned FalseNumPreds = BBI.FalseBB->pred_size();
215 if ((TrueBBI.hasEarlyExit && TrueNumPreds <= 1) &&
216 !(FalseBBI.hasEarlyExit && FalseNumPreds <=1)) {
217 BBI.Kind = ICEarlyExit;
218 TrueBBI.Kind = ICChild;
219 } else if (!(TrueBBI.hasEarlyExit && TrueNumPreds <= 1) &&
220 (FalseBBI.hasEarlyExit && FalseNumPreds <=1)) {
221 BBI.Kind = ICEarlyExit;
222 FalseBBI.Kind = ICChild;
223 } else if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000224 // Triangle:
225 // EBB
226 // | \_
227 // | |
228 // | TBB
229 // | /
230 // FBB
Evan Chenga6b4f432007-05-21 22:22:58 +0000231 BBI.Kind = ICTriangle;
232 TrueBBI.Kind = FalseBBI.Kind = ICChild;
233 } else if (TrueBBI.TrueBB == FalseBBI.TrueBB &&
234 TrueNumPreds <= 1 && FalseNumPreds <= 1) {
Evan Cheng4e654852007-05-16 02:00:57 +0000235 // Diamond:
236 // EBB
237 // / \_
238 // | |
239 // TBB FBB
240 // \ /
Evan Cheng86cbfea2007-05-18 00:20:58 +0000241 // TailBB
Evan Cheng4e654852007-05-16 02:00:57 +0000242 // Note MBB can be empty in case both TBB and FBB are return blocks.
Evan Chenga6b4f432007-05-21 22:22:58 +0000243 BBI.Kind = ICDiamond;
244 TrueBBI.Kind = FalseBBI.Kind = ICChild;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000245 BBI.TailBB = TrueBBI.TrueBB;
Evan Cheng4e654852007-05-16 02:00:57 +0000246 }
247 return;
248}
249
Evan Chengcf6cc112007-05-18 18:14:37 +0000250/// FeasibilityAnalysis - Determine if the block is predicable. In most
251/// cases, that means all the instructions in the block has M_PREDICABLE flag.
252/// Also checks if the block contains any instruction which can clobber a
253/// predicate (e.g. condition code register). If so, the block is not
254/// predicable unless it's the last instruction. Note, this function assumes
255/// all the terminator instructions can be converted or deleted so it ignore
256/// them.
Evan Chenga13aa952007-05-23 07:23:16 +0000257void IfConverter::FeasibilityAnalysis(BBInfo &BBI,
258 std::vector<MachineOperand> &Cond) {
259 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
Evan Chengcf6cc112007-05-18 18:14:37 +0000260 return;
261
262 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
263 I != E; ++I) {
264 // TODO: check if instruction clobbers predicate.
265 if (TII->isTerminatorInstr(I->getOpcode()))
266 break;
267 if (!I->isPredicable())
268 return;
269 }
270
Evan Chenga13aa952007-05-23 07:23:16 +0000271 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Cond))
272 return;
273
Evan Chengcf6cc112007-05-18 18:14:37 +0000274 BBI.isPredicable = true;
275}
276
Evan Chenga13aa952007-05-23 07:23:16 +0000277/// AnalyzeBlocks - Analyze all blocks and find entries for all
Evan Chengd6ddc302007-05-16 21:54:37 +0000278/// if-conversion candidates.
Evan Chenga13aa952007-05-23 07:23:16 +0000279void IfConverter::AnalyzeBlocks(MachineFunction &MF,
280 std::vector<BBInfo*> &Candidates) {
Evan Cheng36489bb2007-05-18 19:26:33 +0000281 std::set<MachineBasicBlock*> Visited;
282 MachineBasicBlock *Entry = MF.begin();
283 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
284 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
285 MachineBasicBlock *BB = *DFI;
Evan Chengcf6cc112007-05-18 18:14:37 +0000286 StructuralAnalysis(BB);
Evan Cheng4e654852007-05-16 02:00:57 +0000287 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Chenga6b4f432007-05-21 22:22:58 +0000288 switch (BBI.Kind) {
289 default: break;
290 case ICEarlyExit:
291 case ICTriangle:
292 case ICDiamond:
Evan Cheng7f8ff8a2007-05-18 19:32:08 +0000293 Candidates.push_back(&BBI);
Evan Chenga6b4f432007-05-21 22:22:58 +0000294 break;
295 }
Evan Cheng4e654852007-05-16 02:00:57 +0000296 }
297}
298
Evan Cheng86cbfea2007-05-18 00:20:58 +0000299/// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
300///
301static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
302 std::vector<MachineBasicBlock*> Preds(FromBB->pred_begin(),
303 FromBB->pred_end());
304 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
305 MachineBasicBlock *Pred = Preds[i];
306 Pred->removeSuccessor(FromBB);
307 if (!Pred->isSuccessor(ToBB))
308 Pred->addSuccessor(ToBB);
309 }
310}
311
312/// TransferSuccs - Transfer all the successors of FromBB to ToBB.
313///
314static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
315 std::vector<MachineBasicBlock*> Succs(FromBB->succ_begin(),
316 FromBB->succ_end());
317 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
318 MachineBasicBlock *Succ = Succs[i];
319 FromBB->removeSuccessor(Succ);
320 if (!ToBB->isSuccessor(Succ))
321 ToBB->addSuccessor(Succ);
322 }
323}
324
Evan Chenga6b4f432007-05-21 22:22:58 +0000325/// isNextBlock - Returns true if ToBB the next basic block after BB.
326///
327static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
328 MachineFunction::iterator Fallthrough = BB;
329 return MachineFunction::iterator(ToBB) == ++Fallthrough;
330}
331
Evan Chenga13aa952007-05-23 07:23:16 +0000332/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
333/// to determine if it can be if-converted.
334void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
335 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
336 E = BB->pred_end(); PI != E; ++PI) {
337 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
338 PBBI.Kind = ICReAnalyze;
339 }
340}
341
Evan Chenga6b4f432007-05-21 22:22:58 +0000342/// IfConvertEarlyExit - If convert a early exit sub-CFG.
343///
344bool IfConverter::IfConvertEarlyExit(BBInfo &BBI) {
Evan Chenga13aa952007-05-23 07:23:16 +0000345 BBI.Kind = ICNotClassfied;
346
Evan Chenga6b4f432007-05-21 22:22:58 +0000347 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
348 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
349 BBInfo *CvtBBI = &TrueBBI;
350 BBInfo *NextBBI = &FalseBBI;
Evan Chenga13aa952007-05-23 07:23:16 +0000351
Evan Chenga6b4f432007-05-21 22:22:58 +0000352 bool ReserveCond = false;
353 if (TrueBBI.Kind != ICChild) {
354 std::swap(CvtBBI, NextBBI);
355 ReserveCond = true;
356 }
357
Evan Chenga13aa952007-05-23 07:23:16 +0000358 std::vector<MachineOperand> NewCond(BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000359 if (ReserveCond)
360 TII->ReverseBranchCondition(NewCond);
Evan Chenga13aa952007-05-23 07:23:16 +0000361 FeasibilityAnalysis(*CvtBBI, NewCond);
362 if (!CvtBBI->isPredicable)
363 return false;
364
365 PredicateBlock(*CvtBBI, NewCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000366
367 // Merge converted block into entry block. Also convert the end of the
368 // block conditional branch (to the non-converted block) into an
369 // unconditional one.
Evan Chenga13aa952007-05-23 07:23:16 +0000370 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000371 MergeBlocks(BBI, *CvtBBI);
372 if (!isNextBlock(BBI.BB, NextBBI->BB)) {
373 std::vector<MachineOperand> NoCond;
374 TII->InsertBranch(*BBI.BB, NextBBI->BB, NULL, NoCond);
375 }
Evan Chenga13aa952007-05-23 07:23:16 +0000376 std::copy(NewCond.begin(), NewCond.end(), std::back_inserter(BBI.Predicate));
Evan Chenga6b4f432007-05-21 22:22:58 +0000377
Evan Chenga13aa952007-05-23 07:23:16 +0000378 // Update block info. BB can be iteratively if-converted.
379 BBI.Kind = ICNotAnalyzed;
380 BBI.TrueBB = BBI.FalseBB = NULL;
381 BBI.BrCond.clear();
382 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
383 InvalidatePreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000384 CvtBBI->Kind = ICDead;
385
386 // FIXME: Must maintain LiveIns.
387 NumIfConvBBs++;
388 return true;
389}
390
Evan Chengd6ddc302007-05-16 21:54:37 +0000391/// IfConvertTriangle - If convert a triangle sub-CFG.
392///
Evan Cheng4e654852007-05-16 02:00:57 +0000393bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
Evan Chenga13aa952007-05-23 07:23:16 +0000394 BBI.Kind = ICNotClassfied;
Evan Chengcf6cc112007-05-18 18:14:37 +0000395
Evan Chenga13aa952007-05-23 07:23:16 +0000396 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
397 FeasibilityAnalysis(TrueBBI, BBI.BrCond);
398 if (!TrueBBI.isPredicable)
Evan Chenga6b4f432007-05-21 22:22:58 +0000399 return false;
Evan Chenga6b4f432007-05-21 22:22:58 +0000400
401 // Predicate the 'true' block after removing its branch.
Evan Chenga13aa952007-05-23 07:23:16 +0000402 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
403 PredicateBlock(TrueBBI, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000404
405 // Join the 'true' and 'false' blocks by copying the instructions
406 // from the 'false' block to the 'true' block.
Evan Chenga6b4f432007-05-21 22:22:58 +0000407 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
408 MergeBlocks(TrueBBI, FalseBBI);
409
410 // Now merge the entry of the triangle with the true block.
Evan Chenga13aa952007-05-23 07:23:16 +0000411 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000412 MergeBlocks(BBI, TrueBBI);
Evan Chenga13aa952007-05-23 07:23:16 +0000413 std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
414 std::back_inserter(BBI.Predicate));
Evan Chenga6b4f432007-05-21 22:22:58 +0000415
Evan Chenga13aa952007-05-23 07:23:16 +0000416 // Update block info. BB can be iteratively if-converted.
417 BBI.Kind = ICNotClassfied;
418 BBI.TrueBB = BBI.FalseBB = NULL;
419 BBI.BrCond.clear();
420 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000421 TrueBBI.Kind = ICDead;
422
423 // FIXME: Must maintain LiveIns.
424 NumIfConvBBs++;
425 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000426}
427
Evan Chengd6ddc302007-05-16 21:54:37 +0000428/// IfConvertDiamond - If convert a diamond sub-CFG.
429///
Evan Cheng4e654852007-05-16 02:00:57 +0000430bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
Evan Chenga13aa952007-05-23 07:23:16 +0000431 BBI.Kind = ICNotClassfied;
432
Evan Chenga6b4f432007-05-21 22:22:58 +0000433 bool TrueNeedCBr;
434 bool FalseNeedCBr;
Evan Chengcf6cc112007-05-18 18:14:37 +0000435 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
436 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chenga13aa952007-05-23 07:23:16 +0000437 FeasibilityAnalysis(TrueBBI, BBI.BrCond);
438 std::vector<MachineOperand> RevCond(BBI.BrCond);
439 TII->ReverseBranchCondition(RevCond);
440 FeasibilityAnalysis(FalseBBI, RevCond);
Evan Chengcf6cc112007-05-18 18:14:37 +0000441
Evan Chenga6b4f432007-05-21 22:22:58 +0000442 SmallVector<MachineInstr*, 2> Dups;
443 bool Proceed = TrueBBI.isPredicable && FalseBBI.isPredicable;
444 if (Proceed) {
Evan Chengcf6cc112007-05-18 18:14:37 +0000445 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
446 // Either the block fallthrough to another block or it ends with a
447 // return. If it's the former, add a conditional branch to its successor.
Evan Chenga6b4f432007-05-21 22:22:58 +0000448 TrueNeedCBr = !TrueBBI.TrueBB && BBI.TrueBB->succ_size();
449 FalseNeedCBr = !FalseBBI.TrueBB && BBI.FalseBB->succ_size();
Evan Chenga13aa952007-05-23 07:23:16 +0000450 if (TrueNeedCBr && TrueBBI.ModifyPredicate) {
Evan Chengcf6cc112007-05-18 18:14:37 +0000451 TrueBBI.isPredicable = false;
452 Proceed = false;
453 }
Evan Chenga13aa952007-05-23 07:23:16 +0000454 if (FalseNeedCBr && FalseBBI.ModifyPredicate) {
Evan Chengcf6cc112007-05-18 18:14:37 +0000455 FalseBBI.isPredicable = false;
456 Proceed = false;
457 }
Evan Chengcf6cc112007-05-18 18:14:37 +0000458
Evan Chenga6b4f432007-05-21 22:22:58 +0000459 if (Proceed) {
460 if (!BBI.TailBB) {
461 // No common merge block. Check if the terminators (e.g. return) are
462 // the same or predicable.
463 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
464 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
465 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
466 if (TT->isIdenticalTo(FT))
467 Dups.push_back(TT); // Will erase these later.
468 else if (!TT->isPredicable() && !FT->isPredicable()) {
469 Proceed = false;
470 break; // Can't if-convert. Abort!
471 }
472 ++TT;
473 ++FT;
474 }
475
476 // One of the two pathes have more terminators, make sure they are
477 // all predicable.
478 while (Proceed && TT != BBI.TrueBB->end())
479 if (!TT->isPredicable()) {
480 Proceed = false;
481 break; // Can't if-convert. Abort!
482 }
483 while (Proceed && FT != BBI.FalseBB->end())
484 if (!FT->isPredicable()) {
485 Proceed = false;
486 break; // Can't if-convert. Abort!
487 }
Evan Cheng4e654852007-05-16 02:00:57 +0000488 }
Evan Cheng4e654852007-05-16 02:00:57 +0000489 }
Evan Cheng4e654852007-05-16 02:00:57 +0000490 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000491
Evan Chenga13aa952007-05-23 07:23:16 +0000492 if (!Proceed)
Evan Chenga6b4f432007-05-21 22:22:58 +0000493 return false;
Evan Chenga6b4f432007-05-21 22:22:58 +0000494
495 // Remove the duplicated instructions from the 'true' block.
496 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
497 Dups[i]->eraseFromParent();
Evan Chenga13aa952007-05-23 07:23:16 +0000498 --TrueBBI.NonPredSize;
Evan Chenga6b4f432007-05-21 22:22:58 +0000499 }
500
501 // Predicate the 'true' block after removing its branch.
Evan Chenga13aa952007-05-23 07:23:16 +0000502 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
503 PredicateBlock(TrueBBI, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000504
505 // Add a conditional branch to 'true' successor if needed.
Evan Chenga13aa952007-05-23 07:23:16 +0000506 if (TrueNeedCBr && TrueBBI.ModifyPredicate &&
Evan Chenga6b4f432007-05-21 22:22:58 +0000507 isNextBlock(BBI.TrueBB, *BBI.TrueBB->succ_begin()))
508 TrueNeedCBr = false;
509 if (TrueNeedCBr)
Evan Chenga13aa952007-05-23 07:23:16 +0000510 TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000511
512 // Predicate the 'false' block.
Evan Chenga13aa952007-05-23 07:23:16 +0000513 PredicateBlock(FalseBBI, RevCond, true);
Evan Chenga6b4f432007-05-21 22:22:58 +0000514
515 // Add a conditional branch to 'false' successor if needed.
Evan Chenga13aa952007-05-23 07:23:16 +0000516 if (FalseNeedCBr && !TrueBBI.ModifyPredicate &&
Evan Chenga6b4f432007-05-21 22:22:58 +0000517 isNextBlock(BBI.FalseBB, *BBI.FalseBB->succ_begin()))
518 FalseNeedCBr = false;
519 if (FalseNeedCBr)
Evan Chenga13aa952007-05-23 07:23:16 +0000520 TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,
521 RevCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000522
523 // Merge the 'true' and 'false' blocks by copying the instructions
524 // from the 'false' block to the 'true' block. That is, unless the true
525 // block would clobber the predicate, in that case, do the opposite.
526 BBInfo *CvtBBI;
Evan Chenga13aa952007-05-23 07:23:16 +0000527 if (!TrueBBI.ModifyPredicate) {
Evan Chenga6b4f432007-05-21 22:22:58 +0000528 MergeBlocks(TrueBBI, FalseBBI);
529 CvtBBI = &TrueBBI;
530 } else {
531 MergeBlocks(FalseBBI, TrueBBI);
532 CvtBBI = &FalseBBI;
533 }
534
535 // Remove the conditional branch from entry to the blocks.
Evan Chenga13aa952007-05-23 07:23:16 +0000536 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000537
Evan Chenga13aa952007-05-23 07:23:16 +0000538 bool OkToIfcvt = true;
Evan Chenga6b4f432007-05-21 22:22:58 +0000539 // Merge the combined block into the entry of the diamond if the entry
540 // block is its only predecessor. Otherwise, insert an unconditional
541 // branch from entry to the if-converted block.
542 if (CvtBBI->BB->pred_size() == 1) {
Evan Chenga6b4f432007-05-21 22:22:58 +0000543 MergeBlocks(BBI, *CvtBBI);
544 CvtBBI = &BBI;
Evan Chenga13aa952007-05-23 07:23:16 +0000545 OkToIfcvt = false;
Evan Chenga6b4f432007-05-21 22:22:58 +0000546 } else {
547 std::vector<MachineOperand> NoCond;
548 TII->InsertBranch(*BBI.BB, CvtBBI->BB, NULL, NoCond);
549 }
550
551 // If the if-converted block fallthrough into the tail block, then
552 // fold the tail block in as well.
553 if (BBI.TailBB && CvtBBI->BB->succ_size() == 1) {
Evan Chenga13aa952007-05-23 07:23:16 +0000554 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000555 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
556 MergeBlocks(*CvtBBI, TailBBI);
557 TailBBI.Kind = ICDead;
558 }
559
Evan Chenga13aa952007-05-23 07:23:16 +0000560 // Update block info. BB may be iteratively if-converted.
561 if (OkToIfcvt) {
562 BBI.Kind = ICNotClassfied;
563 BBI.TrueBB = BBI.FalseBB = NULL;
564 BBI.BrCond.clear();
565 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
566 InvalidatePreds(BBI.BB);
567 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000568 TrueBBI.Kind = ICDead;
569 FalseBBI.Kind = ICDead;
570
571 // FIXME: Must maintain LiveIns.
572 NumIfConvBBs += 2;
573 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000574}
575
Evan Cheng4e654852007-05-16 02:00:57 +0000576/// PredicateBlock - Predicate every instruction in the block with the specified
577/// condition. If IgnoreTerm is true, skip over all terminator instructions.
Evan Chenga13aa952007-05-23 07:23:16 +0000578void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng4e654852007-05-16 02:00:57 +0000579 std::vector<MachineOperand> &Cond,
580 bool IgnoreTerm) {
Evan Chenga13aa952007-05-23 07:23:16 +0000581 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
Evan Cheng4e654852007-05-16 02:00:57 +0000582 I != E; ++I) {
Evan Chenga13aa952007-05-23 07:23:16 +0000583 MachineInstr *MI = I;
584 if (IgnoreTerm && TII->isTerminatorInstr(MI->getOpcode()))
Evan Cheng4e654852007-05-16 02:00:57 +0000585 continue;
Evan Chenga13aa952007-05-23 07:23:16 +0000586 if (TII->isPredicated(MI))
587 continue;
588 if (!TII->PredicateInstruction(MI, Cond)) {
Evan Chengd6ddc302007-05-16 21:54:37 +0000589 cerr << "Unable to predication " << *I << "!\n";
590 abort();
591 }
Evan Cheng4e654852007-05-16 02:00:57 +0000592 }
Evan Chenga13aa952007-05-23 07:23:16 +0000593
594 BBI.NonPredSize = 0;
Evan Cheng4e654852007-05-16 02:00:57 +0000595}
596
Evan Cheng86cbfea2007-05-18 00:20:58 +0000597/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Evan Cheng4e654852007-05-16 02:00:57 +0000598///
Evan Cheng86cbfea2007-05-18 00:20:58 +0000599void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
600 ToBBI.BB->splice(ToBBI.BB->end(),
601 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +0000602
603 // If FromBBI is previously a successor, remove it from ToBBI's successor
604 // list and update its TrueBB / FalseBB field if needed.
605 if (ToBBI.BB->isSuccessor(FromBBI.BB))
606 ToBBI.BB->removeSuccessor(FromBBI.BB);
607
608 // Transfer preds / succs and update size.
Evan Cheng86cbfea2007-05-18 00:20:58 +0000609 TransferPreds(ToBBI.BB, FromBBI.BB);
610 TransferSuccs(ToBBI.BB, FromBBI.BB);
Evan Chenga13aa952007-05-23 07:23:16 +0000611 ToBBI.NonPredSize += FromBBI.NonPredSize;
612 FromBBI.NonPredSize = 0;
Evan Cheng4e654852007-05-16 02:00:57 +0000613}