blob: ba2fa4ce1f1fce23ac8a426a971a9b5facddc809 [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//
Justin Lebaracc47102016-04-01 01:09:03 +000010// This file implements the machine instruction level if-conversion pass, which
11// tries to convert conditional branches into predicated instructions.
Evan Chengf5e53a52007-05-16 02:00:57 +000012//
13//===----------------------------------------------------------------------===//
14
Evan Chengf5e53a52007-05-16 02:00:57 +000015#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "BranchFolding.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000020#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000021#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000022#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000027#include "llvm/CodeGen/TargetSchedule.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000028#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000029#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000030#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000035#include "llvm/Target/TargetSubtargetInfo.h"
Cong Houd97c1002015-12-01 05:29:22 +000036#include <algorithm>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000037
Evan Chengf5e53a52007-05-16 02:00:57 +000038using namespace llvm;
39
Chandler Carruth1b9dde02014-04-22 02:02:50 +000040#define DEBUG_TYPE "ifcvt"
41
Chris Lattner769c86b2008-01-07 05:40:58 +000042// Hidden options for help debugging.
43static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
44static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
45static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000046static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000047 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000048static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000049 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000050static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000051 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000052static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000053 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000054static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000055 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000056static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000057 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000058static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000059 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000060static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
61 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000062
Evan Cheng2117d1f2007-06-09 01:03:43 +000063STATISTIC(NumSimple, "Number of simple if-conversions performed");
64STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
65STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000066STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000067STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
68STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
69STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
70STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000071STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000072STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000073
74namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000075 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000076 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000077 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000078 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000079 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
80 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000081 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000082 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000083 ICTriangle, // BB is entry of a triangle sub-CFG.
Evan Cheng4dd31a72007-06-11 22:26:22 +000084 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Chengf5e53a52007-05-16 02:00:57 +000085 };
86
87 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
88 /// if-conversion feasibility analysis. This includes results from
89 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000090 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000091 /// diamond shape), its size, whether it's predicable, and whether any
92 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000093 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +000094 /// IsDone - True if BB is not to be considered for ifcvt.
95 /// IsBeingAnalyzed - True if BB is currently being analyzed.
96 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
97 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
98 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
99 /// HasFallThrough - True if BB may fallthrough to the following BB.
100 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000101 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000102 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000103 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000104 /// ExtraCost - Extra cost for multi-cycle instructions.
105 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000106 /// BB - Corresponding MachineBasicBlock.
107 /// TrueBB / FalseBB- See AnalyzeBranch().
108 /// BrCond - Conditions for end of block conditional branches.
109 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000110 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000111 bool IsDone : 1;
112 bool IsBeingAnalyzed : 1;
113 bool IsAnalyzed : 1;
114 bool IsEnqueued : 1;
115 bool IsBrAnalyzable : 1;
116 bool HasFallThrough : 1;
117 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000118 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000119 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000120 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000121 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000122 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000123 MachineBasicBlock *BB;
124 MachineBasicBlock *TrueBB;
125 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000126 SmallVector<MachineOperand, 4> BrCond;
127 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000128 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000129 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
130 HasFallThrough(false), IsUnpredicable(false),
Evan Cheng23402fc2007-06-15 21:18:05 +0000131 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Craig Topperc0196b12014-04-14 00:51:57 +0000132 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
133 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000134 };
135
Bob Wilson59475732010-06-15 18:19:27 +0000136 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000137 /// BBI - Corresponding BBInfo.
138 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000139 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000140 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000141 /// NumDups - Number of instructions that would be duplicated due
142 /// to this if-conversion. (For diamonds, the number of
143 /// identical instructions at the beginnings of both
144 /// paths).
145 /// NumDups2 - For diamonds, the number of identical instructions
146 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000147 struct IfcvtToken {
148 BBInfo &BBI;
149 IfcvtKind Kind;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000150 bool NeedSubsumption;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000151 unsigned NumDups;
152 unsigned NumDups2;
153 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson2371f4f2009-05-13 23:25:24 +0000154 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000155 };
156
157 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
158 /// basic block number.
159 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000160 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000161
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000162 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000163 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000164 const TargetRegisterInfo *TRI;
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000165 const MachineBlockFrequencyInfo *MBFI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000166 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000167 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000168
Juergen Ributzka310034e2013-12-14 06:52:56 +0000169 LivePhysRegs Redefs;
170 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000171
Evan Chengc5adcca2012-06-08 21:53:50 +0000172 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000173 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000174 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000175 std::function<bool(const Function &)> PredicateFtor;
176
Evan Chengf5e53a52007-05-16 02:00:57 +0000177 public:
178 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000179 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
180 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(Ftor) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000181 initializeIfConverterPass(*PassRegistry::getPassRegistry());
182 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000183
Craig Topper4584cd52014-03-07 09:26:03 +0000184 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000185 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000186 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000187 MachineFunctionPass::getAnalysisUsage(AU);
188 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000189
Craig Topper4584cd52014-03-07 09:26:03 +0000190 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000191
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000192 MachineFunctionProperties getRequiredProperties() const override {
193 return MachineFunctionProperties().set(
194 MachineFunctionProperties::Property::AllVRegsAllocated);
195 }
196
Evan Chengf5e53a52007-05-16 02:00:57 +0000197 private:
Evan Cheng312b7232007-06-04 06:47:22 +0000198 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersonf31f33e2010-10-01 22:45:50 +0000199 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000200 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000201 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000202 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000203 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000204 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
205 unsigned &Dups1, unsigned &Dups2) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000206 void ScanInstructions(BBInfo &BBI);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000207 void AnalyzeBlock(MachineBasicBlock *MBB,
208 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000209 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng7783f822007-06-08 09:36:04 +0000210 bool isTriangle = false, bool RevBranch = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000211 void AnalyzeBlocks(MachineFunction &MF,
212 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000213 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000214 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000215 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
216 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000217 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
218 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000219 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000220 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000221 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000222 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000223 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000224 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000225 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000226 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000227
Evan Chengdebf9c52010-11-03 00:45:17 +0000228 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
229 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000230 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000231 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000232 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000233 }
234
Evan Chengdebf9c52010-11-03 00:45:17 +0000235 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
236 unsigned TCycle, unsigned TExtra,
237 MachineBasicBlock &FBB,
238 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000239 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000240 return TCycle > 0 && FCycle > 0 &&
241 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000242 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000243 }
244
Evan Chengbe9859e2007-06-07 02:12:15 +0000245 // blockAlwaysFallThrough - Block ends without a terminator.
246 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000247 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000248 }
249
Evan Cheng3a51c852007-06-16 09:34:52 +0000250 // IfcvtTokenCmp - Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000251 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
252 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000253 int Incr1 = (C1->Kind == ICDiamond)
254 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
255 int Incr2 = (C2->Kind == ICDiamond)
256 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
257 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000258 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000259 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000260 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000261 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000262 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000263 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000264 // Favors diamond over triangle, etc.
265 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
266 return true;
267 else if (C1->Kind == C2->Kind)
268 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
269 }
270 }
271 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000272 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000273 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000274
Evan Chengf5e53a52007-05-16 02:00:57 +0000275 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000276}
Evan Chengf5e53a52007-05-16 02:00:57 +0000277
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000278char &llvm::IfConverterID = IfConverter::ID;
279
Owen Anderson8ac477f2010-10-12 19:48:12 +0000280INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000281INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000282INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000283
Evan Chengf5e53a52007-05-16 02:00:57 +0000284bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Akira Hatanaka4a616192015-06-08 18:50:43 +0000285 if (PredicateFtor && !PredicateFtor(*MF.getFunction()))
286 return false;
287
Eric Christopher3d4276f2015-01-27 07:31:29 +0000288 const TargetSubtargetInfo &ST = MF.getSubtarget();
289 TLI = ST.getTargetLowering();
290 TII = ST.getInstrInfo();
291 TRI = ST.getRegisterInfo();
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000292 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000293 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000294 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000295 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000296
Evan Chengf5e53a52007-05-16 02:00:57 +0000297 if (!TII) return false;
298
Evan Chengc5adcca2012-06-08 21:53:50 +0000299 PreRegAlloc = MRI->isSSA();
300
301 bool BFChange = false;
302 if (!PreRegAlloc) {
303 // Tail merge tend to expose more if-conversion opportunities.
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000304 BranchFolder BF(true, false, *MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000305 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000306 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000307 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000308
David Greene72e47cd2010-01-04 22:02:01 +0000309 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000310 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000311
312 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000313 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000314 return false;
315 }
David Greene72e47cd2010-01-04 22:02:01 +0000316 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000317
Evan Chengf5e53a52007-05-16 02:00:57 +0000318 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000319 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000320
Justin Lebar3a7bc572016-02-22 17:51:28 +0000321 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000322 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000323 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
324 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
325 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000326 // Do an initial analysis for each basic block and find all the potential
327 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000328 bool Change = false;
329 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000330 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000331 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000332 Tokens.pop_back();
333 BBInfo &BBI = Token->BBI;
334 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000335 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000336 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000337
Evan Cheng4dd31a72007-06-11 22:26:22 +0000338 // If the block has been evicted out of the queue or it has already been
339 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000340 if (BBI.IsDone)
341 BBI.IsEnqueued = false;
342 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000343 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000344
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000345 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000346
Evan Cheng312b7232007-06-04 06:47:22 +0000347 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000348 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000349 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000350 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000351 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000352 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000353 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000354 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
355 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000356 << "): BB#" << BBI.BB->getNumber() << " ("
357 << ((Kind == ICSimpleFalse)
358 ? BBI.FalseBB->getNumber()
359 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000360 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000361 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000362 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000363 if (isFalse) ++NumSimpleFalse;
364 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000365 }
Evan Cheng312b7232007-06-04 06:47:22 +0000366 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000367 }
Evan Chengd0e66912007-05-23 07:23:16 +0000368 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000369 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000370 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000371 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000372 bool isFalse = Kind == ICTriangleFalse;
373 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000374 if (DisableTriangle && !isFalse && !isRev) break;
375 if (DisableTriangleR && !isFalse && isRev) break;
376 if (DisableTriangleF && isFalse && !isRev) break;
377 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000378 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000379 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000380 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000381 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000382 DEBUG(dbgs() << " rev");
383 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000384 << BBI.TrueBB->getNumber() << ",F:"
385 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000386 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000387 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000388 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000389 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000390 if (isRev) ++NumTriangleFRev;
391 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000392 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000393 if (isRev) ++NumTriangleRev;
394 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000395 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000396 }
Evan Chengd0e66912007-05-23 07:23:16 +0000397 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000398 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000399 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000400 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000401 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000402 << BBI.TrueBB->getNumber() << ",F:"
403 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000404 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000405 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000406 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000407 break;
408 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000409 }
410
Evan Cheng312b7232007-06-04 06:47:22 +0000411 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000412
Evan Cheng92fb5452007-06-15 07:36:12 +0000413 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
414 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
415 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000416 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000417 }
Evan Chengd0e66912007-05-23 07:23:16 +0000418
Evan Chengd0e66912007-05-23 07:23:16 +0000419 if (!Change)
420 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000421 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000422 }
Evan Cheng478b8052007-05-18 01:55:58 +0000423
Evan Cheng3a51c852007-06-16 09:34:52 +0000424 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 }
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000589 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000590 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.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000598 // If both blocks are returning don't skip the branches, since they will
599 // likely be both identical return instructions. In such cases the return
600 // can be left unpredicated.
601 // Check for already containing all of the block.
602 if (TIB == TIE || FIB == FIE)
603 return true;
604 --TIE;
605 --FIE;
606 if (!TrueBBI.BB->succ_empty() || !FalseBBI.BB->succ_empty()) {
607 while (TIE != TIB && TIE->isBranch())
608 --TIE;
609 while (FIE != FIB && FIE->isBranch())
610 --FIE;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000611 }
612
613 // If Dups1 includes all of a block, then don't count duplicate
614 // instructions at the end of the blocks.
615 if (TIB == TIE || FIB == FIE)
616 return true;
617
618 // Count duplicate instructions at the ends of the blocks.
619 while (TIE != TIB && FIE != FIB) {
620 // Skip dbg_value instructions. These do not count.
621 if (TIE->isDebugValue()) {
622 while (TIE != TIB && TIE->isDebugValue())
623 --TIE;
624 if (TIE == TIB)
625 break;
626 }
627 if (FIE->isDebugValue()) {
628 while (FIE != FIB && FIE->isDebugValue())
629 --FIE;
630 if (FIE == FIB)
631 break;
632 }
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000633 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000634 break;
635 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000636 --TIE;
637 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000638 }
639
640 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000641}
642
Evan Cheng4dd31a72007-06-11 22:26:22 +0000643/// ScanInstructions - Scan all the instructions in the block to determine if
644/// the block is predicable. In most cases, that means all the instructions
Chris Lattnera98c6792008-01-07 01:56:04 +0000645/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng4dd31a72007-06-11 22:26:22 +0000646/// instruction which can clobber a predicate (e.g. condition code register).
647/// If so, the block is not predicable unless it's the last instruction.
648void IfConverter::ScanInstructions(BBInfo &BBI) {
649 if (BBI.IsDone)
650 return;
651
Evan Chengc5adcca2012-06-08 21:53:50 +0000652 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000653 // First analyze the end of BB branches.
Craig Topperc0196b12014-04-14 00:51:57 +0000654 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000655 BBI.BrCond.clear();
656 BBI.IsBrAnalyzable =
657 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000658 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000659
660 if (BBI.BrCond.size()) {
661 // No false branch. This BB must end with a conditional branch and a
662 // fallthrough.
663 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000664 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000665 if (!BBI.FalseBB) {
666 // Malformed bcc? True and false blocks are the same?
667 BBI.IsUnpredicable = true;
668 return;
669 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000670 }
671
672 // Then scan all the instructions.
673 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000674 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000675 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000676 BBI.ClobbersPred = false;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000677 for (auto &MI : *BBI.BB) {
678 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000679 continue;
680
Justin Lebar7dba2e02016-04-15 01:38:41 +0000681 // It's unsafe to duplicate convergent instructions in this context, so set
682 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
683 // following CFG, which is subject to our "simple" transformation.
684 //
685 // BB0 // if (c1) goto BB1; else goto BB2;
686 // / \
687 // BB1 |
688 // | BB2 // if (c2) goto TBB; else goto FBB;
689 // | / |
690 // | / |
691 // TBB |
692 // | |
693 // | FBB
694 // |
695 // exit
696 //
697 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
698 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
699 // TBB contains a convergent instruction. This is safe iff doing so does
700 // not add a control-flow dependency to the convergent instruction -- i.e.,
701 // it's safe iff the set of control flows that leads us to the convergent
702 // instruction does not get smaller after the transformation.
703 //
704 // Originally we executed TBB if c1 || c2. After the transformation, there
705 // are two copies of TBB's instructions. We get to the first if c1, and we
706 // get to the second if !c1 && c2.
707 //
708 // There are clearly fewer ways to satisfy the condition "c1" than
709 // "c1 || c2". Since we've shrunk the set of control flows which lead to
710 // our convergent instruction, the transformation is unsafe.
711 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000712 BBI.CannotBeCopied = true;
713
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000714 bool isPredicated = TII->isPredicated(MI);
715 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000716
Joey Goulya5153cb2013-09-09 14:21:49 +0000717 // A conditional branch is not predicable, but it may be eliminated.
718 if (isCondBr)
719 continue;
720
721 if (!isPredicated) {
722 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000723 unsigned ExtraPredCost = TII->getPredicationCost(MI);
724 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000725 if (NumCycles > 1)
726 BBI.ExtraCost += NumCycles-1;
727 BBI.ExtraCost2 += ExtraPredCost;
728 } else if (!AlreadyPredicated) {
729 // FIXME: This instruction is already predicated before the
730 // if-conversion pass. It's probably something like a conditional move.
731 // Mark this block unpredicable for now.
732 BBI.IsUnpredicable = true;
733 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000734 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000735
736 if (BBI.ClobbersPred && !isPredicated) {
737 // Predicate modification instruction should end the block (except for
738 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000739 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000740 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000741 BBI.IsUnpredicable = true;
742 return;
743 }
744
Evan Chengfbc73092007-07-10 17:50:43 +0000745 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
746 // still potentially predicable.
747 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000748 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000749 BBI.ClobbersPred = true;
750
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000751 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000752 BBI.IsUnpredicable = true;
753 return;
754 }
755 }
756}
757
758/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
759/// predicated by the specified predicate.
760bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000761 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng4dd31a72007-06-11 22:26:22 +0000762 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000763 // If the block is dead or unpredicable, then it cannot be predicated.
764 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000765 return false;
766
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000767 // If it is already predicated but we couldn't analyze its terminator, the
768 // latter might fallthrough, but we can't determine where to.
769 // Conservatively avoid if-converting again.
770 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
771 return false;
772
Quentin Colombetbdab2272013-07-24 20:20:37 +0000773 // If it is already predicated, check if the new predicate subsumes
774 // its predicate.
775 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000776 return false;
777
778 if (BBI.BrCond.size()) {
779 if (!isTriangle)
780 return false;
781
Bob Wilson2371f4f2009-05-13 23:25:24 +0000782 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000783 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
784 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000785 if (RevBranch) {
786 if (TII->ReverseBranchCondition(Cond))
787 return false;
788 }
789 if (TII->ReverseBranchCondition(RevPred) ||
790 !TII->SubsumesPredicate(Cond, RevPred))
791 return false;
792 }
793
794 return true;
795}
796
Evan Cheng7783f822007-06-08 09:36:04 +0000797/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +0000798/// the specified block. Record its successors and whether it looks like an
799/// if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000800void IfConverter::AnalyzeBlock(
801 MachineBasicBlock *MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000802 struct BBState {
803 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
804 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000805
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000806 /// This flag is true if MBB's successors have been analyzed.
807 bool SuccsAnalyzed;
808 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000809
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000810 // Push MBB to the stack.
811 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000812
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000813 while (!BBStack.empty()) {
814 BBState &State = BBStack.back();
815 MachineBasicBlock *BB = State.MBB;
816 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000817
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000818 if (!State.SuccsAnalyzed) {
819 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
820 BBStack.pop_back();
821 continue;
822 }
Evan Cheng9030b982007-06-06 10:16:17 +0000823
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000824 BBI.BB = BB;
825 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000826
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000827 ScanInstructions(BBI);
Evan Chengb9bff582009-06-15 21:24:34 +0000828
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000829 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
830 // not considered for ifcvt anymore.
831 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
832 BBI.IsBeingAnalyzed = false;
833 BBI.IsAnalyzed = true;
834 BBStack.pop_back();
835 continue;
836 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000837
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000838 // Do not ifcvt if either path is a back edge to the entry block.
839 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
840 BBI.IsBeingAnalyzed = false;
841 BBI.IsAnalyzed = true;
842 BBStack.pop_back();
843 continue;
844 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000845
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000846 // Do not ifcvt if true and false fallthrough blocks are the same.
847 if (!BBI.FalseBB) {
848 BBI.IsBeingAnalyzed = false;
849 BBI.IsAnalyzed = true;
850 BBStack.pop_back();
851 continue;
852 }
Evan Cheng7783f822007-06-08 09:36:04 +0000853
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000854 // Push the False and True blocks to the stack.
855 State.SuccsAnalyzed = true;
856 BBStack.push_back(BBI.FalseBB);
857 BBStack.push_back(BBI.TrueBB);
858 continue;
859 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000860
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000861 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
862 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +0000863
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000864 if (TrueBBI.IsDone && FalseBBI.IsDone) {
865 BBI.IsBeingAnalyzed = false;
866 BBI.IsAnalyzed = true;
867 BBStack.pop_back();
868 continue;
869 }
870
871 SmallVector<MachineOperand, 4>
872 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
873 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
874
875 unsigned Dups = 0;
876 unsigned Dups2 = 0;
877 bool TNeedSub = !TrueBBI.Predicate.empty();
878 bool FNeedSub = !FalseBBI.Predicate.empty();
879 bool Enqueued = false;
880
881 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
882
883 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
884 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
885 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
886 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000887 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000888 Prediction) &&
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000889 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
890 FeasibilityAnalysis(FalseBBI, RevCond)) {
891 // Diamond:
892 // EBB
893 // / \_
894 // | |
895 // TBB FBB
896 // \ /
897 // TailBB
898 // Note TailBB can be empty.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000899 Tokens.push_back(llvm::make_unique<IfcvtToken>(
900 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
Evan Cheng3a51c852007-06-16 09:34:52 +0000901 Enqueued = true;
902 }
903
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000904 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
905 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
906 TrueBBI.ExtraCost2, Prediction) &&
907 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
908 // Triangle:
909 // EBB
910 // | \_
911 // | |
912 // | TBB
913 // | /
914 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000915 Tokens.push_back(
916 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000917 Enqueued = true;
918 }
919
920 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
921 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
922 TrueBBI.ExtraCost2, Prediction) &&
923 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000924 Tokens.push_back(
925 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000926 Enqueued = true;
927 }
928
929 if (ValidSimple(TrueBBI, Dups, Prediction) &&
930 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
931 TrueBBI.ExtraCost2, Prediction) &&
932 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
933 // Simple (split, no rejoin):
934 // EBB
935 // | \_
936 // | |
937 // | TBB---> exit
938 // |
939 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000940 Tokens.push_back(
941 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000942 Enqueued = true;
943 }
944
945 if (CanRevCond) {
946 // Try the other path...
947 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
948 Prediction.getCompl()) &&
949 MeetIfcvtSizeLimit(*FalseBBI.BB,
950 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
951 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
952 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000953 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
954 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000955 Enqueued = true;
956 }
957
958 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
959 Prediction.getCompl()) &&
960 MeetIfcvtSizeLimit(*FalseBBI.BB,
961 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000962 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000963 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000964 Tokens.push_back(
965 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000966 Enqueued = true;
967 }
968
969 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
970 MeetIfcvtSizeLimit(*FalseBBI.BB,
971 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
972 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
973 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000974 Tokens.push_back(
975 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000976 Enqueued = true;
977 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000978 }
979
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000980 BBI.IsEnqueued = Enqueued;
981 BBI.IsBeingAnalyzed = false;
982 BBI.IsAnalyzed = true;
983 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +0000984 }
Evan Cheng2e82cef2007-05-18 18:14:37 +0000985}
986
Evan Cheng905a8f42007-05-30 19:49:19 +0000987/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000988/// candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000989void IfConverter::AnalyzeBlocks(
990 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000991 for (auto &BB : MF)
992 AnalyzeBlock(&BB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +0000993
Evan Cheng20e05992007-06-01 00:12:12 +0000994 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +0000995 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +0000996}
997
Evan Cheng288f1542007-06-08 22:01:07 +0000998/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
999/// that all the intervening blocks are empty (given BB can fall through to its
1000/// next block).
1001static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001002 MachineFunction::iterator PI = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001003 MachineFunction::iterator I = std::next(PI);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001004 MachineFunction::iterator TI = ToBB->getIterator();
Evan Cheng2c1acd62007-06-05 07:05:25 +00001005 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001006 while (I != TI) {
1007 // Check isSuccessor to avoid case where the next block is empty, but
1008 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001009 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001010 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001011 PI = I++;
1012 }
Evan Cheng312b7232007-06-04 06:47:22 +00001013 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001014}
1015
Evan Cheng51eb2c32007-06-18 08:37:25 +00001016/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
1017/// to determine if it can be if-converted. If predecessor is already enqueued,
1018/// dequeue it!
1019void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001020 for (const auto &Predecessor : BB->predecessors()) {
1021 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +00001022 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001023 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001024 PBBI.IsAnalyzed = false;
1025 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001026 }
1027}
1028
Evan Chengc2237ce2007-05-29 22:31:16 +00001029/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
1030///
1031static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
1032 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001033 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001034 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +00001035 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001036}
1037
Evan Cheng288f1542007-06-08 22:01:07 +00001038/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1039/// successors.
1040void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001041 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001042 SmallVector<MachineOperand, 4> Cond;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001043 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
1044 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001045}
1046
Matthias Braund616ccc2013-10-11 19:04:37 +00001047/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1048/// values defined in MI which are not live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001049static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Pete Cooper7605e372015-05-05 20:14:22 +00001050 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001051 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001052
Pete Cooper7605e372015-05-05 20:14:22 +00001053 // Now add the implicit uses for each of the clobbered values.
1054 for (auto Reg : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001055 // FIXME: Const cast here is nasty, but better than making StepForward
1056 // take a mutable instruction instead of const.
Pete Cooper27483912015-05-06 22:51:04 +00001057 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1058 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001059 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001060 if (Op.isRegMask()) {
1061 // First handle regmasks. They clobber any entries in the mask which
1062 // means that we need a def for those registers.
Pete Cooper7605e372015-05-05 20:14:22 +00001063 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Pete Cooperce9ad752015-05-05 22:09:41 +00001064
1065 // We also need to add an implicit def of this register for the later
1066 // use to read from.
1067 // For the register allocator to have allocated a register clobbered
1068 // by the call which is used later, it must be the case that
1069 // the call doesn't return.
1070 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1071 continue;
1072 }
1073 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001074 if (Op.isDead()) {
1075 // If we found a dead def, but it needs to be live, then remove the dead
1076 // flag.
1077 if (Redefs.contains(Op.getReg()))
1078 Op.setIsDead(false);
1079 }
Pete Cooperce9ad752015-05-05 22:09:41 +00001080 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Matthias Braund616ccc2013-10-11 19:04:37 +00001081 }
1082}
1083
1084/**
1085 * Remove kill flags from operands with a registers in the @p DontKill set.
1086 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001087static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001088 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001089 if (!O->isReg() || !O->isKill())
1090 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001091 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001092 O->setIsKill(false);
1093 }
1094}
1095
1096/**
1097 * Walks a range of machine instructions and removes kill flags for registers
1098 * in the @p DontKill set.
1099 */
1100static void RemoveKills(MachineBasicBlock::iterator I,
1101 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001102 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001103 const MCRegisterInfo &MCRI) {
1104 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001105 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001106}
1107
Evan Cheng312b7232007-06-04 06:47:22 +00001108/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001109///
Evan Cheng3a51c852007-06-16 09:34:52 +00001110bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001111 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1112 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1113 BBInfo *CvtBBI = &TrueBBI;
1114 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001115
Owen Anderson4f6bf042008-08-14 22:49:33 +00001116 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001117 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001118 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001119
Evan Cheng51eb2c32007-06-18 08:37:25 +00001120 if (CvtBBI->IsDone ||
1121 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001122 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001123 BBI.IsAnalyzed = false;
1124 CvtBBI->IsAnalyzed = false;
1125 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001126 }
Evan Chengd0e66912007-05-23 07:23:16 +00001127
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001128 if (CvtBBI->BB->hasAddressTaken())
1129 // Conservatively abort if-conversion if BB's address is taken.
1130 return false;
1131
Evan Cheng3a51c852007-06-16 09:34:52 +00001132 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001133 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001134 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001135
Bob Wilson45814342010-06-19 05:33:57 +00001136 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001137 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001138 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001139 Redefs.addLiveIns(CvtBBI->BB);
1140 Redefs.addLiveIns(NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001141
1142 // Compute a set of registers which must not be killed by instructions in
1143 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001144 DontKill.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001145 DontKill.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001146
Evan Cheng92fb5452007-06-15 07:36:12 +00001147 if (CvtBBI->BB->pred_size() > 1) {
1148 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001149 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001150 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001151 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001152
1153 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1154 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001155 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001156 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001157 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001158 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001159
Evan Cheng92fb5452007-06-15 07:36:12 +00001160 // Merge converted block into entry block.
1161 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1162 MergeBlocks(BBI, *CvtBBI);
1163 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001164
Evan Chenge4ec9182007-06-06 02:08:52 +00001165 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001166 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001167 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001168 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001169 // Now ifcvt'd block will look like this:
1170 // BB:
1171 // ...
1172 // t, f = cmp
1173 // if t op
1174 // b BBf
1175 //
1176 // We cannot further ifcvt this block because the unconditional branch
1177 // will have to be predicated on the new condition, that will not be
1178 // available if cmp executes.
1179 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001180 }
Evan Chenge26c0912007-05-21 22:22:58 +00001181
Evan Cheng288f1542007-06-08 22:01:07 +00001182 RemoveExtraEdges(BBI);
1183
Evan Chengd0e66912007-05-23 07:23:16 +00001184 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001185 if (!IterIfcvt)
1186 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001187 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001188 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001189
1190 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001191 return true;
1192}
1193
Evan Chengaf716102007-05-16 21:54:37 +00001194/// IfConvertTriangle - If convert a triangle sub-CFG.
1195///
Evan Cheng3a51c852007-06-16 09:34:52 +00001196bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001197 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001198 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1199 BBInfo *CvtBBI = &TrueBBI;
1200 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001201 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001202
Owen Anderson4f6bf042008-08-14 22:49:33 +00001203 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001204 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001205 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001206
Evan Cheng51eb2c32007-06-18 08:37:25 +00001207 if (CvtBBI->IsDone ||
1208 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001209 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001210 BBI.IsAnalyzed = false;
1211 CvtBBI->IsAnalyzed = false;
1212 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001213 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001214
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001215 if (CvtBBI->BB->hasAddressTaken())
1216 // Conservatively abort if-conversion if BB's address is taken.
1217 return false;
1218
Evan Cheng3a51c852007-06-16 09:34:52 +00001219 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001220 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001221 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001222
Evan Cheng3a51c852007-06-16 09:34:52 +00001223 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001224 if (ReverseBranchCondition(*CvtBBI)) {
1225 // BB has been changed, modify its predecessors (except for this
1226 // one) so they don't get ifcvt'ed based on bad intel.
1227 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1228 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1229 MachineBasicBlock *PBB = *PI;
1230 if (PBB == BBI.BB)
1231 continue;
1232 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1233 if (PBBI.IsEnqueued) {
1234 PBBI.IsAnalyzed = false;
1235 PBBI.IsEnqueued = false;
1236 }
Evan Chengadd97762007-06-14 23:34:09 +00001237 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001238 }
1239 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001240
Bob Wilson45814342010-06-19 05:33:57 +00001241 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001242 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001243 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001244 Redefs.addLiveIns(CvtBBI->BB);
1245 Redefs.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001246
Andrew Trick276dd452013-10-14 20:45:17 +00001247 DontKill.clear();
1248
Craig Topperc0196b12014-04-14 00:51:57 +00001249 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001250 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001251
Manman Renb6819182014-01-29 23:18:47 +00001252 if (HasEarlyExit) {
Cong Houd97c1002015-12-01 05:29:22 +00001253 // Get probabilities before modifying CvtBBI->BB and BBI.BB.
1254 CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB);
1255 CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB);
1256 BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB);
1257 BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001258 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001259
Bob Wilson1e5da552010-06-29 00:55:23 +00001260 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001261 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001262 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001263 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001264 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001265
1266 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1267 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001268 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001269 } else {
1270 // Predicate the 'true' block after removing its branch.
1271 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001272 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001273
Evan Cheng0598b2d2007-06-18 22:44:57 +00001274 // Now merge the entry of the triangle with the true block.
1275 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001276 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001277 }
1278
Evan Cheng312b7232007-06-04 06:47:22 +00001279 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001280 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001281 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1282 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001283 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001284 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001285
Cong Houd97c1002015-12-01 05:29:22 +00001286 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1287 // NewNext = New_Prob(BBI.BB, NextBBI->BB) =
1288 // Prob(BBI.BB, NextBBI->BB) +
1289 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB)
1290 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1291 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB)
1292 auto NewTrueBB = getNextBlock(BBI.BB);
1293 auto NewNext = BBNext + BBCvt * CvtNext;
1294 auto NewTrueBBIter =
1295 std::find(BBI.BB->succ_begin(), BBI.BB->succ_end(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001296 if (NewTrueBBIter != BBI.BB->succ_end())
1297 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001298
1299 auto NewFalse = BBCvt * CvtFalse;
1300 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1301 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001302 }
Evan Cheng7783f822007-06-08 09:36:04 +00001303
1304 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001305 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001306 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001307 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001308 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001309 if (!isFallThrough) {
1310 // Only merge them if the true block does not fallthrough to the false
1311 // block. By not merging them, we make it possible to iteratively
1312 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001313 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001314 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1315 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001316 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001317 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001318 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001319 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1320 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001321 }
Evan Cheng7783f822007-06-08 09:36:04 +00001322 // Mixed predicated and unpredicated code. This cannot be iteratively
1323 // predicated.
1324 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001325 }
Evan Chenge26c0912007-05-21 22:22:58 +00001326
Evan Cheng288f1542007-06-08 22:01:07 +00001327 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001328
Evan Chengd0e66912007-05-23 07:23:16 +00001329 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001330 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001331 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001332 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001333 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001334 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001335 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001336
1337 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001338 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001339}
1340
Evan Chengaf716102007-05-16 21:54:37 +00001341/// IfConvertDiamond - If convert a diamond sub-CFG.
1342///
Evan Cheng51eb2c32007-06-18 08:37:25 +00001343bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1344 unsigned NumDups1, unsigned NumDups2) {
Evan Cheng312b7232007-06-04 06:47:22 +00001345 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2e82cef2007-05-18 18:14:37 +00001346 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng3a51c852007-06-16 09:34:52 +00001347 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson2371f4f2009-05-13 23:25:24 +00001348 // True block must fall through or end with an unanalyzable terminator.
Evan Cheng3a51c852007-06-16 09:34:52 +00001349 if (!TailBB) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001350 if (blockAlwaysFallThrough(TrueBBI))
1351 TailBB = FalseBBI.TrueBB;
1352 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Chengf5e53a52007-05-16 02:00:57 +00001353 }
Evan Chenge26c0912007-05-21 22:22:58 +00001354
Evan Cheng51eb2c32007-06-18 08:37:25 +00001355 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1356 TrueBBI.BB->pred_size() > 1 ||
1357 FalseBBI.BB->pred_size() > 1) {
1358 // Something has changed. It's no longer safe to predicate these blocks.
1359 BBI.IsAnalyzed = false;
1360 TrueBBI.IsAnalyzed = false;
1361 FalseBBI.IsAnalyzed = false;
1362 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001363 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001364
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001365 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1366 // Conservatively abort if-conversion if either BB has its address taken.
1367 return false;
1368
Bob Wilson1e5da552010-06-29 00:55:23 +00001369 // Put the predicated instructions from the 'true' block before the
1370 // instructions from the 'false' block, unless the true block would clobber
1371 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001372 BBInfo *BBI1 = &TrueBBI;
1373 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001374 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001375 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001376 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001377 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1378 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001379
Evan Cheng3a51c852007-06-16 09:34:52 +00001380 // Figure out the more profitable ordering.
1381 bool DoSwap = false;
1382 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1383 DoSwap = true;
1384 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001385 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001386 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001387 }
1388 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001389 std::swap(BBI1, BBI2);
1390 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001391 }
Evan Cheng79484222007-06-05 23:46:14 +00001392
Evan Cheng51eb2c32007-06-18 08:37:25 +00001393 // Remove the conditional branch from entry to the blocks.
1394 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1395
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001396 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001397 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001398 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001399 Redefs.addLiveIns(BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001400
Evan Cheng51eb2c32007-06-18 08:37:25 +00001401 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001402 // Skip dbg_value instructions
Benjamin Kramer6b568962015-06-23 14:47:29 +00001403 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1404 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001405 BBI1->NonPredSize -= NumDups1;
1406 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001407
1408 // Skip past the dups on each side separately since there may be
1409 // differing dbg_value entries.
1410 for (unsigned i = 0; i < NumDups1; ++DI1) {
1411 if (!DI1->isDebugValue())
1412 ++i;
1413 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001414 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001415 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001416 if (!DI2->isDebugValue())
1417 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001418 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001419
Matthias Braund616ccc2013-10-11 19:04:37 +00001420 // Compute a set of registers which must not be killed by instructions in BB1:
1421 // This is everything used+live in BB2 after the duplicated instructions. We
1422 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001423 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001424 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1425 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001426 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001427 }
1428
1429 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1430 ++I) {
Pete Cooper7605e372015-05-05 20:14:22 +00001431 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1432 Redefs.stepForward(*I, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001433 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001434 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1435 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1436
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001437 // Remove branch from the 'true' block, unless it was not analyzable.
1438 // Non-analyzable branches need to be preserved, since in such cases,
1439 // the CFG structure is not an actual diamond (the join block may not
1440 // be present).
1441 if (BBI1->IsBrAnalyzable)
1442 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1443 // Remove duplicated instructions.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001444 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001445 for (unsigned i = 0; i != NumDups2; ) {
1446 // NumDups2 only counted non-dbg_value instructions, so this won't
1447 // run off the head of the list.
1448 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001449 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001450 // skip dbg_value instructions
1451 if (!DI1->isDebugValue())
1452 ++i;
1453 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001454 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001455
Matthias Braund616ccc2013-10-11 19:04:37 +00001456 // Kill flags in the true block for registers living into the false block
1457 // must be removed.
1458 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1459
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001460 // Remove 'false' block branch (unless it was not analyzable), and find
1461 // the last instruction to predicate.
1462 if (BBI2->IsBrAnalyzable)
1463 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001464 DI2 = BBI2->BB->end();
1465 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001466 // NumDups2 only counted non-dbg_value instructions, so this won't
1467 // run off the head of the list.
1468 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001469 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001470 // skip dbg_value instructions
1471 if (!DI2->isDebugValue())
1472 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001473 }
Evan Cheng4266a792011-12-19 22:01:30 +00001474
1475 // Remember which registers would later be defined by the false block.
1476 // This allows us not to predicate instructions in the true block that would
1477 // later be re-defined. That is, rather than
1478 // subeq r0, r1, #1
1479 // addne r0, r1, #1
1480 // generate:
1481 // sub r0, r1, #1
1482 // addne r0, r1, #1
1483 SmallSet<unsigned, 4> RedefsByFalse;
1484 SmallSet<unsigned, 4> ExtUses;
1485 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1486 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1487 if (FI->isDebugValue())
1488 continue;
1489 SmallVector<unsigned, 4> Defs;
1490 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1491 const MachineOperand &MO = FI->getOperand(i);
1492 if (!MO.isReg())
1493 continue;
1494 unsigned Reg = MO.getReg();
1495 if (!Reg)
1496 continue;
1497 if (MO.isDef()) {
1498 Defs.push_back(Reg);
1499 } else if (!RedefsByFalse.count(Reg)) {
1500 // These are defined before ctrl flow reach the 'false' instructions.
1501 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001502 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1503 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001504 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001505 }
1506 }
1507
1508 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1509 unsigned Reg = Defs[i];
1510 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001511 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1512 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001513 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001514 }
1515 }
1516 }
1517 }
1518
1519 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001520 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001521
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001522 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1523 // a non-predicated in BBI2, then we don't want to predicate the one from
1524 // BBI2. The reason is that if we merged these blocks, we would end up with
1525 // two predicated terminators in the same block.
1526 if (!BBI2->BB->empty() && (DI2 == BBI2->BB->end())) {
1527 MachineBasicBlock::iterator BBI1T = BBI1->BB->getFirstTerminator();
1528 MachineBasicBlock::iterator BBI2T = BBI2->BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001529 if (BBI1T != BBI1->BB->end() && TII->isPredicated(*BBI1T) &&
1530 BBI2T != BBI2->BB->end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001531 --DI2;
1532 }
1533
Evan Cheng4266a792011-12-19 22:01:30 +00001534 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001535 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001536
Evan Cheng0598b2d2007-06-18 22:44:57 +00001537 // Merge the true block into the entry of the diamond.
Craig Topperc0196b12014-04-14 00:51:57 +00001538 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1539 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001540
Bob Wilson2371f4f2009-05-13 23:25:24 +00001541 // If the if-converted block falls through or unconditionally branches into
1542 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001543 // fold the tail block in as well. Otherwise, unless it falls through to the
1544 // tail, add a unconditional branch to it.
1545 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001546 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001547 bool CanMergeTail = !TailBBI.HasFallThrough &&
1548 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001549 // The if-converted block can still have a predicated terminator
1550 // (e.g. a predicated return). If that is the case, we cannot merge
1551 // it with the tail block.
1552 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001553 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001554 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001555 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1556 // check if there are any other predecessors besides those.
1557 unsigned NumPreds = TailBB->pred_size();
1558 if (NumPreds > 1)
1559 CanMergeTail = false;
1560 else if (NumPreds == 1 && CanMergeTail) {
1561 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1562 if (*PI != BBI1->BB && *PI != BBI2->BB)
1563 CanMergeTail = false;
1564 }
1565 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001566 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001567 TailBBI.IsDone = true;
1568 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001569 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Evan Cheng0598b2d2007-06-18 22:44:57 +00001570 InsertUncondBranch(BBI.BB, TailBB, TII);
1571 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001572 }
Evan Chenge26c0912007-05-21 22:22:58 +00001573 }
1574
Bob Wilson1e5da552010-06-29 00:55:23 +00001575 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1576 // which can happen here if TailBB is unanalyzable and is merged, so
1577 // explicitly remove BBI1 and BBI2 as successors.
1578 BBI.BB->removeSuccessor(BBI1->BB);
Cong Houc1069892015-12-13 09:26:17 +00001579 BBI.BB->removeSuccessor(BBI2->BB, true);
Evan Cheng288f1542007-06-08 22:01:07 +00001580 RemoveExtraEdges(BBI);
1581
Evan Cheng79484222007-06-05 23:46:14 +00001582 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001583 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001584 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001585
1586 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001587 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001588}
1589
Evan Cheng4266a792011-12-19 22:01:30 +00001590static bool MaySpeculate(const MachineInstr *MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001591 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001592 bool SawStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001593 if (!MI->isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001594 return false;
1595
1596 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1597 const MachineOperand &MO = MI->getOperand(i);
1598 if (!MO.isReg())
1599 continue;
1600 unsigned Reg = MO.getReg();
1601 if (!Reg)
1602 continue;
1603 if (MO.isDef() && !LaterRedefs.count(Reg))
1604 return false;
1605 }
1606
1607 return true;
1608}
1609
Evan Cheng51eb2c32007-06-18 08:37:25 +00001610/// PredicateBlock - Predicate instructions from the start of the block to the
1611/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001612void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001613 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001614 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001615 SmallSet<unsigned, 4> *LaterRedefs) {
1616 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001617 bool MaySpec = LaterRedefs != nullptr;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001618 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001619 if (I->isDebugValue() || TII->isPredicated(*I))
Evan Chengd0e66912007-05-23 07:23:16 +00001620 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001621 // It may be possible not to predicate an instruction if it's the 'true'
1622 // side of a diamond and the 'false' side may re-define the instruction's
1623 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001624 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001625 AnyUnpred = true;
1626 continue;
1627 }
1628 // If any instruction is predicated, then every instruction after it must
1629 // be predicated.
1630 MaySpec = false;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001631 if (!TII->PredicateInstruction(*I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001632#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001633 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001634#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001635 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001636 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001637
Bob Wilson45814342010-06-19 05:33:57 +00001638 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001639 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001640 UpdatePredRedefs(*I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001641 }
Evan Chengd0e66912007-05-23 07:23:16 +00001642
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001643 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001644
Evan Cheng92fb5452007-06-15 07:36:12 +00001645 BBI.IsAnalyzed = false;
1646 BBI.NonPredSize = 0;
1647
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001648 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001649 if (AnyUnpred)
1650 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001651}
1652
Evan Cheng92fb5452007-06-15 07:36:12 +00001653/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1654/// the destination block. Skip end of block branches if IgnoreBr is true.
1655void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001656 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001657 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001658 MachineFunction &MF = *ToBBI.BB->getParent();
1659
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001660 for (auto &I : *FromBBI.BB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001661 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001662 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001663 break;
1664
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001665 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001666 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001667 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001668 unsigned ExtraPredCost = TII->getPredicationCost(I);
1669 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001670 if (NumCycles > 1)
1671 ToBBI.ExtraCost += NumCycles-1;
1672 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001673
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001674 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001675 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001676#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001677 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001678#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001679 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001680 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001681 }
1682
Bob Wilson45814342010-06-19 05:33:57 +00001683 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001684 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001685 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001686
1687 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001688 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001689 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001690 }
1691
Bob Wilson1e5da552010-06-29 00:55:23 +00001692 if (!IgnoreBr) {
1693 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1694 FromBBI.BB->succ_end());
1695 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001696 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001697
Bob Wilson1e5da552010-06-29 00:55:23 +00001698 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1699 MachineBasicBlock *Succ = Succs[i];
1700 // Fallthrough edge can't be transferred.
1701 if (Succ == FallThrough)
1702 continue;
1703 ToBBI.BB->addSuccessor(Succ);
1704 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001705 }
1706
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001707 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1708 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001709
1710 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1711 ToBBI.IsAnalyzed = false;
1712
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001713 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001714}
1715
Evan Cheng0f745da2007-05-18 00:20:58 +00001716/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00001717/// This will leave FromBB as an empty block, so remove all of its
1718/// successor edges except for the fall-through edge. If AddEdges is true,
1719/// i.e., when FromBBI's branch is being moved, add those successor edges to
1720/// ToBBI.
1721void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001722 assert(!FromBBI.BB->hasAddressTaken() &&
1723 "Removing a BB whose address is taken!");
1724
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001725 // In case FromBBI.BB contains terminators (e.g. return instruction),
1726 // first move the non-terminator instructions, then the terminators.
1727 MachineBasicBlock::iterator FromTI = FromBBI.BB->getFirstTerminator();
1728 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
1729 ToBBI.BB->splice(ToTI, FromBBI.BB, FromBBI.BB->begin(), FromTI);
1730
1731 // If FromBB has non-predicated terminator we should copy it at the end.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001732 if (FromTI != FromBBI.BB->end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001733 ToTI = ToBBI.BB->end();
1734 ToBBI.BB->splice(ToTI, FromBBI.BB, FromTI, FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00001735
Cong Houb9e8d482015-12-17 01:29:08 +00001736 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1737 // unknown probabilities into known ones.
1738 // FIXME: This usage is too tricky and in the future we would like to
1739 // eliminate all unknown probabilities in MBB.
1740 ToBBI.BB->normalizeSuccProbs();
1741
Cong Houd40105d2015-09-18 20:22:41 +00001742 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
1743 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00001744 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001745 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001746 // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001747 // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00001748 auto To2FromProb = BranchProbability::getZero();
Cong Houfa1917c2015-12-01 00:02:51 +00001749 if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
Cong Houd97c1002015-12-01 05:29:22 +00001750 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB);
1751 // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the
1752 // edge probability being merged to other edges when this edge is removed
1753 // later.
1754 ToBBI.BB->setSuccProbability(
1755 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB),
1756 BranchProbability::getZero());
1757 }
1758
Cong Houd40105d2015-09-18 20:22:41 +00001759 for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
1760 MachineBasicBlock *Succ = FromSuccs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00001761 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001762 if (Succ == FallThrough)
1763 continue;
Cong Houd40105d2015-09-18 20:22:41 +00001764
Cong Houd97c1002015-12-01 05:29:22 +00001765 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00001766 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001767 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
1768 // which is a portion of the edge probability from FromBBI.BB to Succ. The
1769 // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if
1770 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
1771 NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001772
Cong Houd97c1002015-12-01 05:29:22 +00001773 // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
Cong Houd40105d2015-09-18 20:22:41 +00001774 // only happens when if-converting a diamond CFG and FromBBI.BB is the
1775 // tail BB. In this case FromBBI.BB post-dominates ToBBI.BB and hence we
Cong Houd97c1002015-12-01 05:29:22 +00001776 // could just use the probabilities on FromBBI.BB's out-edges when adding
1777 // new successors.
1778 if (!To2FromProb.isZero())
1779 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00001780 }
1781
Evan Chengbe9859e2007-06-07 02:12:15 +00001782 FromBBI.BB->removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001783
1784 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001785 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00001786 // probability of this edge by adding NewProb to it. An example is shown
Cong Houd97c1002015-12-01 05:29:22 +00001787 // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we
1788 // don't have to set C as A's successor as it already is. We only need to
1789 // update the edge probability on A->C. Note that B will not be
1790 // immediately removed from A's successors. It is possible that B->D is
1791 // not removed either if D is a fallthrough of B. Later the edge A->D
1792 // (generated here) and B->D will be combined into one edge. To maintain
1793 // correct edge probability of this combined edge, we need to set the edge
1794 // probability of A->B to zero, which is already done above. The edge
1795 // probability on A->D is calculated by scaling the original probability
1796 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00001797 //
1798 // Before ifcvt: After ifcvt (assume B->D is kept):
1799 //
1800 // A A
1801 // /| /|\
1802 // / B / B|
1803 // | /| | ||
1804 // |/ | | |/
1805 // C D C D
1806 //
1807 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00001808 ToBBI.BB->setSuccProbability(
Cong Houd40105d2015-09-18 20:22:41 +00001809 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00001810 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001811 else
Cong Houd97c1002015-12-01 05:29:22 +00001812 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001813 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001814 }
1815
Bob Wilson2371f4f2009-05-13 23:25:24 +00001816 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00001817 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00001818 FromBBI.BB->addSuccessor(NBB);
1819
Cong Houc1069892015-12-13 09:26:17 +00001820 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
1821 // we've done above.
1822 ToBBI.BB->normalizeSuccProbs();
1823
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001824 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001825 FromBBI.Predicate.clear();
1826
Evan Chengd0e66912007-05-23 07:23:16 +00001827 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001828 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001829 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001830 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001831 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001832 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001833
Evan Cheng4dd31a72007-06-11 22:26:22 +00001834 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001835 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001836 ToBBI.IsAnalyzed = false;
1837 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001838}
Akira Hatanaka4a616192015-06-08 18:50:43 +00001839
1840FunctionPass *
1841llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
1842 return new IfConverter(Ftor);
1843}