blob: a8e72f4be8445f104b09f1b10b6dfc1f3264b836 [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 Lebarf62b1652016-02-22 17:51:30 +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
192 private:
Evan Cheng312b7232007-06-04 06:47:22 +0000193 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersonf31f33e2010-10-01 22:45:50 +0000194 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000195 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000196 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000197 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000198 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000199 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
200 unsigned &Dups1, unsigned &Dups2) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000201 void ScanInstructions(BBInfo &BBI);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000202 void AnalyzeBlock(MachineBasicBlock *MBB,
203 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000204 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng7783f822007-06-08 09:36:04 +0000205 bool isTriangle = false, bool RevBranch = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000206 void AnalyzeBlocks(MachineFunction &MF,
207 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000208 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000209 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000210 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
211 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000212 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
213 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000214 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000215 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000216 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000217 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000218 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000219 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000220 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000221 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000222
Evan Chengdebf9c52010-11-03 00:45:17 +0000223 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
224 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000225 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000226 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000227 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000228 }
229
Evan Chengdebf9c52010-11-03 00:45:17 +0000230 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
231 unsigned TCycle, unsigned TExtra,
232 MachineBasicBlock &FBB,
233 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000234 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000235 return TCycle > 0 && FCycle > 0 &&
236 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000237 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000238 }
239
Evan Chengbe9859e2007-06-07 02:12:15 +0000240 // blockAlwaysFallThrough - Block ends without a terminator.
241 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000242 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000243 }
244
Evan Cheng3a51c852007-06-16 09:34:52 +0000245 // IfcvtTokenCmp - Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000246 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
247 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000248 int Incr1 = (C1->Kind == ICDiamond)
249 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
250 int Incr2 = (C2->Kind == ICDiamond)
251 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
252 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000253 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000254 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000255 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000256 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000257 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000258 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000259 // Favors diamond over triangle, etc.
260 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
261 return true;
262 else if (C1->Kind == C2->Kind)
263 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
264 }
265 }
266 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000267 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000268 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000269
Evan Chengf5e53a52007-05-16 02:00:57 +0000270 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000271}
Evan Chengf5e53a52007-05-16 02:00:57 +0000272
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000273char &llvm::IfConverterID = IfConverter::ID;
274
Owen Anderson8ac477f2010-10-12 19:48:12 +0000275INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000276INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000277INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000278
Evan Chengf5e53a52007-05-16 02:00:57 +0000279bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Akira Hatanaka4a616192015-06-08 18:50:43 +0000280 if (PredicateFtor && !PredicateFtor(*MF.getFunction()))
281 return false;
282
Eric Christopher3d4276f2015-01-27 07:31:29 +0000283 const TargetSubtargetInfo &ST = MF.getSubtarget();
284 TLI = ST.getTargetLowering();
285 TII = ST.getInstrInfo();
286 TRI = ST.getRegisterInfo();
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000287 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000288 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000289 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000290 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000291
Evan Chengf5e53a52007-05-16 02:00:57 +0000292 if (!TII) return false;
293
Evan Chengc5adcca2012-06-08 21:53:50 +0000294 PreRegAlloc = MRI->isSSA();
295
296 bool BFChange = false;
297 if (!PreRegAlloc) {
298 // Tail merge tend to expose more if-conversion opportunities.
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000299 BranchFolder BF(true, false, *MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000300 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000301 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000302 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000303
David Greene72e47cd2010-01-04 22:02:01 +0000304 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000305 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000306
307 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000308 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000309 return false;
310 }
David Greene72e47cd2010-01-04 22:02:01 +0000311 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000312
Evan Chengf5e53a52007-05-16 02:00:57 +0000313 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000314 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000315
Justin Lebar3a7bc572016-02-22 17:51:28 +0000316 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000317 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000318 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
319 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
320 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000321 // Do an initial analysis for each basic block and find all the potential
322 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000323 bool Change = false;
324 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000325 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000326 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000327 Tokens.pop_back();
328 BBInfo &BBI = Token->BBI;
329 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000330 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000331 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000332
Evan Cheng4dd31a72007-06-11 22:26:22 +0000333 // If the block has been evicted out of the queue or it has already been
334 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000335 if (BBI.IsDone)
336 BBI.IsEnqueued = false;
337 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000338 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000339
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000340 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000341
Evan Cheng312b7232007-06-04 06:47:22 +0000342 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000343 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000344 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000345 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000346 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000347 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000348 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000349 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
350 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000351 << "): BB#" << BBI.BB->getNumber() << " ("
352 << ((Kind == ICSimpleFalse)
353 ? BBI.FalseBB->getNumber()
354 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000355 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000356 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000357 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000358 if (isFalse) ++NumSimpleFalse;
359 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000360 }
Evan Cheng312b7232007-06-04 06:47:22 +0000361 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000362 }
Evan Chengd0e66912007-05-23 07:23:16 +0000363 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000364 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000365 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000366 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000367 bool isFalse = Kind == ICTriangleFalse;
368 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000369 if (DisableTriangle && !isFalse && !isRev) break;
370 if (DisableTriangleR && !isFalse && isRev) break;
371 if (DisableTriangleF && isFalse && !isRev) break;
372 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000373 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000374 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000375 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000376 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000377 DEBUG(dbgs() << " rev");
378 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000379 << BBI.TrueBB->getNumber() << ",F:"
380 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000381 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000382 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000383 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000384 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000385 if (isRev) ++NumTriangleFRev;
386 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000387 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000388 if (isRev) ++NumTriangleRev;
389 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000390 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000391 }
Evan Chengd0e66912007-05-23 07:23:16 +0000392 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000393 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000394 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000395 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000396 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000397 << BBI.TrueBB->getNumber() << ",F:"
398 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000399 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000400 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000401 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000402 break;
403 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000404 }
405
Evan Cheng312b7232007-06-04 06:47:22 +0000406 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000407
Evan Cheng92fb5452007-06-15 07:36:12 +0000408 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
409 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
410 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000411 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000412 }
Evan Chengd0e66912007-05-23 07:23:16 +0000413
Evan Chengd0e66912007-05-23 07:23:16 +0000414 if (!Change)
415 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000416 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000417 }
Evan Cheng478b8052007-05-18 01:55:58 +0000418
Evan Cheng3a51c852007-06-16 09:34:52 +0000419 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000420 BBAnalysis.clear();
421
Evan Chengcf9e8a92010-06-18 22:17:13 +0000422 if (MadeChange && IfCvtBranchFold) {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000423 BranchFolder BF(false, false, *MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000424 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000425 getAnalysisIfAvailable<MachineModuleInfo>());
426 }
427
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000428 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000429 return MadeChange;
430}
431
Evan Cheng3a51c852007-06-16 09:34:52 +0000432/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
433/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000434static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000435 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000436 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
437 E = BB->succ_end(); SI != E; ++SI) {
438 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000439 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000440 return SuccBB;
441 }
Craig Topperc0196b12014-04-14 00:51:57 +0000442 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000443}
444
Evan Cheng3a51c852007-06-16 09:34:52 +0000445/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000446/// branch. Swap block's 'true' and 'false' successors.
Evan Cheng312b7232007-06-04 06:47:22 +0000447bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000448 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000449 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
450 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000451 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000452 std::swap(BBI.TrueBB, BBI.FalseBB);
453 return true;
454 }
455 return false;
456}
457
Evan Cheng2117d1f2007-06-09 01:03:43 +0000458/// getNextBlock - Returns the next block in the function blocks ordering. If
459/// it is the end, returns NULL.
460static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000461 MachineFunction::iterator I = BB->getIterator();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000462 MachineFunction::iterator E = BB->getParent()->end();
463 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000464 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000465 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000466}
467
Evan Cheng7783f822007-06-08 09:36:04 +0000468/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000469/// predecessor) forms a valid simple shape for ifcvt. It also returns the
470/// number of instructions that the ifcvt would need to duplicate if performed
471/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000472bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000473 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000474 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000475 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000476 return false;
477
Evan Chenga955c022007-06-19 21:45:13 +0000478 if (TrueBBI.IsBrAnalyzable)
479 return false;
480
Evan Cheng23402fc2007-06-15 21:18:05 +0000481 if (TrueBBI.BB->pred_size() > 1) {
482 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000483 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000484 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000485 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000486 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000487 }
488
Evan Chenga955c022007-06-19 21:45:13 +0000489 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000490}
491
Evan Cheng7783f822007-06-08 09:36:04 +0000492/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000493/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000494/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000495/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000496/// returns the number of instructions that the ifcvt would need to duplicate
497/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000498bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000499 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000500 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000501 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000502 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000503 return false;
504
Evan Cheng23402fc2007-06-15 21:18:05 +0000505 if (TrueBBI.BB->pred_size() > 1) {
506 if (TrueBBI.CannotBeCopied)
507 return false;
508
Evan Cheng92fb5452007-06-15 07:36:12 +0000509 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000510 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000511 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000512 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000513 --Size;
514 else {
515 MachineBasicBlock *FExit = FalseBranch
516 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
517 if (FExit)
518 // Require a conditional branch
519 ++Size;
520 }
521 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000522 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000523 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000524 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000525 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000526
Evan Cheng7783f822007-06-08 09:36:04 +0000527 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
528 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000529 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000530 if (++I == TrueBBI.BB->getParent()->end())
531 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000532 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000533 }
Evan Cheng7783f822007-06-08 09:36:04 +0000534 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000535}
536
Evan Cheng7783f822007-06-08 09:36:04 +0000537/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000538/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000539bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
540 unsigned &Dups1, unsigned &Dups2) const {
541 Dups1 = Dups2 = 0;
542 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
543 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000544 return false;
545
Evan Cheng2117d1f2007-06-09 01:03:43 +0000546 MachineBasicBlock *TT = TrueBBI.TrueBB;
547 MachineBasicBlock *FT = FalseBBI.TrueBB;
548
549 if (!TT && blockAlwaysFallThrough(TrueBBI))
550 TT = getNextBlock(TrueBBI.BB);
551 if (!FT && blockAlwaysFallThrough(FalseBBI))
552 FT = getNextBlock(FalseBBI.BB);
553 if (TT != FT)
554 return false;
Craig Topperc0196b12014-04-14 00:51:57 +0000555 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng2117d1f2007-06-09 01:03:43 +0000556 return false;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000557 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
558 return false;
559
560 // FIXME: Allow true block to have an early exit?
561 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
562 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000563 return false;
564
Bob Wilsone1961fe2010-10-26 00:02:24 +0000565 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach6201b992010-06-07 21:28:55 +0000566 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
567 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilsone1961fe2010-10-26 00:02:24 +0000568 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
569 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
570 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000571 // Skip dbg_value instructions. These do not count.
Bob Wilsone1961fe2010-10-26 00:02:24 +0000572 if (TIB->isDebugValue()) {
573 while (TIB != TIE && TIB->isDebugValue())
574 ++TIB;
575 if (TIB == TIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000576 break;
577 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000578 if (FIB->isDebugValue()) {
579 while (FIB != FIE && FIB->isDebugValue())
580 ++FIB;
581 if (FIB == FIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000582 break;
583 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000584 if (!TIB->isIdenticalTo(FIB))
585 break;
586 ++Dups1;
587 ++TIB;
588 ++FIB;
589 }
590
591 // Now, in preparation for counting duplicate instructions at the ends of the
592 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000593 // If both blocks are returning don't skip the branches, since they will
594 // likely be both identical return instructions. In such cases the return
595 // can be left unpredicated.
596 // Check for already containing all of the block.
597 if (TIB == TIE || FIB == FIE)
598 return true;
599 --TIE;
600 --FIE;
601 if (!TrueBBI.BB->succ_empty() || !FalseBBI.BB->succ_empty()) {
602 while (TIE != TIB && TIE->isBranch())
603 --TIE;
604 while (FIE != FIB && FIE->isBranch())
605 --FIE;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000606 }
607
608 // If Dups1 includes all of a block, then don't count duplicate
609 // instructions at the end of the blocks.
610 if (TIB == TIE || FIB == FIE)
611 return true;
612
613 // Count duplicate instructions at the ends of the blocks.
614 while (TIE != TIB && FIE != FIB) {
615 // Skip dbg_value instructions. These do not count.
616 if (TIE->isDebugValue()) {
617 while (TIE != TIB && TIE->isDebugValue())
618 --TIE;
619 if (TIE == TIB)
620 break;
621 }
622 if (FIE->isDebugValue()) {
623 while (FIE != FIB && FIE->isDebugValue())
624 --FIE;
625 if (FIE == FIB)
626 break;
627 }
628 if (!TIE->isIdenticalTo(FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000629 break;
630 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000631 --TIE;
632 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000633 }
634
635 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000636}
637
Evan Cheng4dd31a72007-06-11 22:26:22 +0000638/// ScanInstructions - Scan all the instructions in the block to determine if
639/// the block is predicable. In most cases, that means all the instructions
Chris Lattnera98c6792008-01-07 01:56:04 +0000640/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng4dd31a72007-06-11 22:26:22 +0000641/// instruction which can clobber a predicate (e.g. condition code register).
642/// If so, the block is not predicable unless it's the last instruction.
643void IfConverter::ScanInstructions(BBInfo &BBI) {
644 if (BBI.IsDone)
645 return;
646
Evan Chengc5adcca2012-06-08 21:53:50 +0000647 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000648 // First analyze the end of BB branches.
Craig Topperc0196b12014-04-14 00:51:57 +0000649 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000650 BBI.BrCond.clear();
651 BBI.IsBrAnalyzable =
652 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000653 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000654
655 if (BBI.BrCond.size()) {
656 // No false branch. This BB must end with a conditional branch and a
657 // fallthrough.
658 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000659 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000660 if (!BBI.FalseBB) {
661 // Malformed bcc? True and false blocks are the same?
662 BBI.IsUnpredicable = true;
663 return;
664 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000665 }
666
667 // Then scan all the instructions.
668 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000669 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000670 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000671 BBI.ClobbersPred = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000672 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
673 I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000674 if (I->isDebugValue())
675 continue;
676
Justin Lebarf62b1652016-02-22 17:51:30 +0000677 // Don't need to check isConvergent(). It's OK to duplicate convergent
678 // instructions here, because we'll only push convergent operations up the
679 // CFG -- this can only *remove* control-flow dependencies.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000680 if (I->isNotDuplicable())
Evan Cheng23402fc2007-06-15 21:18:05 +0000681 BBI.CannotBeCopied = true;
682
Evan Cheng4dd31a72007-06-11 22:26:22 +0000683 bool isPredicated = TII->isPredicated(I);
Evan Cheng7f8e5632011-12-07 07:15:52 +0000684 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000685
Joey Goulya5153cb2013-09-09 14:21:49 +0000686 // A conditional branch is not predicable, but it may be eliminated.
687 if (isCondBr)
688 continue;
689
690 if (!isPredicated) {
691 BBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000692 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
693 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000694 if (NumCycles > 1)
695 BBI.ExtraCost += NumCycles-1;
696 BBI.ExtraCost2 += ExtraPredCost;
697 } else if (!AlreadyPredicated) {
698 // FIXME: This instruction is already predicated before the
699 // if-conversion pass. It's probably something like a conditional move.
700 // Mark this block unpredicable for now.
701 BBI.IsUnpredicable = true;
702 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000703 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000704
705 if (BBI.ClobbersPred && !isPredicated) {
706 // Predicate modification instruction should end the block (except for
707 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000708 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000709 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000710 BBI.IsUnpredicable = true;
711 return;
712 }
713
Evan Chengfbc73092007-07-10 17:50:43 +0000714 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
715 // still potentially predicable.
716 std::vector<MachineOperand> PredDefs;
717 if (TII->DefinesPredicate(I, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000718 BBI.ClobbersPred = true;
719
Evan Cheng1f4062f2009-11-21 06:20:26 +0000720 if (!TII->isPredicable(I)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000721 BBI.IsUnpredicable = true;
722 return;
723 }
724 }
725}
726
727/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
728/// predicated by the specified predicate.
729bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000730 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng4dd31a72007-06-11 22:26:22 +0000731 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000732 // If the block is dead or unpredicable, then it cannot be predicated.
733 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000734 return false;
735
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000736 // If it is already predicated but we couldn't analyze its terminator, the
737 // latter might fallthrough, but we can't determine where to.
738 // Conservatively avoid if-converting again.
739 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
740 return false;
741
Quentin Colombetbdab2272013-07-24 20:20:37 +0000742 // If it is already predicated, check if the new predicate subsumes
743 // its predicate.
744 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000745 return false;
746
747 if (BBI.BrCond.size()) {
748 if (!isTriangle)
749 return false;
750
Bob Wilson2371f4f2009-05-13 23:25:24 +0000751 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000752 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
753 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000754 if (RevBranch) {
755 if (TII->ReverseBranchCondition(Cond))
756 return false;
757 }
758 if (TII->ReverseBranchCondition(RevPred) ||
759 !TII->SubsumesPredicate(Cond, RevPred))
760 return false;
761 }
762
763 return true;
764}
765
Evan Cheng7783f822007-06-08 09:36:04 +0000766/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +0000767/// the specified block. Record its successors and whether it looks like an
768/// if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000769void IfConverter::AnalyzeBlock(
770 MachineBasicBlock *MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000771 struct BBState {
772 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
773 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000774
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000775 /// This flag is true if MBB's successors have been analyzed.
776 bool SuccsAnalyzed;
777 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000778
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000779 // Push MBB to the stack.
780 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000781
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000782 while (!BBStack.empty()) {
783 BBState &State = BBStack.back();
784 MachineBasicBlock *BB = State.MBB;
785 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000786
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000787 if (!State.SuccsAnalyzed) {
788 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
789 BBStack.pop_back();
790 continue;
791 }
Evan Cheng9030b982007-06-06 10:16:17 +0000792
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000793 BBI.BB = BB;
794 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000795
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000796 ScanInstructions(BBI);
Evan Chengb9bff582009-06-15 21:24:34 +0000797
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000798 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
799 // not considered for ifcvt anymore.
800 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
801 BBI.IsBeingAnalyzed = false;
802 BBI.IsAnalyzed = true;
803 BBStack.pop_back();
804 continue;
805 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000806
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000807 // Do not ifcvt if either path is a back edge to the entry block.
808 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
809 BBI.IsBeingAnalyzed = false;
810 BBI.IsAnalyzed = true;
811 BBStack.pop_back();
812 continue;
813 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000814
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000815 // Do not ifcvt if true and false fallthrough blocks are the same.
816 if (!BBI.FalseBB) {
817 BBI.IsBeingAnalyzed = false;
818 BBI.IsAnalyzed = true;
819 BBStack.pop_back();
820 continue;
821 }
Evan Cheng7783f822007-06-08 09:36:04 +0000822
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000823 // Push the False and True blocks to the stack.
824 State.SuccsAnalyzed = true;
825 BBStack.push_back(BBI.FalseBB);
826 BBStack.push_back(BBI.TrueBB);
827 continue;
828 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000829
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000830 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
831 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +0000832
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000833 if (TrueBBI.IsDone && FalseBBI.IsDone) {
834 BBI.IsBeingAnalyzed = false;
835 BBI.IsAnalyzed = true;
836 BBStack.pop_back();
837 continue;
838 }
839
840 SmallVector<MachineOperand, 4>
841 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
842 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
843
844 unsigned Dups = 0;
845 unsigned Dups2 = 0;
846 bool TNeedSub = !TrueBBI.Predicate.empty();
847 bool FNeedSub = !FalseBBI.Predicate.empty();
848 bool Enqueued = false;
849
850 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
851
852 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
853 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
854 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
855 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000856 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000857 Prediction) &&
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000858 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
859 FeasibilityAnalysis(FalseBBI, RevCond)) {
860 // Diamond:
861 // EBB
862 // / \_
863 // | |
864 // TBB FBB
865 // \ /
866 // TailBB
867 // Note TailBB can be empty.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000868 Tokens.push_back(llvm::make_unique<IfcvtToken>(
869 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
Evan Cheng3a51c852007-06-16 09:34:52 +0000870 Enqueued = true;
871 }
872
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000873 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
874 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
875 TrueBBI.ExtraCost2, Prediction) &&
876 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
877 // Triangle:
878 // EBB
879 // | \_
880 // | |
881 // | TBB
882 // | /
883 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000884 Tokens.push_back(
885 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000886 Enqueued = true;
887 }
888
889 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
890 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
891 TrueBBI.ExtraCost2, Prediction) &&
892 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000893 Tokens.push_back(
894 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000895 Enqueued = true;
896 }
897
898 if (ValidSimple(TrueBBI, Dups, Prediction) &&
899 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
900 TrueBBI.ExtraCost2, Prediction) &&
901 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
902 // Simple (split, no rejoin):
903 // EBB
904 // | \_
905 // | |
906 // | TBB---> exit
907 // |
908 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000909 Tokens.push_back(
910 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000911 Enqueued = true;
912 }
913
914 if (CanRevCond) {
915 // Try the other path...
916 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
917 Prediction.getCompl()) &&
918 MeetIfcvtSizeLimit(*FalseBBI.BB,
919 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
920 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
921 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000922 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
923 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000924 Enqueued = true;
925 }
926
927 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
928 Prediction.getCompl()) &&
929 MeetIfcvtSizeLimit(*FalseBBI.BB,
930 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000931 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000932 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000933 Tokens.push_back(
934 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000935 Enqueued = true;
936 }
937
938 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
939 MeetIfcvtSizeLimit(*FalseBBI.BB,
940 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
941 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
942 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000943 Tokens.push_back(
944 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000945 Enqueued = true;
946 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000947 }
948
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000949 BBI.IsEnqueued = Enqueued;
950 BBI.IsBeingAnalyzed = false;
951 BBI.IsAnalyzed = true;
952 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +0000953 }
Evan Cheng2e82cef2007-05-18 18:14:37 +0000954}
955
Evan Cheng905a8f42007-05-30 19:49:19 +0000956/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000957/// candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000958void IfConverter::AnalyzeBlocks(
959 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000960 for (auto &BB : MF)
961 AnalyzeBlock(&BB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +0000962
Evan Cheng20e05992007-06-01 00:12:12 +0000963 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +0000964 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +0000965}
966
Evan Cheng288f1542007-06-08 22:01:07 +0000967/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
968/// that all the intervening blocks are empty (given BB can fall through to its
969/// next block).
970static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000971 MachineFunction::iterator PI = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000972 MachineFunction::iterator I = std::next(PI);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000973 MachineFunction::iterator TI = ToBB->getIterator();
Evan Cheng2c1acd62007-06-05 07:05:25 +0000974 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +0000975 while (I != TI) {
976 // Check isSuccessor to avoid case where the next block is empty, but
977 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000978 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +0000979 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +0000980 PI = I++;
981 }
Evan Cheng312b7232007-06-04 06:47:22 +0000982 return true;
Evan Chenge26c0912007-05-21 22:22:58 +0000983}
984
Evan Cheng51eb2c32007-06-18 08:37:25 +0000985/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
986/// to determine if it can be if-converted. If predecessor is already enqueued,
987/// dequeue it!
988void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +0000989 for (const auto &Predecessor : BB->predecessors()) {
990 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +0000991 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +0000992 continue;
Evan Chengadd97762007-06-14 23:34:09 +0000993 PBBI.IsAnalyzed = false;
994 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +0000995 }
996}
997
Evan Chengc2237ce2007-05-29 22:31:16 +0000998/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
999///
1000static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
1001 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001002 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001003 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +00001004 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001005}
1006
Evan Cheng288f1542007-06-08 22:01:07 +00001007/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1008/// successors.
1009void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001010 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001011 SmallVector<MachineOperand, 4> Cond;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001012 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
1013 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001014}
1015
Matthias Braund616ccc2013-10-11 19:04:37 +00001016/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1017/// values defined in MI which are not live/used by MI.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001018static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) {
Pete Cooper7605e372015-05-05 20:14:22 +00001019 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
1020 Redefs.stepForward(*MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001021
Pete Cooper7605e372015-05-05 20:14:22 +00001022 // Now add the implicit uses for each of the clobbered values.
1023 for (auto Reg : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001024 // FIXME: Const cast here is nasty, but better than making StepForward
1025 // take a mutable instruction instead of const.
Pete Cooper27483912015-05-06 22:51:04 +00001026 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1027 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001028 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001029 if (Op.isRegMask()) {
1030 // First handle regmasks. They clobber any entries in the mask which
1031 // means that we need a def for those registers.
Pete Cooper7605e372015-05-05 20:14:22 +00001032 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Pete Cooperce9ad752015-05-05 22:09:41 +00001033
1034 // We also need to add an implicit def of this register for the later
1035 // use to read from.
1036 // For the register allocator to have allocated a register clobbered
1037 // by the call which is used later, it must be the case that
1038 // the call doesn't return.
1039 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1040 continue;
1041 }
1042 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001043 if (Op.isDead()) {
1044 // If we found a dead def, but it needs to be live, then remove the dead
1045 // flag.
1046 if (Redefs.contains(Op.getReg()))
1047 Op.setIsDead(false);
1048 }
Pete Cooperce9ad752015-05-05 22:09:41 +00001049 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Matthias Braund616ccc2013-10-11 19:04:37 +00001050 }
1051}
1052
1053/**
1054 * Remove kill flags from operands with a registers in the @p DontKill set.
1055 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001056static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001057 for (MIBundleOperands O(&MI); O.isValid(); ++O) {
1058 if (!O->isReg() || !O->isKill())
1059 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001060 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001061 O->setIsKill(false);
1062 }
1063}
1064
1065/**
1066 * Walks a range of machine instructions and removes kill flags for registers
1067 * in the @p DontKill set.
1068 */
1069static void RemoveKills(MachineBasicBlock::iterator I,
1070 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001071 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001072 const MCRegisterInfo &MCRI) {
1073 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001074 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001075}
1076
Evan Cheng312b7232007-06-04 06:47:22 +00001077/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001078///
Evan Cheng3a51c852007-06-16 09:34:52 +00001079bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001080 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1081 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1082 BBInfo *CvtBBI = &TrueBBI;
1083 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001084
Owen Anderson4f6bf042008-08-14 22:49:33 +00001085 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001086 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001087 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001088
Evan Cheng51eb2c32007-06-18 08:37:25 +00001089 if (CvtBBI->IsDone ||
1090 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001091 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001092 BBI.IsAnalyzed = false;
1093 CvtBBI->IsAnalyzed = false;
1094 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001095 }
Evan Chengd0e66912007-05-23 07:23:16 +00001096
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001097 if (CvtBBI->BB->hasAddressTaken())
1098 // Conservatively abort if-conversion if BB's address is taken.
1099 return false;
1100
Evan Cheng3a51c852007-06-16 09:34:52 +00001101 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001102 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001103 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001104
Bob Wilson45814342010-06-19 05:33:57 +00001105 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001106 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001107 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001108 Redefs.addLiveIns(CvtBBI->BB);
1109 Redefs.addLiveIns(NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001110
1111 // Compute a set of registers which must not be killed by instructions in
1112 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001113 DontKill.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001114 DontKill.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001115
Evan Cheng92fb5452007-06-15 07:36:12 +00001116 if (CvtBBI->BB->pred_size() > 1) {
1117 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001118 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001119 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001120 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001121
1122 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1123 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001124 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001125 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001126 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001127 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001128
Evan Cheng92fb5452007-06-15 07:36:12 +00001129 // Merge converted block into entry block.
1130 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1131 MergeBlocks(BBI, *CvtBBI);
1132 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001133
Evan Chenge4ec9182007-06-06 02:08:52 +00001134 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001135 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001136 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001137 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001138 // Now ifcvt'd block will look like this:
1139 // BB:
1140 // ...
1141 // t, f = cmp
1142 // if t op
1143 // b BBf
1144 //
1145 // We cannot further ifcvt this block because the unconditional branch
1146 // will have to be predicated on the new condition, that will not be
1147 // available if cmp executes.
1148 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001149 }
Evan Chenge26c0912007-05-21 22:22:58 +00001150
Evan Cheng288f1542007-06-08 22:01:07 +00001151 RemoveExtraEdges(BBI);
1152
Evan Chengd0e66912007-05-23 07:23:16 +00001153 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001154 if (!IterIfcvt)
1155 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001156 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001157 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001158
1159 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001160 return true;
1161}
1162
Evan Chengaf716102007-05-16 21:54:37 +00001163/// IfConvertTriangle - If convert a triangle sub-CFG.
1164///
Evan Cheng3a51c852007-06-16 09:34:52 +00001165bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001166 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001167 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1168 BBInfo *CvtBBI = &TrueBBI;
1169 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001170 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001171
Owen Anderson4f6bf042008-08-14 22:49:33 +00001172 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001173 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001174 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001175
Evan Cheng51eb2c32007-06-18 08:37:25 +00001176 if (CvtBBI->IsDone ||
1177 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001178 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001179 BBI.IsAnalyzed = false;
1180 CvtBBI->IsAnalyzed = false;
1181 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001182 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001183
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001184 if (CvtBBI->BB->hasAddressTaken())
1185 // Conservatively abort if-conversion if BB's address is taken.
1186 return false;
1187
Evan Cheng3a51c852007-06-16 09:34:52 +00001188 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001189 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001190 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001191
Evan Cheng3a51c852007-06-16 09:34:52 +00001192 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001193 if (ReverseBranchCondition(*CvtBBI)) {
1194 // BB has been changed, modify its predecessors (except for this
1195 // one) so they don't get ifcvt'ed based on bad intel.
1196 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1197 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1198 MachineBasicBlock *PBB = *PI;
1199 if (PBB == BBI.BB)
1200 continue;
1201 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1202 if (PBBI.IsEnqueued) {
1203 PBBI.IsAnalyzed = false;
1204 PBBI.IsEnqueued = false;
1205 }
Evan Chengadd97762007-06-14 23:34:09 +00001206 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001207 }
1208 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001209
Bob Wilson45814342010-06-19 05:33:57 +00001210 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001211 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001212 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001213 Redefs.addLiveIns(CvtBBI->BB);
1214 Redefs.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001215
Andrew Trick276dd452013-10-14 20:45:17 +00001216 DontKill.clear();
1217
Craig Topperc0196b12014-04-14 00:51:57 +00001218 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001219 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001220
Manman Renb6819182014-01-29 23:18:47 +00001221 if (HasEarlyExit) {
Cong Houd97c1002015-12-01 05:29:22 +00001222 // Get probabilities before modifying CvtBBI->BB and BBI.BB.
1223 CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB);
1224 CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB);
1225 BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB);
1226 BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001227 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001228
Bob Wilson1e5da552010-06-29 00:55:23 +00001229 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001230 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001231 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001232 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001233 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001234
1235 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1236 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001237 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001238 } else {
1239 // Predicate the 'true' block after removing its branch.
1240 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001241 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001242
Evan Cheng0598b2d2007-06-18 22:44:57 +00001243 // Now merge the entry of the triangle with the true block.
1244 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001245 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001246 }
1247
Evan Cheng312b7232007-06-04 06:47:22 +00001248 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001249 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001250 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1251 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001252 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001253 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001254
Cong Houd97c1002015-12-01 05:29:22 +00001255 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1256 // NewNext = New_Prob(BBI.BB, NextBBI->BB) =
1257 // Prob(BBI.BB, NextBBI->BB) +
1258 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB)
1259 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1260 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB)
1261 auto NewTrueBB = getNextBlock(BBI.BB);
1262 auto NewNext = BBNext + BBCvt * CvtNext;
1263 auto NewTrueBBIter =
1264 std::find(BBI.BB->succ_begin(), BBI.BB->succ_end(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001265 if (NewTrueBBIter != BBI.BB->succ_end())
1266 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001267
1268 auto NewFalse = BBCvt * CvtFalse;
1269 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1270 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001271 }
Evan Cheng7783f822007-06-08 09:36:04 +00001272
1273 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001274 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001275 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001276 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001277 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001278 if (!isFallThrough) {
1279 // Only merge them if the true block does not fallthrough to the false
1280 // block. By not merging them, we make it possible to iteratively
1281 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001282 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001283 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1284 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001285 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001286 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001287 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001288 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1289 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001290 }
Evan Cheng7783f822007-06-08 09:36:04 +00001291 // Mixed predicated and unpredicated code. This cannot be iteratively
1292 // predicated.
1293 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001294 }
Evan Chenge26c0912007-05-21 22:22:58 +00001295
Evan Cheng288f1542007-06-08 22:01:07 +00001296 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001297
Evan Chengd0e66912007-05-23 07:23:16 +00001298 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001299 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001300 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001301 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001302 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001303 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001304 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001305
1306 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001307 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001308}
1309
Evan Chengaf716102007-05-16 21:54:37 +00001310/// IfConvertDiamond - If convert a diamond sub-CFG.
1311///
Evan Cheng51eb2c32007-06-18 08:37:25 +00001312bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1313 unsigned NumDups1, unsigned NumDups2) {
Evan Cheng312b7232007-06-04 06:47:22 +00001314 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2e82cef2007-05-18 18:14:37 +00001315 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng3a51c852007-06-16 09:34:52 +00001316 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson2371f4f2009-05-13 23:25:24 +00001317 // True block must fall through or end with an unanalyzable terminator.
Evan Cheng3a51c852007-06-16 09:34:52 +00001318 if (!TailBB) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001319 if (blockAlwaysFallThrough(TrueBBI))
1320 TailBB = FalseBBI.TrueBB;
1321 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Chengf5e53a52007-05-16 02:00:57 +00001322 }
Evan Chenge26c0912007-05-21 22:22:58 +00001323
Evan Cheng51eb2c32007-06-18 08:37:25 +00001324 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1325 TrueBBI.BB->pred_size() > 1 ||
1326 FalseBBI.BB->pred_size() > 1) {
1327 // Something has changed. It's no longer safe to predicate these blocks.
1328 BBI.IsAnalyzed = false;
1329 TrueBBI.IsAnalyzed = false;
1330 FalseBBI.IsAnalyzed = false;
1331 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001332 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001333
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001334 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1335 // Conservatively abort if-conversion if either BB has its address taken.
1336 return false;
1337
Bob Wilson1e5da552010-06-29 00:55:23 +00001338 // Put the predicated instructions from the 'true' block before the
1339 // instructions from the 'false' block, unless the true block would clobber
1340 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001341 BBInfo *BBI1 = &TrueBBI;
1342 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001343 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001344 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001345 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001346 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1347 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001348
Evan Cheng3a51c852007-06-16 09:34:52 +00001349 // Figure out the more profitable ordering.
1350 bool DoSwap = false;
1351 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1352 DoSwap = true;
1353 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001354 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001355 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001356 }
1357 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001358 std::swap(BBI1, BBI2);
1359 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001360 }
Evan Cheng79484222007-06-05 23:46:14 +00001361
Evan Cheng51eb2c32007-06-18 08:37:25 +00001362 // Remove the conditional branch from entry to the blocks.
1363 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1364
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001365 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001366 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001367 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001368 Redefs.addLiveIns(BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001369
Evan Cheng51eb2c32007-06-18 08:37:25 +00001370 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001371 // Skip dbg_value instructions
Benjamin Kramer6b568962015-06-23 14:47:29 +00001372 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1373 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001374 BBI1->NonPredSize -= NumDups1;
1375 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001376
1377 // Skip past the dups on each side separately since there may be
1378 // differing dbg_value entries.
1379 for (unsigned i = 0; i < NumDups1; ++DI1) {
1380 if (!DI1->isDebugValue())
1381 ++i;
1382 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001383 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001384 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001385 if (!DI2->isDebugValue())
1386 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001387 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001388
Matthias Braund616ccc2013-10-11 19:04:37 +00001389 // Compute a set of registers which must not be killed by instructions in BB1:
1390 // This is everything used+live in BB2 after the duplicated instructions. We
1391 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001392 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001393 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1394 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001395 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001396 }
1397
1398 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1399 ++I) {
Pete Cooper7605e372015-05-05 20:14:22 +00001400 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1401 Redefs.stepForward(*I, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001402 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001403 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1404 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1405
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001406 // Remove branch from the 'true' block, unless it was not analyzable.
1407 // Non-analyzable branches need to be preserved, since in such cases,
1408 // the CFG structure is not an actual diamond (the join block may not
1409 // be present).
1410 if (BBI1->IsBrAnalyzable)
1411 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1412 // Remove duplicated instructions.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001413 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001414 for (unsigned i = 0; i != NumDups2; ) {
1415 // NumDups2 only counted non-dbg_value instructions, so this won't
1416 // run off the head of the list.
1417 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001418 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001419 // skip dbg_value instructions
1420 if (!DI1->isDebugValue())
1421 ++i;
1422 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001423 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001424
Matthias Braund616ccc2013-10-11 19:04:37 +00001425 // Kill flags in the true block for registers living into the false block
1426 // must be removed.
1427 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1428
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001429 // Remove 'false' block branch (unless it was not analyzable), and find
1430 // the last instruction to predicate.
1431 if (BBI2->IsBrAnalyzable)
1432 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001433 DI2 = BBI2->BB->end();
1434 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001435 // NumDups2 only counted non-dbg_value instructions, so this won't
1436 // run off the head of the list.
1437 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001438 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001439 // skip dbg_value instructions
1440 if (!DI2->isDebugValue())
1441 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001442 }
Evan Cheng4266a792011-12-19 22:01:30 +00001443
1444 // Remember which registers would later be defined by the false block.
1445 // This allows us not to predicate instructions in the true block that would
1446 // later be re-defined. That is, rather than
1447 // subeq r0, r1, #1
1448 // addne r0, r1, #1
1449 // generate:
1450 // sub r0, r1, #1
1451 // addne r0, r1, #1
1452 SmallSet<unsigned, 4> RedefsByFalse;
1453 SmallSet<unsigned, 4> ExtUses;
1454 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1455 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1456 if (FI->isDebugValue())
1457 continue;
1458 SmallVector<unsigned, 4> Defs;
1459 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1460 const MachineOperand &MO = FI->getOperand(i);
1461 if (!MO.isReg())
1462 continue;
1463 unsigned Reg = MO.getReg();
1464 if (!Reg)
1465 continue;
1466 if (MO.isDef()) {
1467 Defs.push_back(Reg);
1468 } else if (!RedefsByFalse.count(Reg)) {
1469 // These are defined before ctrl flow reach the 'false' instructions.
1470 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001471 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1472 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001473 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001474 }
1475 }
1476
1477 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1478 unsigned Reg = Defs[i];
1479 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001480 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1481 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001482 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001483 }
1484 }
1485 }
1486 }
1487
1488 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001489 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001490
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001491 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1492 // a non-predicated in BBI2, then we don't want to predicate the one from
1493 // BBI2. The reason is that if we merged these blocks, we would end up with
1494 // two predicated terminators in the same block.
1495 if (!BBI2->BB->empty() && (DI2 == BBI2->BB->end())) {
1496 MachineBasicBlock::iterator BBI1T = BBI1->BB->getFirstTerminator();
1497 MachineBasicBlock::iterator BBI2T = BBI2->BB->getFirstTerminator();
1498 if ((BBI1T != BBI1->BB->end()) && TII->isPredicated(BBI1T) &&
1499 ((BBI2T != BBI2->BB->end()) && !TII->isPredicated(BBI2T)))
1500 --DI2;
1501 }
1502
Evan Cheng4266a792011-12-19 22:01:30 +00001503 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001504 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001505
Evan Cheng0598b2d2007-06-18 22:44:57 +00001506 // Merge the true block into the entry of the diamond.
Craig Topperc0196b12014-04-14 00:51:57 +00001507 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1508 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001509
Bob Wilson2371f4f2009-05-13 23:25:24 +00001510 // If the if-converted block falls through or unconditionally branches into
1511 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001512 // fold the tail block in as well. Otherwise, unless it falls through to the
1513 // tail, add a unconditional branch to it.
1514 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001515 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001516 bool CanMergeTail = !TailBBI.HasFallThrough &&
1517 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001518 // The if-converted block can still have a predicated terminator
1519 // (e.g. a predicated return). If that is the case, we cannot merge
1520 // it with the tail block.
1521 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
1522 if (TI != BBI.BB->end() && TII->isPredicated(TI))
1523 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001524 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1525 // check if there are any other predecessors besides those.
1526 unsigned NumPreds = TailBB->pred_size();
1527 if (NumPreds > 1)
1528 CanMergeTail = false;
1529 else if (NumPreds == 1 && CanMergeTail) {
1530 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1531 if (*PI != BBI1->BB && *PI != BBI2->BB)
1532 CanMergeTail = false;
1533 }
1534 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001535 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001536 TailBBI.IsDone = true;
1537 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001538 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Evan Cheng0598b2d2007-06-18 22:44:57 +00001539 InsertUncondBranch(BBI.BB, TailBB, TII);
1540 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001541 }
Evan Chenge26c0912007-05-21 22:22:58 +00001542 }
1543
Bob Wilson1e5da552010-06-29 00:55:23 +00001544 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1545 // which can happen here if TailBB is unanalyzable and is merged, so
1546 // explicitly remove BBI1 and BBI2 as successors.
1547 BBI.BB->removeSuccessor(BBI1->BB);
Cong Houc1069892015-12-13 09:26:17 +00001548 BBI.BB->removeSuccessor(BBI2->BB, true);
Evan Cheng288f1542007-06-08 22:01:07 +00001549 RemoveExtraEdges(BBI);
1550
Evan Cheng79484222007-06-05 23:46:14 +00001551 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001552 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001553 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001554
1555 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001556 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001557}
1558
Evan Cheng4266a792011-12-19 22:01:30 +00001559static bool MaySpeculate(const MachineInstr *MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001560 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001561 bool SawStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001562 if (!MI->isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001563 return false;
1564
1565 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1566 const MachineOperand &MO = MI->getOperand(i);
1567 if (!MO.isReg())
1568 continue;
1569 unsigned Reg = MO.getReg();
1570 if (!Reg)
1571 continue;
1572 if (MO.isDef() && !LaterRedefs.count(Reg))
1573 return false;
1574 }
1575
1576 return true;
1577}
1578
Evan Cheng51eb2c32007-06-18 08:37:25 +00001579/// PredicateBlock - Predicate instructions from the start of the block to the
1580/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001581void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001582 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001583 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001584 SmallSet<unsigned, 4> *LaterRedefs) {
1585 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001586 bool MaySpec = LaterRedefs != nullptr;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001587 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +00001588 if (I->isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001589 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001590 // It may be possible not to predicate an instruction if it's the 'true'
1591 // side of a diamond and the 'false' side may re-define the instruction's
1592 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001593 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001594 AnyUnpred = true;
1595 continue;
1596 }
1597 // If any instruction is predicated, then every instruction after it must
1598 // be predicated.
1599 MaySpec = false;
Evan Cheng312b7232007-06-04 06:47:22 +00001600 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001601#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001602 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001603#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001604 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001605 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001606
Bob Wilson45814342010-06-19 05:33:57 +00001607 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001608 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001609 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001610 }
Evan Chengd0e66912007-05-23 07:23:16 +00001611
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001612 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001613
Evan Cheng92fb5452007-06-15 07:36:12 +00001614 BBI.IsAnalyzed = false;
1615 BBI.NonPredSize = 0;
1616
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001617 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001618 if (AnyUnpred)
1619 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001620}
1621
Evan Cheng92fb5452007-06-15 07:36:12 +00001622/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1623/// the destination block. Skip end of block branches if IgnoreBr is true.
1624void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001625 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001626 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001627 MachineFunction &MF = *ToBBI.BB->getParent();
1628
Evan Cheng92fb5452007-06-15 07:36:12 +00001629 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1630 E = FromBBI.BB->end(); I != E; ++I) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001631 // Do not copy the end of the block branches.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001632 if (IgnoreBr && I->isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001633 break;
1634
Dan Gohman3b460302008-07-07 23:14:23 +00001635 MachineInstr *MI = MF.CloneMachineInstr(I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001636 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001637 ToBBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +00001638 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
1639 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001640 if (NumCycles > 1)
1641 ToBBI.ExtraCost += NumCycles-1;
1642 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001643
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001644 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001645 if (!TII->PredicateInstruction(MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001646#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001647 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001648#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001649 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001650 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001651 }
1652
Bob Wilson45814342010-06-19 05:33:57 +00001653 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001654 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001655 UpdatePredRedefs(MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001656
1657 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001658 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001659 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001660 }
1661
Bob Wilson1e5da552010-06-29 00:55:23 +00001662 if (!IgnoreBr) {
1663 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1664 FromBBI.BB->succ_end());
1665 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001666 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001667
Bob Wilson1e5da552010-06-29 00:55:23 +00001668 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1669 MachineBasicBlock *Succ = Succs[i];
1670 // Fallthrough edge can't be transferred.
1671 if (Succ == FallThrough)
1672 continue;
1673 ToBBI.BB->addSuccessor(Succ);
1674 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001675 }
1676
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001677 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1678 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001679
1680 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1681 ToBBI.IsAnalyzed = false;
1682
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001683 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001684}
1685
Evan Cheng0f745da2007-05-18 00:20:58 +00001686/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00001687/// This will leave FromBB as an empty block, so remove all of its
1688/// successor edges except for the fall-through edge. If AddEdges is true,
1689/// i.e., when FromBBI's branch is being moved, add those successor edges to
1690/// ToBBI.
1691void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001692 assert(!FromBBI.BB->hasAddressTaken() &&
1693 "Removing a BB whose address is taken!");
1694
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001695 // In case FromBBI.BB contains terminators (e.g. return instruction),
1696 // first move the non-terminator instructions, then the terminators.
1697 MachineBasicBlock::iterator FromTI = FromBBI.BB->getFirstTerminator();
1698 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
1699 ToBBI.BB->splice(ToTI, FromBBI.BB, FromBBI.BB->begin(), FromTI);
1700
1701 // If FromBB has non-predicated terminator we should copy it at the end.
1702 if ((FromTI != FromBBI.BB->end()) && !TII->isPredicated(FromTI))
1703 ToTI = ToBBI.BB->end();
1704 ToBBI.BB->splice(ToTI, FromBBI.BB, FromTI, FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00001705
Cong Houb9e8d482015-12-17 01:29:08 +00001706 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1707 // unknown probabilities into known ones.
1708 // FIXME: This usage is too tricky and in the future we would like to
1709 // eliminate all unknown probabilities in MBB.
1710 ToBBI.BB->normalizeSuccProbs();
1711
Cong Houd40105d2015-09-18 20:22:41 +00001712 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
1713 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00001714 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001715 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001716 // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001717 // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00001718 auto To2FromProb = BranchProbability::getZero();
Cong Houfa1917c2015-12-01 00:02:51 +00001719 if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
Cong Houd97c1002015-12-01 05:29:22 +00001720 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB);
1721 // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the
1722 // edge probability being merged to other edges when this edge is removed
1723 // later.
1724 ToBBI.BB->setSuccProbability(
1725 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB),
1726 BranchProbability::getZero());
1727 }
1728
Cong Houd40105d2015-09-18 20:22:41 +00001729 for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
1730 MachineBasicBlock *Succ = FromSuccs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00001731 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001732 if (Succ == FallThrough)
1733 continue;
Cong Houd40105d2015-09-18 20:22:41 +00001734
Cong Houd97c1002015-12-01 05:29:22 +00001735 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00001736 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001737 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
1738 // which is a portion of the edge probability from FromBBI.BB to Succ. The
1739 // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if
1740 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
1741 NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001742
Cong Houd97c1002015-12-01 05:29:22 +00001743 // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
Cong Houd40105d2015-09-18 20:22:41 +00001744 // only happens when if-converting a diamond CFG and FromBBI.BB is the
1745 // tail BB. In this case FromBBI.BB post-dominates ToBBI.BB and hence we
Cong Houd97c1002015-12-01 05:29:22 +00001746 // could just use the probabilities on FromBBI.BB's out-edges when adding
1747 // new successors.
1748 if (!To2FromProb.isZero())
1749 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00001750 }
1751
Evan Chengbe9859e2007-06-07 02:12:15 +00001752 FromBBI.BB->removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001753
1754 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001755 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00001756 // probability of this edge by adding NewProb to it. An example is shown
Cong Houd97c1002015-12-01 05:29:22 +00001757 // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we
1758 // don't have to set C as A's successor as it already is. We only need to
1759 // update the edge probability on A->C. Note that B will not be
1760 // immediately removed from A's successors. It is possible that B->D is
1761 // not removed either if D is a fallthrough of B. Later the edge A->D
1762 // (generated here) and B->D will be combined into one edge. To maintain
1763 // correct edge probability of this combined edge, we need to set the edge
1764 // probability of A->B to zero, which is already done above. The edge
1765 // probability on A->D is calculated by scaling the original probability
1766 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00001767 //
1768 // Before ifcvt: After ifcvt (assume B->D is kept):
1769 //
1770 // A A
1771 // /| /|\
1772 // / B / B|
1773 // | /| | ||
1774 // |/ | | |/
1775 // C D C D
1776 //
1777 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00001778 ToBBI.BB->setSuccProbability(
Cong Houd40105d2015-09-18 20:22:41 +00001779 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00001780 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001781 else
Cong Houd97c1002015-12-01 05:29:22 +00001782 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001783 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001784 }
1785
Bob Wilson2371f4f2009-05-13 23:25:24 +00001786 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00001787 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00001788 FromBBI.BB->addSuccessor(NBB);
1789
Cong Houc1069892015-12-13 09:26:17 +00001790 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
1791 // we've done above.
1792 ToBBI.BB->normalizeSuccProbs();
1793
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001794 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001795 FromBBI.Predicate.clear();
1796
Evan Chengd0e66912007-05-23 07:23:16 +00001797 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001798 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001799 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001800 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001801 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001802 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001803
Evan Cheng4dd31a72007-06-11 22:26:22 +00001804 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001805 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001806 ToBBI.IsAnalyzed = false;
1807 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001808}
Akira Hatanaka4a616192015-06-08 18:50:43 +00001809
1810FunctionPass *
1811llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
1812 return new IfConverter(Ftor);
1813}