blob: c38c9d22266e721ae3e0525b018931ef90c01012 [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 Chenge93ccc02007-06-08 19:10:51 +000027#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000028#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000029#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000034#include "llvm/Target/TargetSubtargetInfo.h"
Cong Houd97c1002015-12-01 05:29:22 +000035#include <algorithm>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000036
Evan Chengf5e53a52007-05-16 02:00:57 +000037using namespace llvm;
38
Chandler Carruth1b9dde02014-04-22 02:02:50 +000039#define DEBUG_TYPE "ifcvt"
40
Chris Lattner769c86b2008-01-07 05:40:58 +000041// Hidden options for help debugging.
42static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
43static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
44static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000045static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000046 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000047static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000048 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000049static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000050 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000051static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000052 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000053static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000054 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000055static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000056 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000057static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000058 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000059static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
60 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000061
Evan Cheng2117d1f2007-06-09 01:03:43 +000062STATISTIC(NumSimple, "Number of simple if-conversions performed");
63STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
64STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000065STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000066STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
67STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
68STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
69STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000070STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000071STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000072
73namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000074 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000075 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000076 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000077 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000078 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
79 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000080 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000081 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000082 ICTriangle, // BB is entry of a triangle sub-CFG.
Evan Cheng4dd31a72007-06-11 22:26:22 +000083 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Chengf5e53a52007-05-16 02:00:57 +000084 };
85
86 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
87 /// if-conversion feasibility analysis. This includes results from
88 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000089 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000090 /// diamond shape), its size, whether it's predicable, and whether any
91 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000092 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +000093 /// IsDone - True if BB is not to be considered for ifcvt.
94 /// IsBeingAnalyzed - True if BB is currently being analyzed.
95 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
96 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
97 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
98 /// HasFallThrough - True if BB may fallthrough to the following BB.
99 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000100 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000101 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000102 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000103 /// ExtraCost - Extra cost for multi-cycle instructions.
104 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000105 /// BB - Corresponding MachineBasicBlock.
106 /// TrueBB / FalseBB- See AnalyzeBranch().
107 /// BrCond - Conditions for end of block conditional branches.
108 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000109 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000110 bool IsDone : 1;
111 bool IsBeingAnalyzed : 1;
112 bool IsAnalyzed : 1;
113 bool IsEnqueued : 1;
114 bool IsBrAnalyzable : 1;
115 bool HasFallThrough : 1;
116 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000117 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000118 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000119 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000120 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000121 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000122 MachineBasicBlock *BB;
123 MachineBasicBlock *TrueBB;
124 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000125 SmallVector<MachineOperand, 4> BrCond;
126 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000127 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000128 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
129 HasFallThrough(false), IsUnpredicable(false),
Evan Cheng23402fc2007-06-15 21:18:05 +0000130 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Craig Topperc0196b12014-04-14 00:51:57 +0000131 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
132 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000133 };
134
Bob Wilson59475732010-06-15 18:19:27 +0000135 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000136 /// BBI - Corresponding BBInfo.
137 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000138 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000139 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000140 /// NumDups - Number of instructions that would be duplicated due
141 /// to this if-conversion. (For diamonds, the number of
142 /// identical instructions at the beginnings of both
143 /// paths).
144 /// NumDups2 - For diamonds, the number of identical instructions
145 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000146 struct IfcvtToken {
147 BBInfo &BBI;
148 IfcvtKind Kind;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000149 bool NeedSubsumption;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000150 unsigned NumDups;
151 unsigned NumDups2;
152 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson2371f4f2009-05-13 23:25:24 +0000153 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000154 };
155
156 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
157 /// basic block number.
158 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000159 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000160
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000161 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000162 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000163 const TargetRegisterInfo *TRI;
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000164 const MachineBlockFrequencyInfo *MBFI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000165 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000166 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000167
Juergen Ributzka310034e2013-12-14 06:52:56 +0000168 LivePhysRegs Redefs;
169 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000170
Evan Chengc5adcca2012-06-08 21:53:50 +0000171 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000172 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000173 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000174 std::function<bool(const Function &)> PredicateFtor;
175
Evan Chengf5e53a52007-05-16 02:00:57 +0000176 public:
177 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000178 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
179 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(Ftor) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000180 initializeIfConverterPass(*PassRegistry::getPassRegistry());
181 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000182
Craig Topper4584cd52014-03-07 09:26:03 +0000183 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000184 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000185 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000186 MachineFunctionPass::getAnalysisUsage(AU);
187 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000188
Craig Topper4584cd52014-03-07 09:26:03 +0000189 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000190
191 private:
Evan Cheng312b7232007-06-04 06:47:22 +0000192 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersonf31f33e2010-10-01 22:45:50 +0000193 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000194 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000195 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000196 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000197 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000198 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
199 unsigned &Dups1, unsigned &Dups2) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000200 void ScanInstructions(BBInfo &BBI);
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000201 void AnalyzeBlock(MachineBasicBlock *MBB, std::vector<IfcvtToken*> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000202 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng7783f822007-06-08 09:36:04 +0000203 bool isTriangle = false, bool RevBranch = false);
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000204 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000205 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000206 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000207 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
208 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000209 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
210 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000211 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000212 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000213 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000214 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000215 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000216 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000217 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000218 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000219
Evan Chengdebf9c52010-11-03 00:45:17 +0000220 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
221 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000222 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000223 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000224 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000225 }
226
Evan Chengdebf9c52010-11-03 00:45:17 +0000227 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
228 unsigned TCycle, unsigned TExtra,
229 MachineBasicBlock &FBB,
230 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000231 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000232 return TCycle > 0 && FCycle > 0 &&
233 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000234 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000235 }
236
Evan Chengbe9859e2007-06-07 02:12:15 +0000237 // blockAlwaysFallThrough - Block ends without a terminator.
238 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000239 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000240 }
241
Evan Cheng3a51c852007-06-16 09:34:52 +0000242 // IfcvtTokenCmp - Used to sort if-conversion candidates.
243 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000244 int Incr1 = (C1->Kind == ICDiamond)
245 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
246 int Incr2 = (C2->Kind == ICDiamond)
247 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
248 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000249 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000250 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000251 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000252 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000253 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000254 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000255 // Favors diamond over triangle, etc.
256 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
257 return true;
258 else if (C1->Kind == C2->Kind)
259 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
260 }
261 }
262 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000263 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000264 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000265
Evan Chengf5e53a52007-05-16 02:00:57 +0000266 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000267}
Evan Chengf5e53a52007-05-16 02:00:57 +0000268
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000269char &llvm::IfConverterID = IfConverter::ID;
270
Owen Anderson8ac477f2010-10-12 19:48:12 +0000271INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000272INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000273INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000274
Evan Chengf5e53a52007-05-16 02:00:57 +0000275bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Akira Hatanaka4a616192015-06-08 18:50:43 +0000276 if (PredicateFtor && !PredicateFtor(*MF.getFunction()))
277 return false;
278
Eric Christopher3d4276f2015-01-27 07:31:29 +0000279 const TargetSubtargetInfo &ST = MF.getSubtarget();
280 TLI = ST.getTargetLowering();
281 TII = ST.getInstrInfo();
282 TRI = ST.getRegisterInfo();
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000283 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000284 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000285 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000286 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000287
Evan Chengf5e53a52007-05-16 02:00:57 +0000288 if (!TII) return false;
289
Evan Chengc5adcca2012-06-08 21:53:50 +0000290 PreRegAlloc = MRI->isSSA();
291
292 bool BFChange = false;
293 if (!PreRegAlloc) {
294 // Tail merge tend to expose more if-conversion opportunities.
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000295 BranchFolder BF(true, false, *MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000296 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000297 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000298 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000299
David Greene72e47cd2010-01-04 22:02:01 +0000300 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000301 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000302
303 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000304 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000305 return false;
306 }
David Greene72e47cd2010-01-04 22:02:01 +0000307 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000308
Evan Chengf5e53a52007-05-16 02:00:57 +0000309 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000310 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000311
Evan Cheng3a51c852007-06-16 09:34:52 +0000312 std::vector<IfcvtToken*> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000313 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000314 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
315 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
316 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000317 // Do an initial analysis for each basic block and find all the potential
318 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000319 bool Change = false;
320 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000321 while (!Tokens.empty()) {
322 IfcvtToken *Token = Tokens.back();
323 Tokens.pop_back();
324 BBInfo &BBI = Token->BBI;
325 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000326 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000327 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000328
329 delete Token;
Evan Cheng312b7232007-06-04 06:47:22 +0000330
Evan Cheng4dd31a72007-06-11 22:26:22 +0000331 // If the block has been evicted out of the queue or it has already been
332 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000333 if (BBI.IsDone)
334 BBI.IsEnqueued = false;
335 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000336 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000337
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000338 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000339
Evan Cheng312b7232007-06-04 06:47:22 +0000340 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000341 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000342 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000343 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000344 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000345 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000346 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000347 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
348 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000349 << "): BB#" << BBI.BB->getNumber() << " ("
350 << ((Kind == ICSimpleFalse)
351 ? BBI.FalseBB->getNumber()
352 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000353 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000354 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000355 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000356 if (isFalse) ++NumSimpleFalse;
357 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000358 }
Evan Cheng312b7232007-06-04 06:47:22 +0000359 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000360 }
Evan Chengd0e66912007-05-23 07:23:16 +0000361 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000362 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000363 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000364 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000365 bool isFalse = Kind == ICTriangleFalse;
366 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000367 if (DisableTriangle && !isFalse && !isRev) break;
368 if (DisableTriangleR && !isFalse && isRev) break;
369 if (DisableTriangleF && isFalse && !isRev) break;
370 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000371 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000372 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000373 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000374 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000375 DEBUG(dbgs() << " rev");
376 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000377 << BBI.TrueBB->getNumber() << ",F:"
378 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000379 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000380 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000381 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000382 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000383 if (isRev) ++NumTriangleFRev;
384 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000385 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000386 if (isRev) ++NumTriangleRev;
387 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000388 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000389 }
Evan Chengd0e66912007-05-23 07:23:16 +0000390 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000391 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000392 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000393 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000394 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000395 << BBI.TrueBB->getNumber() << ",F:"
396 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000397 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000398 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000399 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000400 break;
401 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000402 }
403
Evan Cheng312b7232007-06-04 06:47:22 +0000404 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000405
Evan Cheng92fb5452007-06-15 07:36:12 +0000406 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
407 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
408 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000409 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000410 }
Evan Chengd0e66912007-05-23 07:23:16 +0000411
Evan Chengd0e66912007-05-23 07:23:16 +0000412 if (!Change)
413 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000414 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000415 }
Evan Cheng478b8052007-05-18 01:55:58 +0000416
Evan Cheng3a51c852007-06-16 09:34:52 +0000417 // Delete tokens in case of early exit.
418 while (!Tokens.empty()) {
419 IfcvtToken *Token = Tokens.back();
420 Tokens.pop_back();
421 delete Token;
422 }
423
424 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000425 BBAnalysis.clear();
426
Evan Chengcf9e8a92010-06-18 22:17:13 +0000427 if (MadeChange && IfCvtBranchFold) {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000428 BranchFolder BF(false, false, *MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000429 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000430 getAnalysisIfAvailable<MachineModuleInfo>());
431 }
432
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000433 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000434 return MadeChange;
435}
436
Evan Cheng3a51c852007-06-16 09:34:52 +0000437/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
438/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000439static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000440 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000441 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
442 E = BB->succ_end(); SI != E; ++SI) {
443 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000444 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000445 return SuccBB;
446 }
Craig Topperc0196b12014-04-14 00:51:57 +0000447 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000448}
449
Evan Cheng3a51c852007-06-16 09:34:52 +0000450/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000451/// branch. Swap block's 'true' and 'false' successors.
Evan Cheng312b7232007-06-04 06:47:22 +0000452bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000453 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000454 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
455 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000456 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000457 std::swap(BBI.TrueBB, BBI.FalseBB);
458 return true;
459 }
460 return false;
461}
462
Evan Cheng2117d1f2007-06-09 01:03:43 +0000463/// getNextBlock - Returns the next block in the function blocks ordering. If
464/// it is the end, returns NULL.
465static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000466 MachineFunction::iterator I = BB->getIterator();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000467 MachineFunction::iterator E = BB->getParent()->end();
468 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000469 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000470 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000471}
472
Evan Cheng7783f822007-06-08 09:36:04 +0000473/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000474/// predecessor) forms a valid simple shape for ifcvt. It also returns the
475/// number of instructions that the ifcvt would need to duplicate if performed
476/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000477bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000478 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000479 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000480 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000481 return false;
482
Evan Chenga955c022007-06-19 21:45:13 +0000483 if (TrueBBI.IsBrAnalyzable)
484 return false;
485
Evan Cheng23402fc2007-06-15 21:18:05 +0000486 if (TrueBBI.BB->pred_size() > 1) {
487 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000488 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000489 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000490 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000491 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000492 }
493
Evan Chenga955c022007-06-19 21:45:13 +0000494 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000495}
496
Evan Cheng7783f822007-06-08 09:36:04 +0000497/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000498/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000499/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000500/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000501/// returns the number of instructions that the ifcvt would need to duplicate
502/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000503bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000504 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000505 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000506 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000507 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000508 return false;
509
Evan Cheng23402fc2007-06-15 21:18:05 +0000510 if (TrueBBI.BB->pred_size() > 1) {
511 if (TrueBBI.CannotBeCopied)
512 return false;
513
Evan Cheng92fb5452007-06-15 07:36:12 +0000514 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000515 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000516 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000517 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000518 --Size;
519 else {
520 MachineBasicBlock *FExit = FalseBranch
521 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
522 if (FExit)
523 // Require a conditional branch
524 ++Size;
525 }
526 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000527 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000528 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000529 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000530 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000531
Evan Cheng7783f822007-06-08 09:36:04 +0000532 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
533 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000534 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000535 if (++I == TrueBBI.BB->getParent()->end())
536 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000537 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000538 }
Evan Cheng7783f822007-06-08 09:36:04 +0000539 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000540}
541
Evan Cheng7783f822007-06-08 09:36:04 +0000542/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000543/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000544bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
545 unsigned &Dups1, unsigned &Dups2) const {
546 Dups1 = Dups2 = 0;
547 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
548 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000549 return false;
550
Evan Cheng2117d1f2007-06-09 01:03:43 +0000551 MachineBasicBlock *TT = TrueBBI.TrueBB;
552 MachineBasicBlock *FT = FalseBBI.TrueBB;
553
554 if (!TT && blockAlwaysFallThrough(TrueBBI))
555 TT = getNextBlock(TrueBBI.BB);
556 if (!FT && blockAlwaysFallThrough(FalseBBI))
557 FT = getNextBlock(FalseBBI.BB);
558 if (TT != FT)
559 return false;
Craig Topperc0196b12014-04-14 00:51:57 +0000560 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng2117d1f2007-06-09 01:03:43 +0000561 return false;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000562 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
563 return false;
564
565 // FIXME: Allow true block to have an early exit?
566 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
567 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000568 return false;
569
Bob Wilsone1961fe2010-10-26 00:02:24 +0000570 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach6201b992010-06-07 21:28:55 +0000571 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
572 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilsone1961fe2010-10-26 00:02:24 +0000573 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
574 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
575 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000576 // Skip dbg_value instructions. These do not count.
Bob Wilsone1961fe2010-10-26 00:02:24 +0000577 if (TIB->isDebugValue()) {
578 while (TIB != TIE && TIB->isDebugValue())
579 ++TIB;
580 if (TIB == TIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000581 break;
582 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000583 if (FIB->isDebugValue()) {
584 while (FIB != FIE && FIB->isDebugValue())
585 ++FIB;
586 if (FIB == FIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000587 break;
588 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000589 if (!TIB->isIdenticalTo(FIB))
590 break;
591 ++Dups1;
592 ++TIB;
593 ++FIB;
594 }
595
596 // Now, in preparation for counting duplicate instructions at the ends of the
597 // blocks, move the end iterators up past any branch instructions.
598 while (TIE != TIB) {
599 --TIE;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000600 if (!TIE->isBranch())
Bob Wilsone1961fe2010-10-26 00:02:24 +0000601 break;
602 }
603 while (FIE != FIB) {
604 --FIE;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000605 if (!FIE->isBranch())
Bob Wilsone1961fe2010-10-26 00:02:24 +0000606 break;
607 }
608
609 // If Dups1 includes all of a block, then don't count duplicate
610 // instructions at the end of the blocks.
611 if (TIB == TIE || FIB == FIE)
612 return true;
613
614 // Count duplicate instructions at the ends of the blocks.
615 while (TIE != TIB && FIE != FIB) {
616 // Skip dbg_value instructions. These do not count.
617 if (TIE->isDebugValue()) {
618 while (TIE != TIB && TIE->isDebugValue())
619 --TIE;
620 if (TIE == TIB)
621 break;
622 }
623 if (FIE->isDebugValue()) {
624 while (FIE != FIB && FIE->isDebugValue())
625 --FIE;
626 if (FIE == FIB)
627 break;
628 }
629 if (!TIE->isIdenticalTo(FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000630 break;
631 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000632 --TIE;
633 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000634 }
635
636 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000637}
638
Evan Cheng4dd31a72007-06-11 22:26:22 +0000639/// ScanInstructions - Scan all the instructions in the block to determine if
640/// the block is predicable. In most cases, that means all the instructions
Chris Lattnera98c6792008-01-07 01:56:04 +0000641/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng4dd31a72007-06-11 22:26:22 +0000642/// instruction which can clobber a predicate (e.g. condition code register).
643/// If so, the block is not predicable unless it's the last instruction.
644void IfConverter::ScanInstructions(BBInfo &BBI) {
645 if (BBI.IsDone)
646 return;
647
Evan Chengc5adcca2012-06-08 21:53:50 +0000648 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000649 // First analyze the end of BB branches.
Craig Topperc0196b12014-04-14 00:51:57 +0000650 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000651 BBI.BrCond.clear();
652 BBI.IsBrAnalyzable =
653 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000654 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000655
656 if (BBI.BrCond.size()) {
657 // No false branch. This BB must end with a conditional branch and a
658 // fallthrough.
659 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000660 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000661 if (!BBI.FalseBB) {
662 // Malformed bcc? True and false blocks are the same?
663 BBI.IsUnpredicable = true;
664 return;
665 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000666 }
667
668 // Then scan all the instructions.
669 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000670 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000671 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000672 BBI.ClobbersPred = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000673 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
674 I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000675 if (I->isDebugValue())
676 continue;
677
Evan Cheng7f8e5632011-12-07 07:15:52 +0000678 if (I->isNotDuplicable())
Evan Cheng23402fc2007-06-15 21:18:05 +0000679 BBI.CannotBeCopied = true;
680
Evan Cheng4dd31a72007-06-11 22:26:22 +0000681 bool isPredicated = TII->isPredicated(I);
Evan Cheng7f8e5632011-12-07 07:15:52 +0000682 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000683
Joey Goulya5153cb2013-09-09 14:21:49 +0000684 // A conditional branch is not predicable, but it may be eliminated.
685 if (isCondBr)
686 continue;
687
688 if (!isPredicated) {
689 BBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000690 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
691 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000692 if (NumCycles > 1)
693 BBI.ExtraCost += NumCycles-1;
694 BBI.ExtraCost2 += ExtraPredCost;
695 } else if (!AlreadyPredicated) {
696 // FIXME: This instruction is already predicated before the
697 // if-conversion pass. It's probably something like a conditional move.
698 // Mark this block unpredicable for now.
699 BBI.IsUnpredicable = true;
700 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000701 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000702
703 if (BBI.ClobbersPred && !isPredicated) {
704 // Predicate modification instruction should end the block (except for
705 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000706 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000707 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000708 BBI.IsUnpredicable = true;
709 return;
710 }
711
Evan Chengfbc73092007-07-10 17:50:43 +0000712 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
713 // still potentially predicable.
714 std::vector<MachineOperand> PredDefs;
715 if (TII->DefinesPredicate(I, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000716 BBI.ClobbersPred = true;
717
Evan Cheng1f4062f2009-11-21 06:20:26 +0000718 if (!TII->isPredicable(I)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000719 BBI.IsUnpredicable = true;
720 return;
721 }
722 }
723}
724
725/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
726/// predicated by the specified predicate.
727bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000728 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng4dd31a72007-06-11 22:26:22 +0000729 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000730 // If the block is dead or unpredicable, then it cannot be predicated.
731 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000732 return false;
733
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000734 // If it is already predicated but we couldn't analyze its terminator, the
735 // latter might fallthrough, but we can't determine where to.
736 // Conservatively avoid if-converting again.
737 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
738 return false;
739
Quentin Colombetbdab2272013-07-24 20:20:37 +0000740 // If it is already predicated, check if the new predicate subsumes
741 // its predicate.
742 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000743 return false;
744
745 if (BBI.BrCond.size()) {
746 if (!isTriangle)
747 return false;
748
Bob Wilson2371f4f2009-05-13 23:25:24 +0000749 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000750 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
751 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000752 if (RevBranch) {
753 if (TII->ReverseBranchCondition(Cond))
754 return false;
755 }
756 if (TII->ReverseBranchCondition(RevPred) ||
757 !TII->SubsumesPredicate(Cond, RevPred))
758 return false;
759 }
760
761 return true;
762}
763
Evan Cheng7783f822007-06-08 09:36:04 +0000764/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +0000765/// the specified block. Record its successors and whether it looks like an
766/// if-conversion candidate.
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000767void IfConverter::AnalyzeBlock(MachineBasicBlock *MBB,
768 std::vector<IfcvtToken*> &Tokens) {
769 struct BBState {
770 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
771 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000772
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000773 /// This flag is true if MBB's successors have been analyzed.
774 bool SuccsAnalyzed;
775 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000776
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000777 // Push MBB to the stack.
778 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000779
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000780 while (!BBStack.empty()) {
781 BBState &State = BBStack.back();
782 MachineBasicBlock *BB = State.MBB;
783 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000784
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000785 if (!State.SuccsAnalyzed) {
786 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
787 BBStack.pop_back();
788 continue;
789 }
Evan Cheng9030b982007-06-06 10:16:17 +0000790
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000791 BBI.BB = BB;
792 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000793
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000794 ScanInstructions(BBI);
Evan Chengb9bff582009-06-15 21:24:34 +0000795
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000796 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
797 // not considered for ifcvt anymore.
798 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
799 BBI.IsBeingAnalyzed = false;
800 BBI.IsAnalyzed = true;
801 BBStack.pop_back();
802 continue;
803 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000804
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000805 // Do not ifcvt if either path is a back edge to the entry block.
806 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
807 BBI.IsBeingAnalyzed = false;
808 BBI.IsAnalyzed = true;
809 BBStack.pop_back();
810 continue;
811 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000812
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000813 // Do not ifcvt if true and false fallthrough blocks are the same.
814 if (!BBI.FalseBB) {
815 BBI.IsBeingAnalyzed = false;
816 BBI.IsAnalyzed = true;
817 BBStack.pop_back();
818 continue;
819 }
Evan Cheng7783f822007-06-08 09:36:04 +0000820
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000821 // Push the False and True blocks to the stack.
822 State.SuccsAnalyzed = true;
823 BBStack.push_back(BBI.FalseBB);
824 BBStack.push_back(BBI.TrueBB);
825 continue;
826 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000827
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000828 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
829 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +0000830
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000831 if (TrueBBI.IsDone && FalseBBI.IsDone) {
832 BBI.IsBeingAnalyzed = false;
833 BBI.IsAnalyzed = true;
834 BBStack.pop_back();
835 continue;
836 }
837
838 SmallVector<MachineOperand, 4>
839 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
840 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
841
842 unsigned Dups = 0;
843 unsigned Dups2 = 0;
844 bool TNeedSub = !TrueBBI.Predicate.empty();
845 bool FNeedSub = !FalseBBI.Predicate.empty();
846 bool Enqueued = false;
847
848 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
849
850 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
851 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
852 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
853 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000854 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000855 Prediction) &&
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000856 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
857 FeasibilityAnalysis(FalseBBI, RevCond)) {
858 // Diamond:
859 // EBB
860 // / \_
861 // | |
862 // TBB FBB
863 // \ /
864 // TailBB
865 // Note TailBB can be empty.
866 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
867 Dups2));
Evan Cheng3a51c852007-06-16 09:34:52 +0000868 Enqueued = true;
869 }
870
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000871 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
872 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
873 TrueBBI.ExtraCost2, Prediction) &&
874 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
875 // Triangle:
876 // EBB
877 // | \_
878 // | |
879 // | TBB
880 // | /
881 // FBB
882 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
883 Enqueued = true;
884 }
885
886 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
887 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
888 TrueBBI.ExtraCost2, Prediction) &&
889 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
890 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
891 Enqueued = true;
892 }
893
894 if (ValidSimple(TrueBBI, Dups, Prediction) &&
895 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
896 TrueBBI.ExtraCost2, Prediction) &&
897 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
898 // Simple (split, no rejoin):
899 // EBB
900 // | \_
901 // | |
902 // | TBB---> exit
903 // |
904 // FBB
905 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
906 Enqueued = true;
907 }
908
909 if (CanRevCond) {
910 // Try the other path...
911 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
912 Prediction.getCompl()) &&
913 MeetIfcvtSizeLimit(*FalseBBI.BB,
914 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
915 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
916 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
917 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
918 Enqueued = true;
919 }
920
921 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
922 Prediction.getCompl()) &&
923 MeetIfcvtSizeLimit(*FalseBBI.BB,
924 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000925 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000926 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000927 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
928 Enqueued = true;
929 }
930
931 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
932 MeetIfcvtSizeLimit(*FalseBBI.BB,
933 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
934 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
935 FeasibilityAnalysis(FalseBBI, RevCond)) {
936 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
937 Enqueued = true;
938 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000939 }
940
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000941 BBI.IsEnqueued = Enqueued;
942 BBI.IsBeingAnalyzed = false;
943 BBI.IsAnalyzed = true;
944 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +0000945 }
Evan Cheng2e82cef2007-05-18 18:14:37 +0000946}
947
Evan Cheng905a8f42007-05-30 19:49:19 +0000948/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000949/// candidates.
950void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Cheng3a51c852007-06-16 09:34:52 +0000951 std::vector<IfcvtToken*> &Tokens) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000952 for (auto &BB : MF)
953 AnalyzeBlock(&BB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +0000954
Evan Cheng20e05992007-06-01 00:12:12 +0000955 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +0000956 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +0000957}
958
Evan Cheng288f1542007-06-08 22:01:07 +0000959/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
960/// that all the intervening blocks are empty (given BB can fall through to its
961/// next block).
962static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000963 MachineFunction::iterator PI = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000964 MachineFunction::iterator I = std::next(PI);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000965 MachineFunction::iterator TI = ToBB->getIterator();
Evan Cheng2c1acd62007-06-05 07:05:25 +0000966 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +0000967 while (I != TI) {
968 // Check isSuccessor to avoid case where the next block is empty, but
969 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000970 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +0000971 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +0000972 PI = I++;
973 }
Evan Cheng312b7232007-06-04 06:47:22 +0000974 return true;
Evan Chenge26c0912007-05-21 22:22:58 +0000975}
976
Evan Cheng51eb2c32007-06-18 08:37:25 +0000977/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
978/// to determine if it can be if-converted. If predecessor is already enqueued,
979/// dequeue it!
980void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +0000981 for (const auto &Predecessor : BB->predecessors()) {
982 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +0000983 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +0000984 continue;
Evan Chengadd97762007-06-14 23:34:09 +0000985 PBBI.IsAnalyzed = false;
986 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +0000987 }
988}
989
Evan Chengc2237ce2007-05-29 22:31:16 +0000990/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
991///
992static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
993 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000994 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +0000995 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +0000996 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +0000997}
998
Evan Cheng288f1542007-06-08 22:01:07 +0000999/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1000/// successors.
1001void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001002 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001003 SmallVector<MachineOperand, 4> Cond;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001004 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
1005 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001006}
1007
Matthias Braund616ccc2013-10-11 19:04:37 +00001008/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1009/// values defined in MI which are not live/used by MI.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001010static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) {
Pete Cooper7605e372015-05-05 20:14:22 +00001011 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
1012 Redefs.stepForward(*MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001013
Pete Cooper7605e372015-05-05 20:14:22 +00001014 // Now add the implicit uses for each of the clobbered values.
1015 for (auto Reg : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001016 // FIXME: Const cast here is nasty, but better than making StepForward
1017 // take a mutable instruction instead of const.
Pete Cooper27483912015-05-06 22:51:04 +00001018 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1019 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001020 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001021 if (Op.isRegMask()) {
1022 // First handle regmasks. They clobber any entries in the mask which
1023 // means that we need a def for those registers.
Pete Cooper7605e372015-05-05 20:14:22 +00001024 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Pete Cooperce9ad752015-05-05 22:09:41 +00001025
1026 // We also need to add an implicit def of this register for the later
1027 // use to read from.
1028 // For the register allocator to have allocated a register clobbered
1029 // by the call which is used later, it must be the case that
1030 // the call doesn't return.
1031 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1032 continue;
1033 }
1034 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001035 if (Op.isDead()) {
1036 // If we found a dead def, but it needs to be live, then remove the dead
1037 // flag.
1038 if (Redefs.contains(Op.getReg()))
1039 Op.setIsDead(false);
1040 }
Pete Cooperce9ad752015-05-05 22:09:41 +00001041 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Matthias Braund616ccc2013-10-11 19:04:37 +00001042 }
1043}
1044
1045/**
1046 * Remove kill flags from operands with a registers in the @p DontKill set.
1047 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001048static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001049 for (MIBundleOperands O(&MI); O.isValid(); ++O) {
1050 if (!O->isReg() || !O->isKill())
1051 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001052 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001053 O->setIsKill(false);
1054 }
1055}
1056
1057/**
1058 * Walks a range of machine instructions and removes kill flags for registers
1059 * in the @p DontKill set.
1060 */
1061static void RemoveKills(MachineBasicBlock::iterator I,
1062 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001063 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001064 const MCRegisterInfo &MCRI) {
1065 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001066 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001067}
1068
Evan Cheng312b7232007-06-04 06:47:22 +00001069/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001070///
Evan Cheng3a51c852007-06-16 09:34:52 +00001071bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001072 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1073 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1074 BBInfo *CvtBBI = &TrueBBI;
1075 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001076
Owen Anderson4f6bf042008-08-14 22:49:33 +00001077 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001078 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001079 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001080
Evan Cheng51eb2c32007-06-18 08:37:25 +00001081 if (CvtBBI->IsDone ||
1082 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001083 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001084 BBI.IsAnalyzed = false;
1085 CvtBBI->IsAnalyzed = false;
1086 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001087 }
Evan Chengd0e66912007-05-23 07:23:16 +00001088
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001089 if (CvtBBI->BB->hasAddressTaken())
1090 // Conservatively abort if-conversion if BB's address is taken.
1091 return false;
1092
Evan Cheng3a51c852007-06-16 09:34:52 +00001093 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001094 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001095 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001096
Bob Wilson45814342010-06-19 05:33:57 +00001097 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001098 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001099 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001100 Redefs.addLiveIns(CvtBBI->BB);
1101 Redefs.addLiveIns(NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001102
1103 // Compute a set of registers which must not be killed by instructions in
1104 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001105 DontKill.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001106 DontKill.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001107
Evan Cheng92fb5452007-06-15 07:36:12 +00001108 if (CvtBBI->BB->pred_size() > 1) {
1109 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001110 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001111 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001112 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001113
1114 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1115 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001116 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001117 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001118 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001119 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001120
Evan Cheng92fb5452007-06-15 07:36:12 +00001121 // Merge converted block into entry block.
1122 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1123 MergeBlocks(BBI, *CvtBBI);
1124 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001125
Evan Chenge4ec9182007-06-06 02:08:52 +00001126 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001127 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001128 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001129 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001130 // Now ifcvt'd block will look like this:
1131 // BB:
1132 // ...
1133 // t, f = cmp
1134 // if t op
1135 // b BBf
1136 //
1137 // We cannot further ifcvt this block because the unconditional branch
1138 // will have to be predicated on the new condition, that will not be
1139 // available if cmp executes.
1140 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001141 }
Evan Chenge26c0912007-05-21 22:22:58 +00001142
Evan Cheng288f1542007-06-08 22:01:07 +00001143 RemoveExtraEdges(BBI);
1144
Evan Chengd0e66912007-05-23 07:23:16 +00001145 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001146 if (!IterIfcvt)
1147 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001148 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001149 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001150
1151 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001152 return true;
1153}
1154
Evan Chengaf716102007-05-16 21:54:37 +00001155/// IfConvertTriangle - If convert a triangle sub-CFG.
1156///
Evan Cheng3a51c852007-06-16 09:34:52 +00001157bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001158 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001159 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1160 BBInfo *CvtBBI = &TrueBBI;
1161 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001162 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001163
Owen Anderson4f6bf042008-08-14 22:49:33 +00001164 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001165 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001166 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001167
Evan Cheng51eb2c32007-06-18 08:37:25 +00001168 if (CvtBBI->IsDone ||
1169 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001170 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001171 BBI.IsAnalyzed = false;
1172 CvtBBI->IsAnalyzed = false;
1173 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001174 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001175
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001176 if (CvtBBI->BB->hasAddressTaken())
1177 // Conservatively abort if-conversion if BB's address is taken.
1178 return false;
1179
Evan Cheng3a51c852007-06-16 09:34:52 +00001180 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001181 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001182 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001183
Evan Cheng3a51c852007-06-16 09:34:52 +00001184 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001185 if (ReverseBranchCondition(*CvtBBI)) {
1186 // BB has been changed, modify its predecessors (except for this
1187 // one) so they don't get ifcvt'ed based on bad intel.
1188 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1189 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1190 MachineBasicBlock *PBB = *PI;
1191 if (PBB == BBI.BB)
1192 continue;
1193 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1194 if (PBBI.IsEnqueued) {
1195 PBBI.IsAnalyzed = false;
1196 PBBI.IsEnqueued = false;
1197 }
Evan Chengadd97762007-06-14 23:34:09 +00001198 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001199 }
1200 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001201
Bob Wilson45814342010-06-19 05:33:57 +00001202 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001203 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001204 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001205 Redefs.addLiveIns(CvtBBI->BB);
1206 Redefs.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001207
Andrew Trick276dd452013-10-14 20:45:17 +00001208 DontKill.clear();
1209
Craig Topperc0196b12014-04-14 00:51:57 +00001210 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001211 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001212
Manman Renb6819182014-01-29 23:18:47 +00001213 if (HasEarlyExit) {
Cong Houd97c1002015-12-01 05:29:22 +00001214 // Get probabilities before modifying CvtBBI->BB and BBI.BB.
1215 CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB);
1216 CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB);
1217 BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB);
1218 BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001219 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001220
Bob Wilson1e5da552010-06-29 00:55:23 +00001221 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001222 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001223 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001224 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001225 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001226
1227 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1228 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001229 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001230 } else {
1231 // Predicate the 'true' block after removing its branch.
1232 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001233 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001234
Evan Cheng0598b2d2007-06-18 22:44:57 +00001235 // Now merge the entry of the triangle with the true block.
1236 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001237 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001238 }
1239
Evan Cheng312b7232007-06-04 06:47:22 +00001240 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001241 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001242 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1243 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001244 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001245 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001246
Cong Houd97c1002015-12-01 05:29:22 +00001247 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1248 // NewNext = New_Prob(BBI.BB, NextBBI->BB) =
1249 // Prob(BBI.BB, NextBBI->BB) +
1250 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB)
1251 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1252 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB)
1253 auto NewTrueBB = getNextBlock(BBI.BB);
1254 auto NewNext = BBNext + BBCvt * CvtNext;
1255 auto NewTrueBBIter =
1256 std::find(BBI.BB->succ_begin(), BBI.BB->succ_end(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001257 if (NewTrueBBIter != BBI.BB->succ_end())
1258 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001259
1260 auto NewFalse = BBCvt * CvtFalse;
1261 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1262 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001263 }
Evan Cheng7783f822007-06-08 09:36:04 +00001264
1265 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001266 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001267 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001268 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001269 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001270 if (!isFallThrough) {
1271 // Only merge them if the true block does not fallthrough to the false
1272 // block. By not merging them, we make it possible to iteratively
1273 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001274 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001275 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1276 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001277 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001278 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001279 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001280 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1281 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001282 }
Evan Cheng7783f822007-06-08 09:36:04 +00001283 // Mixed predicated and unpredicated code. This cannot be iteratively
1284 // predicated.
1285 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001286 }
Evan Chenge26c0912007-05-21 22:22:58 +00001287
Evan Cheng288f1542007-06-08 22:01:07 +00001288 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001289
Evan Chengd0e66912007-05-23 07:23:16 +00001290 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001291 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001292 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001293 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001294 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001295 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001296 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001297
1298 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001299 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001300}
1301
Evan Chengaf716102007-05-16 21:54:37 +00001302/// IfConvertDiamond - If convert a diamond sub-CFG.
1303///
Evan Cheng51eb2c32007-06-18 08:37:25 +00001304bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1305 unsigned NumDups1, unsigned NumDups2) {
Evan Cheng312b7232007-06-04 06:47:22 +00001306 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2e82cef2007-05-18 18:14:37 +00001307 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng3a51c852007-06-16 09:34:52 +00001308 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson2371f4f2009-05-13 23:25:24 +00001309 // True block must fall through or end with an unanalyzable terminator.
Evan Cheng3a51c852007-06-16 09:34:52 +00001310 if (!TailBB) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001311 if (blockAlwaysFallThrough(TrueBBI))
1312 TailBB = FalseBBI.TrueBB;
1313 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Chengf5e53a52007-05-16 02:00:57 +00001314 }
Evan Chenge26c0912007-05-21 22:22:58 +00001315
Evan Cheng51eb2c32007-06-18 08:37:25 +00001316 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1317 TrueBBI.BB->pred_size() > 1 ||
1318 FalseBBI.BB->pred_size() > 1) {
1319 // Something has changed. It's no longer safe to predicate these blocks.
1320 BBI.IsAnalyzed = false;
1321 TrueBBI.IsAnalyzed = false;
1322 FalseBBI.IsAnalyzed = false;
1323 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001324 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001325
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001326 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1327 // Conservatively abort if-conversion if either BB has its address taken.
1328 return false;
1329
Bob Wilson1e5da552010-06-29 00:55:23 +00001330 // Put the predicated instructions from the 'true' block before the
1331 // instructions from the 'false' block, unless the true block would clobber
1332 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001333 BBInfo *BBI1 = &TrueBBI;
1334 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001335 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001336 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001337 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001338 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1339 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001340
Evan Cheng3a51c852007-06-16 09:34:52 +00001341 // Figure out the more profitable ordering.
1342 bool DoSwap = false;
1343 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1344 DoSwap = true;
1345 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001346 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001347 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001348 }
1349 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001350 std::swap(BBI1, BBI2);
1351 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001352 }
Evan Cheng79484222007-06-05 23:46:14 +00001353
Evan Cheng51eb2c32007-06-18 08:37:25 +00001354 // Remove the conditional branch from entry to the blocks.
1355 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1356
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001357 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001358 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001359 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001360 Redefs.addLiveIns(BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001361
Evan Cheng51eb2c32007-06-18 08:37:25 +00001362 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001363 // Skip dbg_value instructions
Benjamin Kramer6b568962015-06-23 14:47:29 +00001364 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1365 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001366 BBI1->NonPredSize -= NumDups1;
1367 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001368
1369 // Skip past the dups on each side separately since there may be
1370 // differing dbg_value entries.
1371 for (unsigned i = 0; i < NumDups1; ++DI1) {
1372 if (!DI1->isDebugValue())
1373 ++i;
1374 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001375 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001376 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001377 if (!DI2->isDebugValue())
1378 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001379 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001380
Matthias Braund616ccc2013-10-11 19:04:37 +00001381 // Compute a set of registers which must not be killed by instructions in BB1:
1382 // This is everything used+live in BB2 after the duplicated instructions. We
1383 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001384 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001385 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1386 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001387 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001388 }
1389
1390 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1391 ++I) {
Pete Cooper7605e372015-05-05 20:14:22 +00001392 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1393 Redefs.stepForward(*I, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001394 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001395 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1396 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1397
Evan Cheng4266a792011-12-19 22:01:30 +00001398 // Remove branch from 'true' block and remove duplicated instructions.
Evan Cheng79484222007-06-05 23:46:14 +00001399 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001400 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001401 for (unsigned i = 0; i != NumDups2; ) {
1402 // NumDups2 only counted non-dbg_value instructions, so this won't
1403 // run off the head of the list.
1404 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001405 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001406 // skip dbg_value instructions
1407 if (!DI1->isDebugValue())
1408 ++i;
1409 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001410 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001411
Matthias Braund616ccc2013-10-11 19:04:37 +00001412 // Kill flags in the true block for registers living into the false block
1413 // must be removed.
1414 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1415
Evan Cheng4266a792011-12-19 22:01:30 +00001416 // Remove 'false' block branch and find the last instruction to predicate.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001417 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1418 DI2 = BBI2->BB->end();
1419 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001420 // NumDups2 only counted non-dbg_value instructions, so this won't
1421 // run off the head of the list.
1422 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001423 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001424 // skip dbg_value instructions
1425 if (!DI2->isDebugValue())
1426 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001427 }
Evan Cheng4266a792011-12-19 22:01:30 +00001428
1429 // Remember which registers would later be defined by the false block.
1430 // This allows us not to predicate instructions in the true block that would
1431 // later be re-defined. That is, rather than
1432 // subeq r0, r1, #1
1433 // addne r0, r1, #1
1434 // generate:
1435 // sub r0, r1, #1
1436 // addne r0, r1, #1
1437 SmallSet<unsigned, 4> RedefsByFalse;
1438 SmallSet<unsigned, 4> ExtUses;
1439 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1440 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1441 if (FI->isDebugValue())
1442 continue;
1443 SmallVector<unsigned, 4> Defs;
1444 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1445 const MachineOperand &MO = FI->getOperand(i);
1446 if (!MO.isReg())
1447 continue;
1448 unsigned Reg = MO.getReg();
1449 if (!Reg)
1450 continue;
1451 if (MO.isDef()) {
1452 Defs.push_back(Reg);
1453 } else if (!RedefsByFalse.count(Reg)) {
1454 // These are defined before ctrl flow reach the 'false' instructions.
1455 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001456 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1457 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001458 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001459 }
1460 }
1461
1462 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1463 unsigned Reg = Defs[i];
1464 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001465 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1466 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001467 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001468 }
1469 }
1470 }
1471 }
1472
1473 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001474 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001475
1476 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001477 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001478
Evan Cheng0598b2d2007-06-18 22:44:57 +00001479 // Merge the true block into the entry of the diamond.
Craig Topperc0196b12014-04-14 00:51:57 +00001480 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1481 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001482
Bob Wilson2371f4f2009-05-13 23:25:24 +00001483 // If the if-converted block falls through or unconditionally branches into
1484 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001485 // fold the tail block in as well. Otherwise, unless it falls through to the
1486 // tail, add a unconditional branch to it.
1487 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001488 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001489 bool CanMergeTail = !TailBBI.HasFallThrough &&
1490 !TailBBI.BB->hasAddressTaken();
Bob Wilson1e5da552010-06-29 00:55:23 +00001491 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1492 // check if there are any other predecessors besides those.
1493 unsigned NumPreds = TailBB->pred_size();
1494 if (NumPreds > 1)
1495 CanMergeTail = false;
1496 else if (NumPreds == 1 && CanMergeTail) {
1497 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1498 if (*PI != BBI1->BB && *PI != BBI2->BB)
1499 CanMergeTail = false;
1500 }
1501 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001502 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001503 TailBBI.IsDone = true;
1504 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001505 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Evan Cheng0598b2d2007-06-18 22:44:57 +00001506 InsertUncondBranch(BBI.BB, TailBB, TII);
1507 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001508 }
Evan Chenge26c0912007-05-21 22:22:58 +00001509 }
1510
Bob Wilson1e5da552010-06-29 00:55:23 +00001511 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1512 // which can happen here if TailBB is unanalyzable and is merged, so
1513 // explicitly remove BBI1 and BBI2 as successors.
1514 BBI.BB->removeSuccessor(BBI1->BB);
Cong Houc1069892015-12-13 09:26:17 +00001515 BBI.BB->removeSuccessor(BBI2->BB, true);
Evan Cheng288f1542007-06-08 22:01:07 +00001516 RemoveExtraEdges(BBI);
1517
Evan Cheng79484222007-06-05 23:46:14 +00001518 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001519 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001520 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001521
1522 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001523 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001524}
1525
Evan Cheng4266a792011-12-19 22:01:30 +00001526static bool MaySpeculate(const MachineInstr *MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001527 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001528 bool SawStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001529 if (!MI->isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001530 return false;
1531
1532 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1533 const MachineOperand &MO = MI->getOperand(i);
1534 if (!MO.isReg())
1535 continue;
1536 unsigned Reg = MO.getReg();
1537 if (!Reg)
1538 continue;
1539 if (MO.isDef() && !LaterRedefs.count(Reg))
1540 return false;
1541 }
1542
1543 return true;
1544}
1545
Evan Cheng51eb2c32007-06-18 08:37:25 +00001546/// PredicateBlock - Predicate instructions from the start of the block to the
1547/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001548void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001549 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001550 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001551 SmallSet<unsigned, 4> *LaterRedefs) {
1552 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001553 bool MaySpec = LaterRedefs != nullptr;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001554 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +00001555 if (I->isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001556 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001557 // It may be possible not to predicate an instruction if it's the 'true'
1558 // side of a diamond and the 'false' side may re-define the instruction's
1559 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001560 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001561 AnyUnpred = true;
1562 continue;
1563 }
1564 // If any instruction is predicated, then every instruction after it must
1565 // be predicated.
1566 MaySpec = false;
Evan Cheng312b7232007-06-04 06:47:22 +00001567 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001568#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001569 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001570#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001571 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001572 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001573
Bob Wilson45814342010-06-19 05:33:57 +00001574 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001575 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001576 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001577 }
Evan Chengd0e66912007-05-23 07:23:16 +00001578
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001579 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001580
Evan Cheng92fb5452007-06-15 07:36:12 +00001581 BBI.IsAnalyzed = false;
1582 BBI.NonPredSize = 0;
1583
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001584 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001585 if (AnyUnpred)
1586 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001587}
1588
Evan Cheng92fb5452007-06-15 07:36:12 +00001589/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1590/// the destination block. Skip end of block branches if IgnoreBr is true.
1591void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001592 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001593 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001594 MachineFunction &MF = *ToBBI.BB->getParent();
1595
Evan Cheng92fb5452007-06-15 07:36:12 +00001596 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1597 E = FromBBI.BB->end(); I != E; ++I) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001598 // Do not copy the end of the block branches.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001599 if (IgnoreBr && I->isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001600 break;
1601
Dan Gohman3b460302008-07-07 23:14:23 +00001602 MachineInstr *MI = MF.CloneMachineInstr(I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001603 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001604 ToBBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +00001605 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
1606 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001607 if (NumCycles > 1)
1608 ToBBI.ExtraCost += NumCycles-1;
1609 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001610
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001611 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001612 if (!TII->PredicateInstruction(MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001613#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001614 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001615#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001616 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001617 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001618 }
1619
Bob Wilson45814342010-06-19 05:33:57 +00001620 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001621 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001622 UpdatePredRedefs(MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001623
1624 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001625 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001626 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001627 }
1628
Bob Wilson1e5da552010-06-29 00:55:23 +00001629 if (!IgnoreBr) {
1630 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1631 FromBBI.BB->succ_end());
1632 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001633 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001634
Bob Wilson1e5da552010-06-29 00:55:23 +00001635 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1636 MachineBasicBlock *Succ = Succs[i];
1637 // Fallthrough edge can't be transferred.
1638 if (Succ == FallThrough)
1639 continue;
1640 ToBBI.BB->addSuccessor(Succ);
1641 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001642 }
1643
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001644 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1645 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001646
1647 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1648 ToBBI.IsAnalyzed = false;
1649
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001650 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001651}
1652
Evan Cheng0f745da2007-05-18 00:20:58 +00001653/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00001654/// This will leave FromBB as an empty block, so remove all of its
1655/// successor edges except for the fall-through edge. If AddEdges is true,
1656/// i.e., when FromBBI's branch is being moved, add those successor edges to
1657/// ToBBI.
1658void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001659 assert(!FromBBI.BB->hasAddressTaken() &&
1660 "Removing a BB whose address is taken!");
1661
Evan Cheng0f745da2007-05-18 00:20:58 +00001662 ToBBI.BB->splice(ToBBI.BB->end(),
1663 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00001664
Cong Houb9e8d482015-12-17 01:29:08 +00001665 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1666 // unknown probabilities into known ones.
1667 // FIXME: This usage is too tricky and in the future we would like to
1668 // eliminate all unknown probabilities in MBB.
1669 ToBBI.BB->normalizeSuccProbs();
1670
Cong Houd40105d2015-09-18 20:22:41 +00001671 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
1672 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00001673 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001674 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001675 // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001676 // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00001677 auto To2FromProb = BranchProbability::getZero();
Cong Houfa1917c2015-12-01 00:02:51 +00001678 if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
Cong Houd97c1002015-12-01 05:29:22 +00001679 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB);
1680 // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the
1681 // edge probability being merged to other edges when this edge is removed
1682 // later.
1683 ToBBI.BB->setSuccProbability(
1684 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB),
1685 BranchProbability::getZero());
1686 }
1687
Cong Houd40105d2015-09-18 20:22:41 +00001688 for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
1689 MachineBasicBlock *Succ = FromSuccs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00001690 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001691 if (Succ == FallThrough)
1692 continue;
Cong Houd40105d2015-09-18 20:22:41 +00001693
Cong Houd97c1002015-12-01 05:29:22 +00001694 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00001695 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001696 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
1697 // which is a portion of the edge probability from FromBBI.BB to Succ. The
1698 // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if
1699 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
1700 NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001701
Cong Houd97c1002015-12-01 05:29:22 +00001702 // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
Cong Houd40105d2015-09-18 20:22:41 +00001703 // only happens when if-converting a diamond CFG and FromBBI.BB is the
1704 // tail BB. In this case FromBBI.BB post-dominates ToBBI.BB and hence we
Cong Houd97c1002015-12-01 05:29:22 +00001705 // could just use the probabilities on FromBBI.BB's out-edges when adding
1706 // new successors.
1707 if (!To2FromProb.isZero())
1708 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00001709 }
1710
Evan Chengbe9859e2007-06-07 02:12:15 +00001711 FromBBI.BB->removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001712
1713 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001714 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00001715 // probability of this edge by adding NewProb to it. An example is shown
Cong Houd97c1002015-12-01 05:29:22 +00001716 // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we
1717 // don't have to set C as A's successor as it already is. We only need to
1718 // update the edge probability on A->C. Note that B will not be
1719 // immediately removed from A's successors. It is possible that B->D is
1720 // not removed either if D is a fallthrough of B. Later the edge A->D
1721 // (generated here) and B->D will be combined into one edge. To maintain
1722 // correct edge probability of this combined edge, we need to set the edge
1723 // probability of A->B to zero, which is already done above. The edge
1724 // probability on A->D is calculated by scaling the original probability
1725 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00001726 //
1727 // Before ifcvt: After ifcvt (assume B->D is kept):
1728 //
1729 // A A
1730 // /| /|\
1731 // / B / B|
1732 // | /| | ||
1733 // |/ | | |/
1734 // C D C D
1735 //
1736 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00001737 ToBBI.BB->setSuccProbability(
Cong Houd40105d2015-09-18 20:22:41 +00001738 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00001739 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001740 else
Cong Houd97c1002015-12-01 05:29:22 +00001741 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001742 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001743 }
1744
Bob Wilson2371f4f2009-05-13 23:25:24 +00001745 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00001746 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00001747 FromBBI.BB->addSuccessor(NBB);
1748
Cong Houc1069892015-12-13 09:26:17 +00001749 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
1750 // we've done above.
1751 ToBBI.BB->normalizeSuccProbs();
1752
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001753 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001754 FromBBI.Predicate.clear();
1755
Evan Chengd0e66912007-05-23 07:23:16 +00001756 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001757 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001758 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001759 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001760 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001761 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001762
Evan Cheng4dd31a72007-06-11 22:26:22 +00001763 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001764 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001765 ToBBI.IsAnalyzed = false;
1766 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001767}
Akira Hatanaka4a616192015-06-08 18:50:43 +00001768
1769FunctionPass *
1770llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
1771 return new IfConverter(Ftor);
1772}