blob: f2154bce8980d5bd58478962f16de6821daebe2f [file] [log] [blame]
Evan Chengf5e53a52007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the machine instruction level if-conversion pass.
11//
12//===----------------------------------------------------------------------===//
13
Evan Chengf5e53a52007-05-16 02:00:57 +000014#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "BranchFolding.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallSet.h"
18#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000019#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000020#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000021#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000023#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000026#include "llvm/CodeGen/TargetSchedule.h"
Evan Cheng8264e272011-06-29 01:14:12 +000027#include "llvm/MC/MCInstrItineraries.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000028#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000029#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000030#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetLowering.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000036#include "llvm/Target/TargetSubtargetInfo.h"
37
Evan Chengf5e53a52007-05-16 02:00:57 +000038using namespace llvm;
39
Chandler Carruth1b9dde02014-04-22 02:02:50 +000040#define DEBUG_TYPE "ifcvt"
41
Chris Lattner769c86b2008-01-07 05:40:58 +000042// Hidden options for help debugging.
43static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
44static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
45static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000046static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000047 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000048static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000049 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000050static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000051 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000052static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000053 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000054static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000055 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000056static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000057 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000058static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000059 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000060static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
61 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000062
Evan Cheng2117d1f2007-06-09 01:03:43 +000063STATISTIC(NumSimple, "Number of simple if-conversions performed");
64STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
65STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000066STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000067STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
68STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
69STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
70STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000071STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000072STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000073
74namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000075 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000076 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000077 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000078 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000079 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
80 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000081 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000082 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000083 ICTriangle, // BB is entry of a triangle sub-CFG.
Evan Cheng4dd31a72007-06-11 22:26:22 +000084 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Chengf5e53a52007-05-16 02:00:57 +000085 };
86
87 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
88 /// if-conversion feasibility analysis. This includes results from
89 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000090 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000091 /// diamond shape), its size, whether it's predicable, and whether any
92 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000093 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +000094 /// IsDone - True if BB is not to be considered for ifcvt.
95 /// IsBeingAnalyzed - True if BB is currently being analyzed.
96 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
97 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
98 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
99 /// HasFallThrough - True if BB may fallthrough to the following BB.
100 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000101 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000102 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000103 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000104 /// ExtraCost - Extra cost for multi-cycle instructions.
105 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000106 /// BB - Corresponding MachineBasicBlock.
107 /// TrueBB / FalseBB- See AnalyzeBranch().
108 /// BrCond - Conditions for end of block conditional branches.
109 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000110 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000111 bool IsDone : 1;
112 bool IsBeingAnalyzed : 1;
113 bool IsAnalyzed : 1;
114 bool IsEnqueued : 1;
115 bool IsBrAnalyzable : 1;
116 bool HasFallThrough : 1;
117 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000118 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000119 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000120 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000121 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000122 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000123 MachineBasicBlock *BB;
124 MachineBasicBlock *TrueBB;
125 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000126 SmallVector<MachineOperand, 4> BrCond;
127 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000128 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000129 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
130 HasFallThrough(false), IsUnpredicable(false),
Evan Cheng23402fc2007-06-15 21:18:05 +0000131 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Craig Topperc0196b12014-04-14 00:51:57 +0000132 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
133 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000134 };
135
Bob Wilson59475732010-06-15 18:19:27 +0000136 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000137 /// BBI - Corresponding BBInfo.
138 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000139 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000140 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000141 /// NumDups - Number of instructions that would be duplicated due
142 /// to this if-conversion. (For diamonds, the number of
143 /// identical instructions at the beginnings of both
144 /// paths).
145 /// NumDups2 - For diamonds, the number of identical instructions
146 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000147 struct IfcvtToken {
148 BBInfo &BBI;
149 IfcvtKind Kind;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000150 bool NeedSubsumption;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000151 unsigned NumDups;
152 unsigned NumDups2;
153 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson2371f4f2009-05-13 23:25:24 +0000154 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000155 };
156
157 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
158 /// basic block number.
159 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000160 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000161
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000162 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000163 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000164 const TargetRegisterInfo *TRI;
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000165 const MachineBlockFrequencyInfo *MBFI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000166 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000167 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000168
Juergen Ributzka310034e2013-12-14 06:52:56 +0000169 LivePhysRegs Redefs;
170 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000171
Evan Chengc5adcca2012-06-08 21:53:50 +0000172 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000173 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000174 int FnNum;
Evan Chengf5e53a52007-05-16 02:00:57 +0000175 public:
176 static char ID;
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000177 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
178 initializeIfConverterPass(*PassRegistry::getPassRegistry());
179 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000180
Craig Topper4584cd52014-03-07 09:26:03 +0000181 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000182 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000183 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000184 MachineFunctionPass::getAnalysisUsage(AU);
185 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000186
Craig Topper4584cd52014-03-07 09:26:03 +0000187 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000188
189 private:
Evan Cheng312b7232007-06-04 06:47:22 +0000190 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersonf31f33e2010-10-01 22:45:50 +0000191 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000192 const BranchProbability &Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000193 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000194 bool FalseBranch, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000195 const BranchProbability &Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000196 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
197 unsigned &Dups1, unsigned &Dups2) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000198 void ScanInstructions(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000199 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
200 std::vector<IfcvtToken*> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000201 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng7783f822007-06-08 09:36:04 +0000202 bool isTriangle = false, bool RevBranch = false);
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000203 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000204 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000205 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000206 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
207 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000208 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
209 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000210 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000211 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000212 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000213 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000214 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000215 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000216 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000217 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000218
Evan Chengdebf9c52010-11-03 00:45:17 +0000219 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
220 unsigned Cycle, unsigned Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000221 const BranchProbability &Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000222 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000223 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000224 }
225
Evan Chengdebf9c52010-11-03 00:45:17 +0000226 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
227 unsigned TCycle, unsigned TExtra,
228 MachineBasicBlock &FBB,
229 unsigned FCycle, unsigned FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000230 const BranchProbability &Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000231 return TCycle > 0 && FCycle > 0 &&
232 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000233 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000234 }
235
Evan Chengbe9859e2007-06-07 02:12:15 +0000236 // blockAlwaysFallThrough - Block ends without a terminator.
237 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000238 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000239 }
240
Evan Cheng3a51c852007-06-16 09:34:52 +0000241 // IfcvtTokenCmp - Used to sort if-conversion candidates.
242 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000243 int Incr1 = (C1->Kind == ICDiamond)
244 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
245 int Incr2 = (C2->Kind == ICDiamond)
246 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
247 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000248 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000249 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000250 // Favors subsumption.
251 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
Evan Cheng3a51c852007-06-16 09:34:52 +0000252 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000253 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000254 // Favors diamond over triangle, etc.
255 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
256 return true;
257 else if (C1->Kind == C2->Kind)
258 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
259 }
260 }
261 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000262 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000263 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000264
Evan Chengf5e53a52007-05-16 02:00:57 +0000265 char IfConverter::ID = 0;
266}
267
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000268char &llvm::IfConverterID = IfConverter::ID;
269
Owen Anderson8ac477f2010-10-12 19:48:12 +0000270INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000271INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000272INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000273
Evan Chengf5e53a52007-05-16 02:00:57 +0000274bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Eric Christopherfc6de422014-08-05 02:39:49 +0000275 TLI = MF.getSubtarget().getTargetLowering();
276 TII = MF.getSubtarget().getInstrInfo();
277 TRI = MF.getSubtarget().getRegisterInfo();
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000278 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000279 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000280 MRI = &MF.getRegInfo();
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000281
282 const TargetSubtargetInfo &ST =
283 MF.getTarget().getSubtarget<TargetSubtargetInfo>();
Pete Cooper11759452014-09-02 17:43:54 +0000284 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000285
Evan Chengf5e53a52007-05-16 02:00:57 +0000286 if (!TII) return false;
287
Evan Chengc5adcca2012-06-08 21:53:50 +0000288 PreRegAlloc = MRI->isSSA();
289
290 bool BFChange = false;
291 if (!PreRegAlloc) {
292 // Tail merge tend to expose more if-conversion opportunities.
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000293 BranchFolder BF(true, false, *MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000294 BFChange = BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
295 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000296 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000297
David Greene72e47cd2010-01-04 22:02:01 +0000298 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000299 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000300
301 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000302 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000303 return false;
304 }
David Greene72e47cd2010-01-04 22:02:01 +0000305 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000306
Evan Chengf5e53a52007-05-16 02:00:57 +0000307 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000308 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000309
Evan Cheng3a51c852007-06-16 09:34:52 +0000310 std::vector<IfcvtToken*> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000311 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000312 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
313 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
314 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000315 // Do an initial analysis for each basic block and find all the potential
316 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000317 bool Change = false;
318 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000319 while (!Tokens.empty()) {
320 IfcvtToken *Token = Tokens.back();
321 Tokens.pop_back();
322 BBInfo &BBI = Token->BBI;
323 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000324 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000325 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000326
327 delete Token;
Evan Cheng312b7232007-06-04 06:47:22 +0000328
Evan Cheng4dd31a72007-06-11 22:26:22 +0000329 // If the block has been evicted out of the queue or it has already been
330 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000331 if (BBI.IsDone)
332 BBI.IsEnqueued = false;
333 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000334 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000335
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000336 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000337
Evan Cheng312b7232007-06-04 06:47:22 +0000338 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000339 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000340 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000341 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000342 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000343 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000344 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000345 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
346 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000347 << "): BB#" << BBI.BB->getNumber() << " ("
348 << ((Kind == ICSimpleFalse)
349 ? BBI.FalseBB->getNumber()
350 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000351 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000352 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000353 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000354 if (isFalse) ++NumSimpleFalse;
355 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000356 }
Evan Cheng312b7232007-06-04 06:47:22 +0000357 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000358 }
Evan Chengd0e66912007-05-23 07:23:16 +0000359 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000360 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000361 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000362 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000363 bool isFalse = Kind == ICTriangleFalse;
364 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000365 if (DisableTriangle && !isFalse && !isRev) break;
366 if (DisableTriangleR && !isFalse && isRev) break;
367 if (DisableTriangleF && isFalse && !isRev) break;
368 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000369 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000370 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000371 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000372 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000373 DEBUG(dbgs() << " rev");
374 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000375 << BBI.TrueBB->getNumber() << ",F:"
376 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000377 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000378 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000379 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000380 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000381 if (isRev) ++NumTriangleFRev;
382 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000383 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000384 if (isRev) ++NumTriangleRev;
385 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000386 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000387 }
Evan Chengd0e66912007-05-23 07:23:16 +0000388 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000389 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000390 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000391 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000392 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000393 << BBI.TrueBB->getNumber() << ",F:"
394 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000395 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000396 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000397 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000398 break;
399 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000400 }
401
Evan Cheng312b7232007-06-04 06:47:22 +0000402 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000403
Evan Cheng92fb5452007-06-15 07:36:12 +0000404 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
405 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
406 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000407 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000408 }
Evan Chengd0e66912007-05-23 07:23:16 +0000409
Evan Chengd0e66912007-05-23 07:23:16 +0000410 if (!Change)
411 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000412 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000413 }
Evan Cheng478b8052007-05-18 01:55:58 +0000414
Evan Cheng3a51c852007-06-16 09:34:52 +0000415 // Delete tokens in case of early exit.
416 while (!Tokens.empty()) {
417 IfcvtToken *Token = Tokens.back();
418 Tokens.pop_back();
419 delete Token;
420 }
421
422 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000423 BBAnalysis.clear();
424
Evan Chengcf9e8a92010-06-18 22:17:13 +0000425 if (MadeChange && IfCvtBranchFold) {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000426 BranchFolder BF(false, false, *MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000427 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000428 getAnalysisIfAvailable<MachineModuleInfo>());
429 }
430
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000431 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000432 return MadeChange;
433}
434
Evan Cheng3a51c852007-06-16 09:34:52 +0000435/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
436/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000437static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000438 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000439 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
440 E = BB->succ_end(); SI != E; ++SI) {
441 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000442 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000443 return SuccBB;
444 }
Craig Topperc0196b12014-04-14 00:51:57 +0000445 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000446}
447
Evan Cheng3a51c852007-06-16 09:34:52 +0000448/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000449/// branch. Swap block's 'true' and 'false' successors.
Evan Cheng312b7232007-06-04 06:47:22 +0000450bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000451 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000452 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
453 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000454 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000455 std::swap(BBI.TrueBB, BBI.FalseBB);
456 return true;
457 }
458 return false;
459}
460
Evan Cheng2117d1f2007-06-09 01:03:43 +0000461/// getNextBlock - Returns the next block in the function blocks ordering. If
462/// it is the end, returns NULL.
463static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
464 MachineFunction::iterator I = BB;
465 MachineFunction::iterator E = BB->getParent()->end();
466 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000467 return nullptr;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000468 return I;
469}
470
Evan Cheng7783f822007-06-08 09:36:04 +0000471/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000472/// predecessor) forms a valid simple shape for ifcvt. It also returns the
473/// number of instructions that the ifcvt would need to duplicate if performed
474/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000475bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000476 const BranchProbability &Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000477 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000478 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000479 return false;
480
Evan Chenga955c022007-06-19 21:45:13 +0000481 if (TrueBBI.IsBrAnalyzable)
482 return false;
483
Evan Cheng23402fc2007-06-15 21:18:05 +0000484 if (TrueBBI.BB->pred_size() > 1) {
485 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000486 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000487 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000488 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000489 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000490 }
491
Evan Chenga955c022007-06-19 21:45:13 +0000492 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000493}
494
Evan Cheng7783f822007-06-08 09:36:04 +0000495/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000496/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000497/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000498/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000499/// returns the number of instructions that the ifcvt would need to duplicate
500/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000501bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000502 bool FalseBranch, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000503 const BranchProbability &Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000504 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000505 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000506 return false;
507
Evan Cheng23402fc2007-06-15 21:18:05 +0000508 if (TrueBBI.BB->pred_size() > 1) {
509 if (TrueBBI.CannotBeCopied)
510 return false;
511
Evan Cheng92fb5452007-06-15 07:36:12 +0000512 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000513 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000514 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000515 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000516 --Size;
517 else {
518 MachineBasicBlock *FExit = FalseBranch
519 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
520 if (FExit)
521 // Require a conditional branch
522 ++Size;
523 }
524 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000525 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000526 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000527 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000528 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000529
Evan Cheng7783f822007-06-08 09:36:04 +0000530 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
531 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Evan Chengbe9859e2007-06-07 02:12:15 +0000532 MachineFunction::iterator I = TrueBBI.BB;
533 if (++I == TrueBBI.BB->getParent()->end())
534 return false;
Evan Cheng7783f822007-06-08 09:36:04 +0000535 TExit = I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000536 }
Evan Cheng7783f822007-06-08 09:36:04 +0000537 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000538}
539
Evan Cheng7783f822007-06-08 09:36:04 +0000540/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000541/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000542bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
543 unsigned &Dups1, unsigned &Dups2) const {
544 Dups1 = Dups2 = 0;
545 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
546 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000547 return false;
548
Evan Cheng2117d1f2007-06-09 01:03:43 +0000549 MachineBasicBlock *TT = TrueBBI.TrueBB;
550 MachineBasicBlock *FT = FalseBBI.TrueBB;
551
552 if (!TT && blockAlwaysFallThrough(TrueBBI))
553 TT = getNextBlock(TrueBBI.BB);
554 if (!FT && blockAlwaysFallThrough(FalseBBI))
555 FT = getNextBlock(FalseBBI.BB);
556 if (TT != FT)
557 return false;
Craig Topperc0196b12014-04-14 00:51:57 +0000558 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng2117d1f2007-06-09 01:03:43 +0000559 return false;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000560 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
561 return false;
562
563 // FIXME: Allow true block to have an early exit?
564 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
565 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000566 return false;
567
Bob Wilsone1961fe2010-10-26 00:02:24 +0000568 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach6201b992010-06-07 21:28:55 +0000569 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
570 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilsone1961fe2010-10-26 00:02:24 +0000571 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
572 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
573 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000574 // Skip dbg_value instructions. These do not count.
Bob Wilsone1961fe2010-10-26 00:02:24 +0000575 if (TIB->isDebugValue()) {
576 while (TIB != TIE && TIB->isDebugValue())
577 ++TIB;
578 if (TIB == TIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000579 break;
580 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000581 if (FIB->isDebugValue()) {
582 while (FIB != FIE && FIB->isDebugValue())
583 ++FIB;
584 if (FIB == FIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000585 break;
586 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000587 if (!TIB->isIdenticalTo(FIB))
588 break;
589 ++Dups1;
590 ++TIB;
591 ++FIB;
592 }
593
594 // Now, in preparation for counting duplicate instructions at the ends of the
595 // blocks, move the end iterators up past any branch instructions.
596 while (TIE != TIB) {
597 --TIE;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000598 if (!TIE->isBranch())
Bob Wilsone1961fe2010-10-26 00:02:24 +0000599 break;
600 }
601 while (FIE != FIB) {
602 --FIE;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000603 if (!FIE->isBranch())
Bob Wilsone1961fe2010-10-26 00:02:24 +0000604 break;
605 }
606
607 // If Dups1 includes all of a block, then don't count duplicate
608 // instructions at the end of the blocks.
609 if (TIB == TIE || FIB == FIE)
610 return true;
611
612 // Count duplicate instructions at the ends of the blocks.
613 while (TIE != TIB && FIE != FIB) {
614 // Skip dbg_value instructions. These do not count.
615 if (TIE->isDebugValue()) {
616 while (TIE != TIB && TIE->isDebugValue())
617 --TIE;
618 if (TIE == TIB)
619 break;
620 }
621 if (FIE->isDebugValue()) {
622 while (FIE != FIB && FIE->isDebugValue())
623 --FIE;
624 if (FIE == FIB)
625 break;
626 }
627 if (!TIE->isIdenticalTo(FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000628 break;
629 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000630 --TIE;
631 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000632 }
633
634 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000635}
636
Evan Cheng4dd31a72007-06-11 22:26:22 +0000637/// ScanInstructions - Scan all the instructions in the block to determine if
638/// the block is predicable. In most cases, that means all the instructions
Chris Lattnera98c6792008-01-07 01:56:04 +0000639/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng4dd31a72007-06-11 22:26:22 +0000640/// instruction which can clobber a predicate (e.g. condition code register).
641/// If so, the block is not predicable unless it's the last instruction.
642void IfConverter::ScanInstructions(BBInfo &BBI) {
643 if (BBI.IsDone)
644 return;
645
Evan Chengc5adcca2012-06-08 21:53:50 +0000646 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000647 // First analyze the end of BB branches.
Craig Topperc0196b12014-04-14 00:51:57 +0000648 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000649 BBI.BrCond.clear();
650 BBI.IsBrAnalyzable =
651 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000652 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000653
654 if (BBI.BrCond.size()) {
655 // No false branch. This BB must end with a conditional branch and a
656 // fallthrough.
657 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000658 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000659 if (!BBI.FalseBB) {
660 // Malformed bcc? True and false blocks are the same?
661 BBI.IsUnpredicable = true;
662 return;
663 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000664 }
665
666 // Then scan all the instructions.
667 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000668 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000669 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000670 BBI.ClobbersPred = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000671 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
672 I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000673 if (I->isDebugValue())
674 continue;
675
Evan Cheng7f8e5632011-12-07 07:15:52 +0000676 if (I->isNotDuplicable())
Evan Cheng23402fc2007-06-15 21:18:05 +0000677 BBI.CannotBeCopied = true;
678
Evan Cheng4dd31a72007-06-11 22:26:22 +0000679 bool isPredicated = TII->isPredicated(I);
Evan Cheng7f8e5632011-12-07 07:15:52 +0000680 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000681
Joey Goulya5153cb2013-09-09 14:21:49 +0000682 // A conditional branch is not predicable, but it may be eliminated.
683 if (isCondBr)
684 continue;
685
686 if (!isPredicated) {
687 BBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000688 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
689 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000690 if (NumCycles > 1)
691 BBI.ExtraCost += NumCycles-1;
692 BBI.ExtraCost2 += ExtraPredCost;
693 } else if (!AlreadyPredicated) {
694 // FIXME: This instruction is already predicated before the
695 // if-conversion pass. It's probably something like a conditional move.
696 // Mark this block unpredicable for now.
697 BBI.IsUnpredicable = true;
698 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000699 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000700
701 if (BBI.ClobbersPred && !isPredicated) {
702 // Predicate modification instruction should end the block (except for
703 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000704 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000705 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000706 BBI.IsUnpredicable = true;
707 return;
708 }
709
Evan Chengfbc73092007-07-10 17:50:43 +0000710 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
711 // still potentially predicable.
712 std::vector<MachineOperand> PredDefs;
713 if (TII->DefinesPredicate(I, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000714 BBI.ClobbersPred = true;
715
Evan Cheng1f4062f2009-11-21 06:20:26 +0000716 if (!TII->isPredicable(I)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000717 BBI.IsUnpredicable = true;
718 return;
719 }
720 }
721}
722
723/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
724/// predicated by the specified predicate.
725bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000726 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng4dd31a72007-06-11 22:26:22 +0000727 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000728 // If the block is dead or unpredicable, then it cannot be predicated.
729 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000730 return false;
731
Quentin Colombetbdab2272013-07-24 20:20:37 +0000732 // If it is already predicated, check if the new predicate subsumes
733 // its predicate.
734 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000735 return false;
736
737 if (BBI.BrCond.size()) {
738 if (!isTriangle)
739 return false;
740
Bob Wilson2371f4f2009-05-13 23:25:24 +0000741 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000742 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
743 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000744 if (RevBranch) {
745 if (TII->ReverseBranchCondition(Cond))
746 return false;
747 }
748 if (TII->ReverseBranchCondition(RevPred) ||
749 !TII->SubsumesPredicate(Cond, RevPred))
750 return false;
751 }
752
753 return true;
754}
755
Evan Cheng7783f822007-06-08 09:36:04 +0000756/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +0000757/// the specified block. Record its successors and whether it looks like an
758/// if-conversion candidate.
Evan Cheng3a51c852007-06-16 09:34:52 +0000759IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
760 std::vector<IfcvtToken*> &Tokens) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000761 BBInfo &BBI = BBAnalysis[BB->getNumber()];
762
Evan Cheng4dd31a72007-06-11 22:26:22 +0000763 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
764 return BBI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000765
Evan Cheng4dd31a72007-06-11 22:26:22 +0000766 BBI.BB = BB;
767 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000768
769 ScanInstructions(BBI);
770
Jakub Staszaka4a18f02011-07-10 02:00:16 +0000771 // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
772 // considered for ifcvt anymore.
773 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000774 BBI.IsBeingAnalyzed = false;
775 BBI.IsAnalyzed = true;
776 return BBI;
Evan Cheng9030b982007-06-06 10:16:17 +0000777 }
778
Evan Cheng4dd31a72007-06-11 22:26:22 +0000779 // Do not ifcvt if either path is a back edge to the entry block.
780 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
781 BBI.IsBeingAnalyzed = false;
782 BBI.IsAnalyzed = true;
783 return BBI;
784 }
785
Evan Chengb9bff582009-06-15 21:24:34 +0000786 // Do not ifcvt if true and false fallthrough blocks are the same.
787 if (!BBI.FalseBB) {
788 BBI.IsBeingAnalyzed = false;
789 BBI.IsAnalyzed = true;
790 return BBI;
791 }
792
Evan Cheng3a51c852007-06-16 09:34:52 +0000793 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
794 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000795
796 if (TrueBBI.IsDone && FalseBBI.IsDone) {
797 BBI.IsBeingAnalyzed = false;
798 BBI.IsAnalyzed = true;
799 return BBI;
800 }
801
Owen Anderson4f6bf042008-08-14 22:49:33 +0000802 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng312b7232007-06-04 06:47:22 +0000803 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
Evan Cheng7783f822007-06-08 09:36:04 +0000804
Evan Cheng3a51c852007-06-16 09:34:52 +0000805 unsigned Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000806 unsigned Dups2 = 0;
Evan Chengc5adcca2012-06-08 21:53:50 +0000807 bool TNeedSub = !TrueBBI.Predicate.empty();
808 bool FNeedSub = !FalseBBI.Predicate.empty();
Evan Cheng3a51c852007-06-16 09:34:52 +0000809 bool Enqueued = false;
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000810
Jakub Staszak15e5b742011-08-03 22:34:43 +0000811 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
812
Evan Cheng51eb2c32007-06-18 08:37:25 +0000813 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000814 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000815 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
Bob Wilsonefd360c2010-10-26 00:02:21 +0000816 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000817 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000818 Prediction) &&
Evan Cheng7783f822007-06-08 09:36:04 +0000819 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
820 FeasibilityAnalysis(FalseBBI, RevCond)) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000821 // Diamond:
822 // EBB
823 // / \_
824 // | |
825 // TBB FBB
826 // \ /
Evan Cheng0f745da2007-05-18 00:20:58 +0000827 // TailBB
Evan Cheng79484222007-06-05 23:46:14 +0000828 // Note TailBB can be empty.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000829 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
830 Dups2));
Evan Cheng3a51c852007-06-16 09:34:52 +0000831 Enqueued = true;
832 }
833
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000834 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000835 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000836 TrueBBI.ExtraCost2, Prediction) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000837 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
838 // Triangle:
839 // EBB
840 // | \_
841 // | |
842 // | TBB
843 // | /
844 // FBB
845 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
846 Enqueued = true;
847 }
Bob Wilson81051442010-06-15 22:18:54 +0000848
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000849 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000850 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000851 TrueBBI.ExtraCost2, Prediction) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000852 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
853 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
854 Enqueued = true;
855 }
856
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000857 if (ValidSimple(TrueBBI, Dups, Prediction) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000858 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000859 TrueBBI.ExtraCost2, Prediction) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000860 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
861 // Simple (split, no rejoin):
862 // EBB
863 // | \_
864 // | |
865 // | TBB---> exit
Bob Wilson81051442010-06-15 22:18:54 +0000866 // |
Evan Cheng3a51c852007-06-16 09:34:52 +0000867 // FBB
868 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
869 Enqueued = true;
870 }
871
872 if (CanRevCond) {
873 // Try the other path...
Owen Andersonf31f33e2010-10-01 22:45:50 +0000874 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000875 Prediction.getCompl()) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000876 MeetIfcvtSizeLimit(*FalseBBI.BB,
877 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000878 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000879 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
880 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
881 Enqueued = true;
882 }
883
Owen Andersonf31f33e2010-10-01 22:45:50 +0000884 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000885 Prediction.getCompl()) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000886 MeetIfcvtSizeLimit(*FalseBBI.BB,
887 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000888 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000889 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
890 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
891 Enqueued = true;
892 }
893
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000894 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000895 MeetIfcvtSizeLimit(*FalseBBI.BB,
896 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000897 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000898 FeasibilityAnalysis(FalseBBI, RevCond)) {
899 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
900 Enqueued = true;
Evan Cheng312b7232007-06-04 06:47:22 +0000901 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000902 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000903
Evan Cheng3a51c852007-06-16 09:34:52 +0000904 BBI.IsEnqueued = Enqueued;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000905 BBI.IsBeingAnalyzed = false;
906 BBI.IsAnalyzed = true;
907 return BBI;
Evan Cheng2e82cef2007-05-18 18:14:37 +0000908}
909
Evan Cheng905a8f42007-05-30 19:49:19 +0000910/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000911/// candidates.
912void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Cheng3a51c852007-06-16 09:34:52 +0000913 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng9808d312011-04-27 19:32:43 +0000914 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
915 MachineBasicBlock *BB = I;
916 AnalyzeBlock(BB, Tokens);
Evan Chengf5e53a52007-05-16 02:00:57 +0000917 }
Evan Cheng905a8f42007-05-30 19:49:19 +0000918
Evan Cheng20e05992007-06-01 00:12:12 +0000919 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +0000920 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +0000921}
922
Evan Cheng288f1542007-06-08 22:01:07 +0000923/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
924/// that all the intervening blocks are empty (given BB can fall through to its
925/// next block).
926static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Chengf128bdc2010-06-16 07:35:02 +0000927 MachineFunction::iterator PI = BB;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000928 MachineFunction::iterator I = std::next(PI);
Evan Cheng2c1acd62007-06-05 07:05:25 +0000929 MachineFunction::iterator TI = ToBB;
930 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +0000931 while (I != TI) {
932 // Check isSuccessor to avoid case where the next block is empty, but
933 // it's not a successor.
934 if (I == E || !I->empty() || !PI->isSuccessor(I))
Evan Cheng312b7232007-06-04 06:47:22 +0000935 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +0000936 PI = I++;
937 }
Evan Cheng312b7232007-06-04 06:47:22 +0000938 return true;
Evan Chenge26c0912007-05-21 22:22:58 +0000939}
940
Evan Cheng51eb2c32007-06-18 08:37:25 +0000941/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
942/// to determine if it can be if-converted. If predecessor is already enqueued,
943/// dequeue it!
944void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +0000945 for (const auto &Predecessor : BB->predecessors()) {
946 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +0000947 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +0000948 continue;
Evan Chengadd97762007-06-14 23:34:09 +0000949 PBBI.IsAnalyzed = false;
950 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +0000951 }
952}
953
Evan Chengc2237ce2007-05-29 22:31:16 +0000954/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
955///
956static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
957 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000958 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +0000959 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +0000960 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +0000961}
962
Evan Cheng288f1542007-06-08 22:01:07 +0000963/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
964/// successors.
965void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +0000966 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000967 SmallVector<MachineOperand, 4> Cond;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000968 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
969 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +0000970}
971
Matthias Braund616ccc2013-10-11 19:04:37 +0000972/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
973/// values defined in MI which are not live/used by MI.
Juergen Ributzka310034e2013-12-14 06:52:56 +0000974static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) {
Matthias Braund616ccc2013-10-11 19:04:37 +0000975 for (ConstMIBundleOperands Ops(MI); Ops.isValid(); ++Ops) {
976 if (!Ops->isReg() || !Ops->isKill())
977 continue;
978 unsigned Reg = Ops->getReg();
979 if (Reg == 0)
980 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +0000981 Redefs.removeReg(Reg);
Evan Chengf128bdc2010-06-16 07:35:02 +0000982 }
Matthias Braund616ccc2013-10-11 19:04:37 +0000983 for (MIBundleOperands Ops(MI); Ops.isValid(); ++Ops) {
984 if (!Ops->isReg() || !Ops->isDef())
985 continue;
986 unsigned Reg = Ops->getReg();
Juergen Ributzka310034e2013-12-14 06:52:56 +0000987 if (Reg == 0 || Redefs.contains(Reg))
Matthias Braund616ccc2013-10-11 19:04:37 +0000988 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +0000989 Redefs.addReg(Reg);
Matthias Braund616ccc2013-10-11 19:04:37 +0000990
991 MachineOperand &Op = *Ops;
992 MachineInstr *MI = Op.getParent();
993 MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
994 MIB.addReg(Reg, RegState::Implicit | RegState::Undef);
995 }
996}
997
998/**
999 * Remove kill flags from operands with a registers in the @p DontKill set.
1000 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001001static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001002 for (MIBundleOperands O(&MI); O.isValid(); ++O) {
1003 if (!O->isReg() || !O->isKill())
1004 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001005 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001006 O->setIsKill(false);
1007 }
1008}
1009
1010/**
1011 * Walks a range of machine instructions and removes kill flags for registers
1012 * in the @p DontKill set.
1013 */
1014static void RemoveKills(MachineBasicBlock::iterator I,
1015 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001016 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001017 const MCRegisterInfo &MCRI) {
1018 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001019 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001020}
1021
Evan Cheng312b7232007-06-04 06:47:22 +00001022/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001023///
Evan Cheng3a51c852007-06-16 09:34:52 +00001024bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001025 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1026 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1027 BBInfo *CvtBBI = &TrueBBI;
1028 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001029
Owen Anderson4f6bf042008-08-14 22:49:33 +00001030 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001031 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001032 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001033
Evan Cheng51eb2c32007-06-18 08:37:25 +00001034 if (CvtBBI->IsDone ||
1035 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001036 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001037 BBI.IsAnalyzed = false;
1038 CvtBBI->IsAnalyzed = false;
1039 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001040 }
Evan Chengd0e66912007-05-23 07:23:16 +00001041
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001042 if (CvtBBI->BB->hasAddressTaken())
1043 // Conservatively abort if-conversion if BB's address is taken.
1044 return false;
1045
Evan Cheng3a51c852007-06-16 09:34:52 +00001046 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001047 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001048 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001049
Bob Wilson45814342010-06-19 05:33:57 +00001050 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001051 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001052 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001053 Redefs.addLiveIns(CvtBBI->BB);
1054 Redefs.addLiveIns(NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001055
1056 // Compute a set of registers which must not be killed by instructions in
1057 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001058 DontKill.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001059 DontKill.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001060
Evan Cheng92fb5452007-06-15 07:36:12 +00001061 if (CvtBBI->BB->pred_size() > 1) {
1062 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001063 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001064 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001065 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001066
1067 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1068 // explicitly remove CvtBBI as a successor.
1069 BBI.BB->removeSuccessor(CvtBBI->BB);
Evan Cheng92fb5452007-06-15 07:36:12 +00001070 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001071 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001072 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001073
Evan Cheng92fb5452007-06-15 07:36:12 +00001074 // Merge converted block into entry block.
1075 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1076 MergeBlocks(BBI, *CvtBBI);
1077 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001078
Evan Chenge4ec9182007-06-06 02:08:52 +00001079 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001080 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001081 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001082 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001083 // Now ifcvt'd block will look like this:
1084 // BB:
1085 // ...
1086 // t, f = cmp
1087 // if t op
1088 // b BBf
1089 //
1090 // We cannot further ifcvt this block because the unconditional branch
1091 // will have to be predicated on the new condition, that will not be
1092 // available if cmp executes.
1093 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001094 }
Evan Chenge26c0912007-05-21 22:22:58 +00001095
Evan Cheng288f1542007-06-08 22:01:07 +00001096 RemoveExtraEdges(BBI);
1097
Evan Chengd0e66912007-05-23 07:23:16 +00001098 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001099 if (!IterIfcvt)
1100 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001101 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001102 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001103
1104 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001105 return true;
1106}
1107
Manman Renb6819182014-01-29 23:18:47 +00001108/// Scale down weights to fit into uint32_t. NewTrue is the new weight
1109/// for successor TrueBB, and NewFalse is the new weight for successor
1110/// FalseBB.
1111static void ScaleWeights(uint64_t NewTrue, uint64_t NewFalse,
1112 MachineBasicBlock *MBB,
1113 const MachineBasicBlock *TrueBB,
1114 const MachineBasicBlock *FalseBB,
1115 const MachineBranchProbabilityInfo *MBPI) {
1116 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1117 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1118 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1119 SE = MBB->succ_end();
1120 SI != SE; ++SI) {
1121 if (*SI == TrueBB)
1122 MBB->setSuccWeight(SI, (uint32_t)(NewTrue / Scale));
1123 else if (*SI == FalseBB)
1124 MBB->setSuccWeight(SI, (uint32_t)(NewFalse / Scale));
1125 else
1126 MBB->setSuccWeight(SI, MBPI->getEdgeWeight(MBB, SI) / Scale);
1127 }
1128}
1129
Evan Chengaf716102007-05-16 21:54:37 +00001130/// IfConvertTriangle - If convert a triangle sub-CFG.
1131///
Evan Cheng3a51c852007-06-16 09:34:52 +00001132bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001133 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001134 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1135 BBInfo *CvtBBI = &TrueBBI;
1136 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001137 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001138
Owen Anderson4f6bf042008-08-14 22:49:33 +00001139 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001140 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001141 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001142
Evan Cheng51eb2c32007-06-18 08:37:25 +00001143 if (CvtBBI->IsDone ||
1144 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001145 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001146 BBI.IsAnalyzed = false;
1147 CvtBBI->IsAnalyzed = false;
1148 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001149 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001150
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001151 if (CvtBBI->BB->hasAddressTaken())
1152 // Conservatively abort if-conversion if BB's address is taken.
1153 return false;
1154
Evan Cheng3a51c852007-06-16 09:34:52 +00001155 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001156 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001157 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001158
Evan Cheng3a51c852007-06-16 09:34:52 +00001159 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001160 if (ReverseBranchCondition(*CvtBBI)) {
1161 // BB has been changed, modify its predecessors (except for this
1162 // one) so they don't get ifcvt'ed based on bad intel.
1163 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1164 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1165 MachineBasicBlock *PBB = *PI;
1166 if (PBB == BBI.BB)
1167 continue;
1168 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1169 if (PBBI.IsEnqueued) {
1170 PBBI.IsAnalyzed = false;
1171 PBBI.IsEnqueued = false;
1172 }
Evan Chengadd97762007-06-14 23:34:09 +00001173 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001174 }
1175 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001176
Bob Wilson45814342010-06-19 05:33:57 +00001177 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001178 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001179 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001180 Redefs.addLiveIns(CvtBBI->BB);
1181 Redefs.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001182
Andrew Trick276dd452013-10-14 20:45:17 +00001183 DontKill.clear();
1184
Craig Topperc0196b12014-04-14 00:51:57 +00001185 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Manman Ren37c92672014-02-07 00:38:56 +00001186 uint64_t CvtNext = 0, CvtFalse = 0, BBNext = 0, BBCvt = 0, SumWeight = 0;
Manman Renb6819182014-01-29 23:18:47 +00001187 uint32_t WeightScale = 0;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001188
Manman Renb6819182014-01-29 23:18:47 +00001189 if (HasEarlyExit) {
Manman Ren37c92672014-02-07 00:38:56 +00001190 // Get weights before modifying CvtBBI->BB and BBI.BB.
Manman Renb6819182014-01-29 23:18:47 +00001191 CvtNext = MBPI->getEdgeWeight(CvtBBI->BB, NextBBI->BB);
1192 CvtFalse = MBPI->getEdgeWeight(CvtBBI->BB, CvtBBI->FalseBB);
Manman Ren37c92672014-02-07 00:38:56 +00001193 BBNext = MBPI->getEdgeWeight(BBI.BB, NextBBI->BB);
1194 BBCvt = MBPI->getEdgeWeight(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001195 SumWeight = MBPI->getSumForBlock(CvtBBI->BB, WeightScale);
1196 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001197
Bob Wilson1e5da552010-06-29 00:55:23 +00001198 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001199 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001200 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001201 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001202 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001203
1204 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1205 // explicitly remove CvtBBI as a successor.
1206 BBI.BB->removeSuccessor(CvtBBI->BB);
Evan Cheng92fb5452007-06-15 07:36:12 +00001207 } else {
1208 // Predicate the 'true' block after removing its branch.
1209 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001210 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001211
Evan Cheng0598b2d2007-06-18 22:44:57 +00001212 // Now merge the entry of the triangle with the true block.
1213 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001214 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001215 }
1216
Evan Cheng312b7232007-06-04 06:47:22 +00001217 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001218 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001219 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1220 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001221 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001222 llvm_unreachable("Unable to reverse branch condition!");
Craig Topperc0196b12014-04-14 00:51:57 +00001223 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001224 BBI.BB->addSuccessor(CvtBBI->FalseBB);
Manman Renb6819182014-01-29 23:18:47 +00001225 // Update the edge weight for both CvtBBI->FalseBB and NextBBI.
1226 // New_Weight(BBI.BB, NextBBI->BB) =
1227 // Weight(BBI.BB, NextBBI->BB) * getSumForBlock(CvtBBI->BB) +
1228 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, NextBBI->BB)
1229 // New_Weight(BBI.BB, CvtBBI->FalseBB) =
1230 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, CvtBBI->FalseBB)
1231
Manman Renb6819182014-01-29 23:18:47 +00001232 uint64_t NewNext = BBNext * SumWeight + (BBCvt * CvtNext) / WeightScale;
1233 uint64_t NewFalse = (BBCvt * CvtFalse) / WeightScale;
1234 // We need to scale down all weights of BBI.BB to fit uint32_t.
1235 // Here BBI.BB is connected to CvtBBI->FalseBB and will fall through to
1236 // the next block.
1237 ScaleWeights(NewNext, NewFalse, BBI.BB, getNextBlock(BBI.BB),
1238 CvtBBI->FalseBB, MBPI);
Evan Cheng92fb5452007-06-15 07:36:12 +00001239 }
Evan Cheng7783f822007-06-08 09:36:04 +00001240
1241 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001242 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001243 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001244 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001245 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001246 if (!isFallThrough) {
1247 // Only merge them if the true block does not fallthrough to the false
1248 // block. By not merging them, we make it possible to iteratively
1249 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001250 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001251 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1252 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001253 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001254 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001255 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001256 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1257 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001258 }
Evan Cheng7783f822007-06-08 09:36:04 +00001259 // Mixed predicated and unpredicated code. This cannot be iteratively
1260 // predicated.
1261 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001262 }
Evan Chenge26c0912007-05-21 22:22:58 +00001263
Evan Cheng288f1542007-06-08 22:01:07 +00001264 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001265
Evan Chengd0e66912007-05-23 07:23:16 +00001266 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001267 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001268 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001269 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001270 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001271 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001272 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001273
1274 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001275 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001276}
1277
Evan Chengaf716102007-05-16 21:54:37 +00001278/// IfConvertDiamond - If convert a diamond sub-CFG.
1279///
Evan Cheng51eb2c32007-06-18 08:37:25 +00001280bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1281 unsigned NumDups1, unsigned NumDups2) {
Evan Cheng312b7232007-06-04 06:47:22 +00001282 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2e82cef2007-05-18 18:14:37 +00001283 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng3a51c852007-06-16 09:34:52 +00001284 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson2371f4f2009-05-13 23:25:24 +00001285 // True block must fall through or end with an unanalyzable terminator.
Evan Cheng3a51c852007-06-16 09:34:52 +00001286 if (!TailBB) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001287 if (blockAlwaysFallThrough(TrueBBI))
1288 TailBB = FalseBBI.TrueBB;
1289 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Chengf5e53a52007-05-16 02:00:57 +00001290 }
Evan Chenge26c0912007-05-21 22:22:58 +00001291
Evan Cheng51eb2c32007-06-18 08:37:25 +00001292 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1293 TrueBBI.BB->pred_size() > 1 ||
1294 FalseBBI.BB->pred_size() > 1) {
1295 // Something has changed. It's no longer safe to predicate these blocks.
1296 BBI.IsAnalyzed = false;
1297 TrueBBI.IsAnalyzed = false;
1298 FalseBBI.IsAnalyzed = false;
1299 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001300 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001301
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001302 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1303 // Conservatively abort if-conversion if either BB has its address taken.
1304 return false;
1305
Bob Wilson1e5da552010-06-29 00:55:23 +00001306 // Put the predicated instructions from the 'true' block before the
1307 // instructions from the 'false' block, unless the true block would clobber
1308 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001309 BBInfo *BBI1 = &TrueBBI;
1310 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001311 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001312 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001313 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001314 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1315 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001316
Evan Cheng3a51c852007-06-16 09:34:52 +00001317 // Figure out the more profitable ordering.
1318 bool DoSwap = false;
1319 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1320 DoSwap = true;
1321 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001322 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001323 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001324 }
1325 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001326 std::swap(BBI1, BBI2);
1327 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001328 }
Evan Cheng79484222007-06-05 23:46:14 +00001329
Evan Cheng51eb2c32007-06-18 08:37:25 +00001330 // Remove the conditional branch from entry to the blocks.
1331 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1332
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001333 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001334 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001335 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001336 Redefs.addLiveIns(BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001337
Evan Cheng51eb2c32007-06-18 08:37:25 +00001338 // Remove the duplicated instructions at the beginnings of both paths.
1339 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1340 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbach412800d2010-06-14 21:30:32 +00001341 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1342 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1343 // Skip dbg_value instructions
1344 while (DI1 != DIE1 && DI1->isDebugValue())
1345 ++DI1;
1346 while (DI2 != DIE2 && DI2->isDebugValue())
1347 ++DI2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001348 BBI1->NonPredSize -= NumDups1;
1349 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001350
1351 // Skip past the dups on each side separately since there may be
1352 // differing dbg_value entries.
1353 for (unsigned i = 0; i < NumDups1; ++DI1) {
1354 if (!DI1->isDebugValue())
1355 ++i;
1356 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001357 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001358 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001359 if (!DI2->isDebugValue())
1360 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001361 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001362
Matthias Braund616ccc2013-10-11 19:04:37 +00001363 // Compute a set of registers which must not be killed by instructions in BB1:
1364 // This is everything used+live in BB2 after the duplicated instructions. We
1365 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001366 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001367 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1368 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001369 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001370 }
1371
1372 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1373 ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001374 Redefs.stepForward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001375 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001376 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1377 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1378
Evan Cheng4266a792011-12-19 22:01:30 +00001379 // Remove branch from 'true' block and remove duplicated instructions.
Evan Cheng79484222007-06-05 23:46:14 +00001380 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001381 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001382 for (unsigned i = 0; i != NumDups2; ) {
1383 // NumDups2 only counted non-dbg_value instructions, so this won't
1384 // run off the head of the list.
1385 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001386 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001387 // skip dbg_value instructions
1388 if (!DI1->isDebugValue())
1389 ++i;
1390 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001391 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001392
Matthias Braund616ccc2013-10-11 19:04:37 +00001393 // Kill flags in the true block for registers living into the false block
1394 // must be removed.
1395 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1396
Evan Cheng4266a792011-12-19 22:01:30 +00001397 // Remove 'false' block branch and find the last instruction to predicate.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001398 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1399 DI2 = BBI2->BB->end();
1400 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001401 // NumDups2 only counted non-dbg_value instructions, so this won't
1402 // run off the head of the list.
1403 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001404 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001405 // skip dbg_value instructions
1406 if (!DI2->isDebugValue())
1407 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001408 }
Evan Cheng4266a792011-12-19 22:01:30 +00001409
1410 // Remember which registers would later be defined by the false block.
1411 // This allows us not to predicate instructions in the true block that would
1412 // later be re-defined. That is, rather than
1413 // subeq r0, r1, #1
1414 // addne r0, r1, #1
1415 // generate:
1416 // sub r0, r1, #1
1417 // addne r0, r1, #1
1418 SmallSet<unsigned, 4> RedefsByFalse;
1419 SmallSet<unsigned, 4> ExtUses;
1420 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1421 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1422 if (FI->isDebugValue())
1423 continue;
1424 SmallVector<unsigned, 4> Defs;
1425 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1426 const MachineOperand &MO = FI->getOperand(i);
1427 if (!MO.isReg())
1428 continue;
1429 unsigned Reg = MO.getReg();
1430 if (!Reg)
1431 continue;
1432 if (MO.isDef()) {
1433 Defs.push_back(Reg);
1434 } else if (!RedefsByFalse.count(Reg)) {
1435 // These are defined before ctrl flow reach the 'false' instructions.
1436 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001437 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1438 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001439 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001440 }
1441 }
1442
1443 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1444 unsigned Reg = Defs[i];
1445 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001446 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1447 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001448 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001449 }
1450 }
1451 }
1452 }
1453
1454 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001455 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001456
1457 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001458 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001459
Evan Cheng0598b2d2007-06-18 22:44:57 +00001460 // Merge the true block into the entry of the diamond.
Craig Topperc0196b12014-04-14 00:51:57 +00001461 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1462 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001463
Bob Wilson2371f4f2009-05-13 23:25:24 +00001464 // If the if-converted block falls through or unconditionally branches into
1465 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001466 // fold the tail block in as well. Otherwise, unless it falls through to the
1467 // tail, add a unconditional branch to it.
1468 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001469 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001470 bool CanMergeTail = !TailBBI.HasFallThrough &&
1471 !TailBBI.BB->hasAddressTaken();
Bob Wilson1e5da552010-06-29 00:55:23 +00001472 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1473 // check if there are any other predecessors besides those.
1474 unsigned NumPreds = TailBB->pred_size();
1475 if (NumPreds > 1)
1476 CanMergeTail = false;
1477 else if (NumPreds == 1 && CanMergeTail) {
1478 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1479 if (*PI != BBI1->BB && *PI != BBI2->BB)
1480 CanMergeTail = false;
1481 }
1482 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001483 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001484 TailBBI.IsDone = true;
1485 } else {
Bob Wilson1e5da552010-06-29 00:55:23 +00001486 BBI.BB->addSuccessor(TailBB);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001487 InsertUncondBranch(BBI.BB, TailBB, TII);
1488 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001489 }
Evan Chenge26c0912007-05-21 22:22:58 +00001490 }
1491
Bob Wilson1e5da552010-06-29 00:55:23 +00001492 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1493 // which can happen here if TailBB is unanalyzable and is merged, so
1494 // explicitly remove BBI1 and BBI2 as successors.
1495 BBI.BB->removeSuccessor(BBI1->BB);
1496 BBI.BB->removeSuccessor(BBI2->BB);
Evan Cheng288f1542007-06-08 22:01:07 +00001497 RemoveExtraEdges(BBI);
1498
Evan Cheng79484222007-06-05 23:46:14 +00001499 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001500 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001501 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001502
1503 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001504 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001505}
1506
Evan Cheng4266a792011-12-19 22:01:30 +00001507static bool MaySpeculate(const MachineInstr *MI,
1508 SmallSet<unsigned, 4> &LaterRedefs,
1509 const TargetInstrInfo *TII) {
1510 bool SawStore = true;
Craig Topperc0196b12014-04-14 00:51:57 +00001511 if (!MI->isSafeToMove(TII, nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001512 return false;
1513
1514 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1515 const MachineOperand &MO = MI->getOperand(i);
1516 if (!MO.isReg())
1517 continue;
1518 unsigned Reg = MO.getReg();
1519 if (!Reg)
1520 continue;
1521 if (MO.isDef() && !LaterRedefs.count(Reg))
1522 return false;
1523 }
1524
1525 return true;
1526}
1527
Evan Cheng51eb2c32007-06-18 08:37:25 +00001528/// PredicateBlock - Predicate instructions from the start of the block to the
1529/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001530void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001531 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001532 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001533 SmallSet<unsigned, 4> *LaterRedefs) {
1534 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001535 bool MaySpec = LaterRedefs != nullptr;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001536 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +00001537 if (I->isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001538 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001539 // It may be possible not to predicate an instruction if it's the 'true'
1540 // side of a diamond and the 'false' side may re-define the instruction's
1541 // defs.
1542 if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
1543 AnyUnpred = true;
1544 continue;
1545 }
1546 // If any instruction is predicated, then every instruction after it must
1547 // be predicated.
1548 MaySpec = false;
Evan Cheng312b7232007-06-04 06:47:22 +00001549 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001550#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001551 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001552#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001553 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001554 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001555
Bob Wilson45814342010-06-19 05:33:57 +00001556 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001557 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001558 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001559 }
Evan Chengd0e66912007-05-23 07:23:16 +00001560
Evan Chengdf1a4292007-06-08 19:17:12 +00001561 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1562
Evan Cheng92fb5452007-06-15 07:36:12 +00001563 BBI.IsAnalyzed = false;
1564 BBI.NonPredSize = 0;
1565
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001566 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001567 if (AnyUnpred)
1568 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001569}
1570
Evan Cheng92fb5452007-06-15 07:36:12 +00001571/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1572/// the destination block. Skip end of block branches if IgnoreBr is true.
1573void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001574 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001575 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001576 MachineFunction &MF = *ToBBI.BB->getParent();
1577
Evan Cheng92fb5452007-06-15 07:36:12 +00001578 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1579 E = FromBBI.BB->end(); I != E; ++I) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001580 // Do not copy the end of the block branches.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001581 if (IgnoreBr && I->isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001582 break;
1583
Dan Gohman3b460302008-07-07 23:14:23 +00001584 MachineInstr *MI = MF.CloneMachineInstr(I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001585 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001586 ToBBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +00001587 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
1588 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001589 if (NumCycles > 1)
1590 ToBBI.ExtraCost += NumCycles-1;
1591 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001592
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001593 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001594 if (!TII->PredicateInstruction(MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001595#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001596 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001597#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001598 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001599 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001600 }
1601
Bob Wilson45814342010-06-19 05:33:57 +00001602 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001603 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001604 UpdatePredRedefs(MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001605
1606 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001607 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001608 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001609 }
1610
Bob Wilson1e5da552010-06-29 00:55:23 +00001611 if (!IgnoreBr) {
1612 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1613 FromBBI.BB->succ_end());
1614 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001615 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001616
Bob Wilson1e5da552010-06-29 00:55:23 +00001617 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1618 MachineBasicBlock *Succ = Succs[i];
1619 // Fallthrough edge can't be transferred.
1620 if (Succ == FallThrough)
1621 continue;
1622 ToBBI.BB->addSuccessor(Succ);
1623 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001624 }
1625
Evan Cheng92fb5452007-06-15 07:36:12 +00001626 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1627 std::back_inserter(ToBBI.Predicate));
1628 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1629
1630 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1631 ToBBI.IsAnalyzed = false;
1632
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001633 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001634}
1635
Evan Cheng0f745da2007-05-18 00:20:58 +00001636/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00001637/// This will leave FromBB as an empty block, so remove all of its
1638/// successor edges except for the fall-through edge. If AddEdges is true,
1639/// i.e., when FromBBI's branch is being moved, add those successor edges to
1640/// ToBBI.
1641void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001642 assert(!FromBBI.BB->hasAddressTaken() &&
1643 "Removing a BB whose address is taken!");
1644
Evan Cheng0f745da2007-05-18 00:20:58 +00001645 ToBBI.BB->splice(ToBBI.BB->end(),
1646 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00001647
Evan Chengbe9859e2007-06-07 02:12:15 +00001648 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1649 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00001650 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001651 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng312b7232007-06-04 06:47:22 +00001652
Evan Chengbe9859e2007-06-07 02:12:15 +00001653 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1654 MachineBasicBlock *Succ = Succs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00001655 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001656 if (Succ == FallThrough)
1657 continue;
1658 FromBBI.BB->removeSuccessor(Succ);
Jakob Stoklund Olesene0ef4742013-01-24 23:59:08 +00001659 if (AddEdges && !ToBBI.BB->isSuccessor(Succ))
Bob Wilson1e5da552010-06-29 00:55:23 +00001660 ToBBI.BB->addSuccessor(Succ);
Evan Chengbe9859e2007-06-07 02:12:15 +00001661 }
1662
Bob Wilson2371f4f2009-05-13 23:25:24 +00001663 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00001664 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00001665 FromBBI.BB->addSuccessor(NBB);
1666
Evan Cheng92fb5452007-06-15 07:36:12 +00001667 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1668 std::back_inserter(ToBBI.Predicate));
1669 FromBBI.Predicate.clear();
1670
Evan Chengd0e66912007-05-23 07:23:16 +00001671 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001672 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001673 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001674 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001675 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001676 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001677
Evan Cheng4dd31a72007-06-11 22:26:22 +00001678 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001679 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001680 ToBBI.IsAnalyzed = false;
1681 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001682}