blob: 8e7b0fe45a4bb743ced97d93bcf120dc1faa44bc [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 Chenga13aa952007-05-23 07:23:16 +0000176 }
Evan Cheng86cbfea2007-05-18 00:20:58 +0000177
Evan Cheng4bec8ae2007-05-25 00:59:01 +0000178 // Look for 'root' of a simple (non-nested) triangle or diamond.
179 BBI.Kind = ICNotClassfied;
180 bool CanAnalyze = !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB,
181 BBI.BrCond);
182 // Does it end with a return, indirect jump, or jumptable branch?
183 BBI.hasEarlyExit = TII->BlockHasNoFallThrough(*BB) && !BBI.TrueBB;
184 if (!CanAnalyze || !BBI.TrueBB || BBI.BrCond.size() == 0)
185 return;
186
Evan Cheng86cbfea2007-05-18 00:20:58 +0000187 // 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 Chengc8ed9ba2007-05-29 22:31:16 +0000342/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
343///
344static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
345 const TargetInstrInfo *TII) {
346 std::vector<MachineOperand> NoCond;
347 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
348}
349
Evan Chenga6b4f432007-05-21 22:22:58 +0000350/// IfConvertEarlyExit - If convert a early exit sub-CFG.
351///
352bool IfConverter::IfConvertEarlyExit(BBInfo &BBI) {
Evan Chenga13aa952007-05-23 07:23:16 +0000353 BBI.Kind = ICNotClassfied;
354
Evan Chenga6b4f432007-05-21 22:22:58 +0000355 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
356 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
357 BBInfo *CvtBBI = &TrueBBI;
358 BBInfo *NextBBI = &FalseBBI;
Evan Chenga13aa952007-05-23 07:23:16 +0000359
Evan Chenga6b4f432007-05-21 22:22:58 +0000360 bool ReserveCond = false;
361 if (TrueBBI.Kind != ICChild) {
362 std::swap(CvtBBI, NextBBI);
363 ReserveCond = true;
364 }
365
Evan Chenga13aa952007-05-23 07:23:16 +0000366 std::vector<MachineOperand> NewCond(BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000367 if (ReserveCond)
368 TII->ReverseBranchCondition(NewCond);
Evan Chenga13aa952007-05-23 07:23:16 +0000369 FeasibilityAnalysis(*CvtBBI, NewCond);
370 if (!CvtBBI->isPredicable)
371 return false;
372
373 PredicateBlock(*CvtBBI, NewCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000374
375 // Merge converted block into entry block. Also convert the end of the
376 // block conditional branch (to the non-converted block) into an
377 // unconditional one.
Evan Chenga13aa952007-05-23 07:23:16 +0000378 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000379 MergeBlocks(BBI, *CvtBBI);
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000380 if (!isNextBlock(BBI.BB, NextBBI->BB))
381 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Chenga13aa952007-05-23 07:23:16 +0000382 std::copy(NewCond.begin(), NewCond.end(), std::back_inserter(BBI.Predicate));
Evan Chenga6b4f432007-05-21 22:22:58 +0000383
Evan Chenga13aa952007-05-23 07:23:16 +0000384 // Update block info. BB can be iteratively if-converted.
385 BBI.Kind = ICNotAnalyzed;
386 BBI.TrueBB = BBI.FalseBB = NULL;
387 BBI.BrCond.clear();
388 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
389 InvalidatePreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000390 CvtBBI->Kind = ICDead;
391
392 // FIXME: Must maintain LiveIns.
393 NumIfConvBBs++;
394 return true;
395}
396
Evan Chengd6ddc302007-05-16 21:54:37 +0000397/// IfConvertTriangle - If convert a triangle sub-CFG.
398///
Evan Cheng4e654852007-05-16 02:00:57 +0000399bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
Evan Chenga13aa952007-05-23 07:23:16 +0000400 BBI.Kind = ICNotClassfied;
Evan Chengcf6cc112007-05-18 18:14:37 +0000401
Evan Chenga13aa952007-05-23 07:23:16 +0000402 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
403 FeasibilityAnalysis(TrueBBI, BBI.BrCond);
404 if (!TrueBBI.isPredicable)
Evan Chenga6b4f432007-05-21 22:22:58 +0000405 return false;
Evan Chenga6b4f432007-05-21 22:22:58 +0000406
407 // Predicate the 'true' block after removing its branch.
Evan Chenga13aa952007-05-23 07:23:16 +0000408 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
409 PredicateBlock(TrueBBI, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000410
411 // Join the 'true' and 'false' blocks by copying the instructions
412 // from the 'false' block to the 'true' block.
Evan Chenga6b4f432007-05-21 22:22:58 +0000413 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
414 MergeBlocks(TrueBBI, FalseBBI);
415
416 // Now merge the entry of the triangle with the true block.
Evan Chenga13aa952007-05-23 07:23:16 +0000417 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000418 MergeBlocks(BBI, TrueBBI);
Evan Chenga13aa952007-05-23 07:23:16 +0000419 std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
420 std::back_inserter(BBI.Predicate));
Evan Chenga6b4f432007-05-21 22:22:58 +0000421
Evan Chenga13aa952007-05-23 07:23:16 +0000422 // Update block info. BB can be iteratively if-converted.
423 BBI.Kind = ICNotClassfied;
424 BBI.TrueBB = BBI.FalseBB = NULL;
425 BBI.BrCond.clear();
426 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000427 TrueBBI.Kind = ICDead;
428
429 // FIXME: Must maintain LiveIns.
430 NumIfConvBBs++;
431 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000432}
433
Evan Chengd6ddc302007-05-16 21:54:37 +0000434/// IfConvertDiamond - If convert a diamond sub-CFG.
435///
Evan Cheng4e654852007-05-16 02:00:57 +0000436bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
Evan Chenga13aa952007-05-23 07:23:16 +0000437 BBI.Kind = ICNotClassfied;
438
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000439 bool TrueNeedBr;
440 bool FalseNeedBr;
Evan Chengcf6cc112007-05-18 18:14:37 +0000441 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
442 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chenga13aa952007-05-23 07:23:16 +0000443 FeasibilityAnalysis(TrueBBI, BBI.BrCond);
444 std::vector<MachineOperand> RevCond(BBI.BrCond);
445 TII->ReverseBranchCondition(RevCond);
446 FeasibilityAnalysis(FalseBBI, RevCond);
Evan Chengcf6cc112007-05-18 18:14:37 +0000447
Evan Chenga6b4f432007-05-21 22:22:58 +0000448 SmallVector<MachineInstr*, 2> Dups;
449 bool Proceed = TrueBBI.isPredicable && FalseBBI.isPredicable;
450 if (Proceed) {
Evan Chengcf6cc112007-05-18 18:14:37 +0000451 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
452 // Either the block fallthrough to another block or it ends with a
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000453 // return. If it's the former, add a branch to its successor.
454 TrueNeedBr = !TrueBBI.TrueBB && BBI.TrueBB->succ_size();
455 FalseNeedBr = !FalseBBI.TrueBB && BBI.FalseBB->succ_size();
456 if (TrueNeedBr && TrueBBI.ModifyPredicate) {
Evan Chengcf6cc112007-05-18 18:14:37 +0000457 TrueBBI.isPredicable = false;
458 Proceed = false;
459 }
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000460 if (FalseNeedBr && FalseBBI.ModifyPredicate) {
Evan Chengcf6cc112007-05-18 18:14:37 +0000461 FalseBBI.isPredicable = false;
462 Proceed = false;
463 }
Evan Chengcf6cc112007-05-18 18:14:37 +0000464
Evan Chenga6b4f432007-05-21 22:22:58 +0000465 if (Proceed) {
466 if (!BBI.TailBB) {
467 // No common merge block. Check if the terminators (e.g. return) are
468 // the same or predicable.
469 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
470 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
471 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
472 if (TT->isIdenticalTo(FT))
473 Dups.push_back(TT); // Will erase these later.
474 else if (!TT->isPredicable() && !FT->isPredicable()) {
475 Proceed = false;
476 break; // Can't if-convert. Abort!
477 }
478 ++TT;
479 ++FT;
480 }
481
482 // One of the two pathes have more terminators, make sure they are
483 // all predicable.
484 while (Proceed && TT != BBI.TrueBB->end())
485 if (!TT->isPredicable()) {
486 Proceed = false;
487 break; // Can't if-convert. Abort!
488 }
489 while (Proceed && FT != BBI.FalseBB->end())
490 if (!FT->isPredicable()) {
491 Proceed = false;
492 break; // Can't if-convert. Abort!
493 }
Evan Cheng4e654852007-05-16 02:00:57 +0000494 }
Evan Cheng4e654852007-05-16 02:00:57 +0000495 }
Evan Cheng4e654852007-05-16 02:00:57 +0000496 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000497
Evan Chenga13aa952007-05-23 07:23:16 +0000498 if (!Proceed)
Evan Chenga6b4f432007-05-21 22:22:58 +0000499 return false;
Evan Chenga6b4f432007-05-21 22:22:58 +0000500
501 // Remove the duplicated instructions from the 'true' block.
502 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
503 Dups[i]->eraseFromParent();
Evan Chenga13aa952007-05-23 07:23:16 +0000504 --TrueBBI.NonPredSize;
Evan Chenga6b4f432007-05-21 22:22:58 +0000505 }
506
507 // Predicate the 'true' block after removing its branch.
Evan Chenga13aa952007-05-23 07:23:16 +0000508 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
509 PredicateBlock(TrueBBI, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000510
Evan Chenga6b4f432007-05-21 22:22:58 +0000511 // Predicate the 'false' block.
Evan Chenga13aa952007-05-23 07:23:16 +0000512 PredicateBlock(FalseBBI, RevCond, true);
Evan Chenga6b4f432007-05-21 22:22:58 +0000513
Evan Chenga6b4f432007-05-21 22:22:58 +0000514 // Merge the 'true' and 'false' blocks by copying the instructions
515 // from the 'false' block to the 'true' block. That is, unless the true
516 // block would clobber the predicate, in that case, do the opposite.
517 BBInfo *CvtBBI;
Evan Chenga13aa952007-05-23 07:23:16 +0000518 if (!TrueBBI.ModifyPredicate) {
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000519 // Add a conditional branch from 'true' to 'true' successor if needed.
520 if (TrueNeedBr)
521 TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL,
522 BBI.BrCond);
523 // Add an unconditional branch from 'false' to to 'false' successor if it
524 // will not be the fallthrough block.
525 if (FalseNeedBr &&
526 !isNextBlock(BBI.BB, *BBI.FalseBB->succ_begin()))
527 InsertUncondBranch(BBI.FalseBB, *BBI.FalseBB->succ_begin(), TII);
Evan Chenga6b4f432007-05-21 22:22:58 +0000528 MergeBlocks(TrueBBI, FalseBBI);
529 CvtBBI = &TrueBBI;
530 } else {
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000531 // Add a conditional branch from 'false' to 'false' successor if needed.
532 if (FalseNeedBr)
533 TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,
534 RevCond);
535 // Add an unconditional branch from 'true' to to 'true' successor if it
536 // will not be the fallthrough block.
537 if (TrueNeedBr &&
538 !isNextBlock(BBI.BB, *BBI.TrueBB->succ_begin()))
539 InsertUncondBranch(BBI.TrueBB, *BBI.TrueBB->succ_begin(), TII);
Evan Chenga6b4f432007-05-21 22:22:58 +0000540 MergeBlocks(FalseBBI, TrueBBI);
541 CvtBBI = &FalseBBI;
542 }
543
544 // Remove the conditional branch from entry to the blocks.
Evan Chenga13aa952007-05-23 07:23:16 +0000545 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000546
Evan Chenga13aa952007-05-23 07:23:16 +0000547 bool OkToIfcvt = true;
Evan Chenga6b4f432007-05-21 22:22:58 +0000548 // Merge the combined block into the entry of the diamond if the entry
549 // block is its only predecessor. Otherwise, insert an unconditional
550 // branch from entry to the if-converted block.
551 if (CvtBBI->BB->pred_size() == 1) {
Evan Chenga6b4f432007-05-21 22:22:58 +0000552 MergeBlocks(BBI, *CvtBBI);
553 CvtBBI = &BBI;
Evan Chenga13aa952007-05-23 07:23:16 +0000554 OkToIfcvt = false;
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000555 } else
556 InsertUncondBranch(BBI.BB, CvtBBI->BB, TII);
Evan Chenga6b4f432007-05-21 22:22:58 +0000557
558 // If the if-converted block fallthrough into the tail block, then
559 // fold the tail block in as well.
560 if (BBI.TailBB && CvtBBI->BB->succ_size() == 1) {
Evan Chenga13aa952007-05-23 07:23:16 +0000561 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000562 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
563 MergeBlocks(*CvtBBI, TailBBI);
564 TailBBI.Kind = ICDead;
565 }
566
Evan Chenga13aa952007-05-23 07:23:16 +0000567 // Update block info. BB may be iteratively if-converted.
568 if (OkToIfcvt) {
569 BBI.Kind = ICNotClassfied;
570 BBI.TrueBB = BBI.FalseBB = NULL;
571 BBI.BrCond.clear();
572 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
573 InvalidatePreds(BBI.BB);
574 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000575 TrueBBI.Kind = ICDead;
576 FalseBBI.Kind = ICDead;
577
578 // FIXME: Must maintain LiveIns.
579 NumIfConvBBs += 2;
580 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000581}
582
Evan Cheng4e654852007-05-16 02:00:57 +0000583/// PredicateBlock - Predicate every instruction in the block with the specified
584/// condition. If IgnoreTerm is true, skip over all terminator instructions.
Evan Chenga13aa952007-05-23 07:23:16 +0000585void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng4e654852007-05-16 02:00:57 +0000586 std::vector<MachineOperand> &Cond,
587 bool IgnoreTerm) {
Evan Chenga13aa952007-05-23 07:23:16 +0000588 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
Evan Cheng4e654852007-05-16 02:00:57 +0000589 I != E; ++I) {
Evan Chenga13aa952007-05-23 07:23:16 +0000590 MachineInstr *MI = I;
591 if (IgnoreTerm && TII->isTerminatorInstr(MI->getOpcode()))
Evan Cheng4e654852007-05-16 02:00:57 +0000592 continue;
Evan Chenga13aa952007-05-23 07:23:16 +0000593 if (TII->isPredicated(MI))
594 continue;
595 if (!TII->PredicateInstruction(MI, Cond)) {
Evan Chengd6ddc302007-05-16 21:54:37 +0000596 cerr << "Unable to predication " << *I << "!\n";
597 abort();
598 }
Evan Cheng4e654852007-05-16 02:00:57 +0000599 }
Evan Chenga13aa952007-05-23 07:23:16 +0000600
601 BBI.NonPredSize = 0;
Evan Cheng4e654852007-05-16 02:00:57 +0000602}
603
Evan Cheng86cbfea2007-05-18 00:20:58 +0000604/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Evan Cheng4e654852007-05-16 02:00:57 +0000605///
Evan Cheng86cbfea2007-05-18 00:20:58 +0000606void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
607 ToBBI.BB->splice(ToBBI.BB->end(),
608 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +0000609
610 // If FromBBI is previously a successor, remove it from ToBBI's successor
611 // list and update its TrueBB / FalseBB field if needed.
612 if (ToBBI.BB->isSuccessor(FromBBI.BB))
613 ToBBI.BB->removeSuccessor(FromBBI.BB);
614
615 // Transfer preds / succs and update size.
Evan Cheng86cbfea2007-05-18 00:20:58 +0000616 TransferPreds(ToBBI.BB, FromBBI.BB);
617 TransferSuccs(ToBBI.BB, FromBBI.BB);
Evan Chenga13aa952007-05-23 07:23:16 +0000618 ToBBI.NonPredSize += FromBBI.NonPredSize;
619 FromBBI.NonPredSize = 0;
Evan Cheng4e654852007-05-16 02:00:57 +0000620}