blob: 9b30fa191a6ab1645710f4339a51f648ea9e9e9d [file] [log] [blame]
Evan Chengf5e53a52007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
Justin Lebaracc47102016-04-01 01:09:03 +000010// This file implements the machine instruction level if-conversion pass, which
11// tries to convert conditional branches into predicated instructions.
Evan Chengf5e53a52007-05-16 02:00:57 +000012//
13//===----------------------------------------------------------------------===//
14
Evan Chengf5e53a52007-05-16 02:00:57 +000015#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "BranchFolding.h"
17#include "llvm/ADT/STLExtras.h"
Kyle Buttd76755e2016-08-18 22:09:23 +000018#include "llvm/ADT/ScopeExit.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000021#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000022#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000023#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000024#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000025#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000028#include "llvm/CodeGen/TargetSchedule.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000029#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000030#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000031#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000036#include "llvm/Target/TargetSubtargetInfo.h"
Cong Houd97c1002015-12-01 05:29:22 +000037#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000038#include <utility>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000039
Evan Chengf5e53a52007-05-16 02:00:57 +000040using namespace llvm;
41
Chandler Carruth1b9dde02014-04-22 02:02:50 +000042#define DEBUG_TYPE "ifcvt"
43
Chris Lattner769c86b2008-01-07 05:40:58 +000044// Hidden options for help debugging.
45static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
46static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
47static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000048static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000049 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000050static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000051 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000052static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000053 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000054static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000055 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000056static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000057 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000058static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000059 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000060static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000061 cl::init(false), cl::Hidden);
Kyle Butta8c73712016-08-24 21:34:27 +000062static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
63 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000064static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
65 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000066
Evan Cheng2117d1f2007-06-09 01:03:43 +000067STATISTIC(NumSimple, "Number of simple if-conversions performed");
68STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
69STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000070STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000071STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
72STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
73STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
Kyle Butta8c73712016-08-24 21:34:27 +000074STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000075STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000076STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000077STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000078
79namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000080 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000081 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000082 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000083 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000084 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
85 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000086 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000087 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000088 ICTriangle, // BB is entry of a triangle sub-CFG.
Kyle Butta8c73712016-08-24 21:34:27 +000089 ICDiamond, // BB is entry of a diamond sub-CFG.
90 ICForkedDiamond // BB is entry of an almost diamond sub-CFG, with a
91 // common tail that can be shared.
Evan Chengf5e53a52007-05-16 02:00:57 +000092 };
93
Matthias Braun2c931792016-08-17 02:51:57 +000094 /// One per MachineBasicBlock, this is used to cache the result
Evan Chengf5e53a52007-05-16 02:00:57 +000095 /// if-conversion feasibility analysis. This includes results from
Jacques Pienaar71c30a12016-07-15 14:41:04 +000096 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000097 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000098 /// diamond shape), its size, whether it's predicable, and whether any
99 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +0000100 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +0000101 /// IsDone - True if BB is not to be considered for ifcvt.
102 /// IsBeingAnalyzed - True if BB is currently being analyzed.
103 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
104 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000105 /// IsBrAnalyzable - True if analyzeBranch() returns false.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000106 /// HasFallThrough - True if BB may fallthrough to the following BB.
107 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000108 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000109 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000110 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000111 /// ExtraCost - Extra cost for multi-cycle instructions.
112 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000113 /// BB - Corresponding MachineBasicBlock.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000114 /// TrueBB / FalseBB- See analyzeBranch().
Evan Chengd0e66912007-05-23 07:23:16 +0000115 /// BrCond - Conditions for end of block conditional branches.
116 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000117 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000118 bool IsDone : 1;
119 bool IsBeingAnalyzed : 1;
120 bool IsAnalyzed : 1;
121 bool IsEnqueued : 1;
122 bool IsBrAnalyzable : 1;
Kyle Butta8c73712016-08-24 21:34:27 +0000123 bool IsBrReversible : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000124 bool HasFallThrough : 1;
125 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000126 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000127 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000128 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000129 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000130 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000131 MachineBasicBlock *BB;
132 MachineBasicBlock *TrueBB;
133 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000134 SmallVector<MachineOperand, 4> BrCond;
135 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000136 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000137 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
Kyle Butta8c73712016-08-24 21:34:27 +0000138 IsBrReversible(false), HasFallThrough(false),
139 IsUnpredicable(false), CannotBeCopied(false),
140 ClobbersPred(false), NonPredSize(0), ExtraCost(0),
141 ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
Craig Topperc0196b12014-04-14 00:51:57 +0000142 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000143 };
144
Matthias Braun2c931792016-08-17 02:51:57 +0000145 /// Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000146 /// BBI - Corresponding BBInfo.
147 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000148 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000149 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000150 /// NumDups - Number of instructions that would be duplicated due
151 /// to this if-conversion. (For diamonds, the number of
152 /// identical instructions at the beginnings of both
153 /// paths).
154 /// NumDups2 - For diamonds, the number of identical instructions
155 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000156 struct IfcvtToken {
157 BBInfo &BBI;
158 IfcvtKind Kind;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000159 unsigned NumDups;
160 unsigned NumDups2;
Kyle Butt6262ca32016-08-24 21:34:24 +0000161 bool NeedSubsumption : 1;
162 bool TClobbersPred : 1;
163 bool FClobbersPred : 1;
164 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
165 bool tc = false, bool fc = false)
166 : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
167 TClobbersPred(tc), FClobbersPred(fc) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000168 };
169
Matthias Braun2c931792016-08-17 02:51:57 +0000170 /// Results of if-conversion feasibility analysis indexed by basic block
171 /// number.
Evan Chengf5e53a52007-05-16 02:00:57 +0000172 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000173 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000174
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000175 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000176 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000177 const TargetRegisterInfo *TRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000178 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000179 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000180
Juergen Ributzka310034e2013-12-14 06:52:56 +0000181 LivePhysRegs Redefs;
182 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000183
Evan Chengc5adcca2012-06-08 21:53:50 +0000184 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000185 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000186 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000187 std::function<bool(const Function &)> PredicateFtor;
188
Evan Chengf5e53a52007-05-16 02:00:57 +0000189 public:
190 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000191 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000192 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000193 initializeIfConverterPass(*PassRegistry::getPassRegistry());
194 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000195
Craig Topper4584cd52014-03-07 09:26:03 +0000196 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000197 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000198 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000199 MachineFunctionPass::getAnalysisUsage(AU);
200 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000201
Craig Topper4584cd52014-03-07 09:26:03 +0000202 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000203
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000204 MachineFunctionProperties getRequiredProperties() const override {
205 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000206 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000207 }
208
Evan Chengf5e53a52007-05-16 02:00:57 +0000209 private:
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000210 bool ReverseBranchCondition(BBInfo &BBI) const;
Owen Andersonf31f33e2010-10-01 22:45:50 +0000211 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000212 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000213 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000214 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000215 BranchProbability Prediction) const;
Kyle Butt6262ca32016-08-24 21:34:24 +0000216 bool CountDuplicatedInstructions(
217 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
218 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
219 unsigned &Dups1, unsigned &Dups2,
220 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
221 bool SkipUnconditionalBranches) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000222 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
Kyle Butt6262ca32016-08-24 21:34:24 +0000223 unsigned &Dups1, unsigned &Dups2,
224 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butta8c73712016-08-24 21:34:27 +0000225 bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
226 unsigned &Dups1, unsigned &Dups2,
227 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000228 void AnalyzeBranches(BBInfo &BBI);
229 void ScanInstructions(BBInfo &BBI,
230 MachineBasicBlock::iterator &Begin,
Kyle Butt6262ca32016-08-24 21:34:24 +0000231 MachineBasicBlock::iterator &End,
232 bool BranchUnpredicable = false) const;
233 bool RescanInstructions(
234 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
235 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
236 BBInfo &TrueBBI, BBInfo &FalseBBI) const;
Matthias Braun08f47042016-08-17 02:52:01 +0000237 void AnalyzeBlock(MachineBasicBlock &MBB,
Justin Lebar3a7bc572016-02-22 17:51:28 +0000238 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000239 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Kyle Butt6262ca32016-08-24 21:34:24 +0000240 bool isTriangle = false, bool RevBranch = false,
241 bool hasCommonTail = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000242 void AnalyzeBlocks(MachineFunction &MF,
243 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Matthias Braun08f47042016-08-17 02:52:01 +0000244 void InvalidatePreds(MachineBasicBlock &MBB);
Evan Cheng288f1542007-06-08 22:01:07 +0000245 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000246 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
247 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Kyle Butta8c73712016-08-24 21:34:27 +0000248 bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
249 unsigned NumDups1, unsigned NumDups2,
250 bool TClobbersPred, bool FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +0000251 bool RemoveBranch, bool MergeAddEdges);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000252 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
Kyle Butt6262ca32016-08-24 21:34:24 +0000253 unsigned NumDups1, unsigned NumDups2,
254 bool TClobbers, bool FClobbers);
Kyle Butta8c73712016-08-24 21:34:27 +0000255 bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
256 unsigned NumDups1, unsigned NumDups2,
257 bool TClobbers, bool FClobbers);
Evan Chengd0e66912007-05-23 07:23:16 +0000258 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000259 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000260 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000261 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000262 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000263 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000264 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000265 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000266
Evan Chengdebf9c52010-11-03 00:45:17 +0000267 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
268 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000269 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000270 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000271 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000272 }
273
Evan Chengdebf9c52010-11-03 00:45:17 +0000274 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
275 unsigned TCycle, unsigned TExtra,
276 MachineBasicBlock &FBB,
277 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000278 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000279 return TCycle > 0 && FCycle > 0 &&
280 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000281 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000282 }
283
Matthias Braun2c931792016-08-17 02:51:57 +0000284 /// Returns true if Block ends without a terminator.
Evan Chengbe9859e2007-06-07 02:12:15 +0000285 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000286 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000287 }
288
Matthias Braun2c931792016-08-17 02:51:57 +0000289 /// Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000290 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
291 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000292 int Incr1 = (C1->Kind == ICDiamond)
293 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
294 int Incr2 = (C2->Kind == ICDiamond)
295 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
296 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000297 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000298 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000299 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000300 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000301 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000302 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000303 // Favors diamond over triangle, etc.
304 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
305 return true;
306 else if (C1->Kind == C2->Kind)
307 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
308 }
309 }
310 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000311 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000312 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000313
Evan Chengf5e53a52007-05-16 02:00:57 +0000314 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000315}
Evan Chengf5e53a52007-05-16 02:00:57 +0000316
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000317char &llvm::IfConverterID = IfConverter::ID;
318
Owen Anderson8ac477f2010-10-12 19:48:12 +0000319INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000320INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000321INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000322
Evan Chengf5e53a52007-05-16 02:00:57 +0000323bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000324 if (skipFunction(*MF.getFunction()) ||
325 (PredicateFtor && !PredicateFtor(*MF.getFunction())))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000326 return false;
327
Eric Christopher3d4276f2015-01-27 07:31:29 +0000328 const TargetSubtargetInfo &ST = MF.getSubtarget();
329 TLI = ST.getTargetLowering();
330 TII = ST.getInstrInfo();
331 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000332 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000333 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000334 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000335 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000336
Evan Chengf5e53a52007-05-16 02:00:57 +0000337 if (!TII) return false;
338
Evan Chengc5adcca2012-06-08 21:53:50 +0000339 PreRegAlloc = MRI->isSSA();
340
341 bool BFChange = false;
342 if (!PreRegAlloc) {
343 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000344 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000345 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000346 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000347 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000348
David Greene72e47cd2010-01-04 22:02:01 +0000349 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000350 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000351
352 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000353 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000354 return false;
355 }
David Greene72e47cd2010-01-04 22:02:01 +0000356 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000357
Evan Chengf5e53a52007-05-16 02:00:57 +0000358 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000359 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000360
Justin Lebar3a7bc572016-02-22 17:51:28 +0000361 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000362 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000363 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
364 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
365 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000366 // Do an initial analysis for each basic block and find all the potential
367 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000368 bool Change = false;
369 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000370 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000371 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000372 Tokens.pop_back();
373 BBInfo &BBI = Token->BBI;
374 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000375 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000376 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000377
Evan Cheng4dd31a72007-06-11 22:26:22 +0000378 // If the block has been evicted out of the queue or it has already been
379 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000380 if (BBI.IsDone)
381 BBI.IsEnqueued = false;
382 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000383 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000384
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000385 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000386
Evan Cheng312b7232007-06-04 06:47:22 +0000387 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000388 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000389 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000390 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000391 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000392 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000393 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000394 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
395 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000396 << "): BB#" << BBI.BB->getNumber() << " ("
397 << ((Kind == ICSimpleFalse)
398 ? BBI.FalseBB->getNumber()
399 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000400 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000401 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000402 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000403 if (isFalse) ++NumSimpleFalse;
404 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000405 }
Evan Cheng312b7232007-06-04 06:47:22 +0000406 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000407 }
Evan Chengd0e66912007-05-23 07:23:16 +0000408 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000409 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000410 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000411 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000412 bool isFalse = Kind == ICTriangleFalse;
413 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000414 if (DisableTriangle && !isFalse && !isRev) break;
415 if (DisableTriangleR && !isFalse && isRev) break;
416 if (DisableTriangleF && isFalse && !isRev) break;
417 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000418 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000419 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000420 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000421 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000422 DEBUG(dbgs() << " rev");
423 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000424 << BBI.TrueBB->getNumber() << ",F:"
425 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000426 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000427 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000428 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000429 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000430 if (isRev) ++NumTriangleFRev;
431 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000432 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000433 if (isRev) ++NumTriangleRev;
434 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000435 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000436 }
Evan Chengd0e66912007-05-23 07:23:16 +0000437 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000438 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000439 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000440 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000441 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000442 << BBI.TrueBB->getNumber() << ",F:"
443 << BBI.FalseBB->getNumber() << ") ");
Kyle Butt6262ca32016-08-24 21:34:24 +0000444 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
445 Token->TClobbersPred,
446 Token->FClobbersPred);
David Greene72e47cd2010-01-04 22:02:01 +0000447 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000448 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000449 break;
450 }
Kyle Butta8c73712016-08-24 21:34:27 +0000451 case ICForkedDiamond: {
452 if (DisableForkedDiamond) break;
453 DEBUG(dbgs() << "Ifcvt (Forked Diamond): BB#"
454 << BBI.BB->getNumber() << " (T:"
455 << BBI.TrueBB->getNumber() << ",F:"
456 << BBI.FalseBB->getNumber() << ") ");
457 RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
458 Token->TClobbersPred,
459 Token->FClobbersPred);
460 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
461 if (RetVal) ++NumForkedDiamonds;
462 break;
463 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000464 }
465
Evan Cheng312b7232007-06-04 06:47:22 +0000466 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000467
Evan Cheng92fb5452007-06-15 07:36:12 +0000468 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
469 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
470 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000471 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000472 }
Evan Chengd0e66912007-05-23 07:23:16 +0000473
Evan Chengd0e66912007-05-23 07:23:16 +0000474 if (!Change)
475 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000476 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000477 }
Evan Cheng478b8052007-05-18 01:55:58 +0000478
Evan Cheng3a51c852007-06-16 09:34:52 +0000479 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000480 BBAnalysis.clear();
481
Evan Chengcf9e8a92010-06-18 22:17:13 +0000482 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000483 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000484 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000485 getAnalysisIfAvailable<MachineModuleInfo>());
486 }
487
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000488 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000489 return MadeChange;
490}
491
Matthias Braun2c931792016-08-17 02:51:57 +0000492/// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000493static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000494 MachineBasicBlock *TrueBB) {
Matthias Braunb1e05582016-08-17 02:51:59 +0000495 for (MachineBasicBlock *SuccBB : BB->successors()) {
Evan Cheng0f745da2007-05-18 00:20:58 +0000496 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000497 return SuccBB;
498 }
Craig Topperc0196b12014-04-14 00:51:57 +0000499 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000500}
501
Matthias Braun2c931792016-08-17 02:51:57 +0000502/// Reverse the condition of the end of the block branch. Swap block's 'true'
503/// and 'false' successors.
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000504bool IfConverter::ReverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000505 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000506 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
507 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000508 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000509 std::swap(BBI.TrueBB, BBI.FalseBB);
510 return true;
511 }
512 return false;
513}
514
Matthias Braun2c931792016-08-17 02:51:57 +0000515/// Returns the next block in the function blocks ordering. If it is the end,
516/// returns NULL.
Matthias Braun08f47042016-08-17 02:52:01 +0000517static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
518 MachineFunction::iterator I = MBB.getIterator();
519 MachineFunction::iterator E = MBB.getParent()->end();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000520 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000521 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000522 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000523}
524
Matthias Braun2c931792016-08-17 02:51:57 +0000525/// Returns true if the 'true' block (along with its predecessor) forms a valid
526/// simple shape for ifcvt. It also returns the number of instructions that the
527/// ifcvt would need to duplicate if performed in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000528bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000529 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000530 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000531 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000532 return false;
533
Evan Chenga955c022007-06-19 21:45:13 +0000534 if (TrueBBI.IsBrAnalyzable)
535 return false;
536
Evan Cheng23402fc2007-06-15 21:18:05 +0000537 if (TrueBBI.BB->pred_size() > 1) {
538 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000539 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000540 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000541 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000542 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000543 }
544
Evan Chenga955c022007-06-19 21:45:13 +0000545 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000546}
547
Matthias Braun2c931792016-08-17 02:51:57 +0000548/// Returns true if the 'true' and 'false' blocks (along with their common
549/// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
550/// true, it checks if 'true' block's false branch branches to the 'false' block
551/// rather than the other way around. It also returns the number of instructions
552/// that the ifcvt would need to duplicate if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000553bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000554 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000555 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000556 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000557 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000558 return false;
559
Evan Cheng23402fc2007-06-15 21:18:05 +0000560 if (TrueBBI.BB->pred_size() > 1) {
561 if (TrueBBI.CannotBeCopied)
562 return false;
563
Evan Cheng92fb5452007-06-15 07:36:12 +0000564 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000565 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000566 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000567 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000568 --Size;
569 else {
570 MachineBasicBlock *FExit = FalseBranch
571 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
572 if (FExit)
573 // Require a conditional branch
574 ++Size;
575 }
576 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000577 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000578 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000579 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000580 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000581
Evan Cheng7783f822007-06-08 09:36:04 +0000582 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
583 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000584 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000585 if (++I == TrueBBI.BB->getParent()->end())
586 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000587 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000588 }
Evan Cheng7783f822007-06-08 09:36:04 +0000589 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000590}
591
Matthias Braun2c931792016-08-17 02:51:57 +0000592/// Increment \p It until it points to a non-debug instruction or to \p End.
Kyle Buttfe916822016-08-06 01:52:31 +0000593/// @param It Iterator to increment
594/// @param End Iterator that points to end. Will be compared to It
595/// @returns true if It == End, false otherwise.
596static inline bool skipDebugInstructionsForward(
597 MachineBasicBlock::iterator &It,
598 MachineBasicBlock::iterator &End) {
599 while (It != End && It->isDebugValue())
600 It++;
601 return It == End;
602}
603
Kyle Buttd76755e2016-08-18 22:09:23 +0000604/// Shrink the provided inclusive range by one instruction.
605/// If the range was one instruction (\p It == \p Begin), It is not modified,
606/// but \p Empty is set to true.
607static inline void shrinkInclusiveRange(
608 MachineBasicBlock::iterator &Begin,
609 MachineBasicBlock::iterator &It,
610 bool &Empty) {
611 if (It == Begin)
612 Empty = true;
613 else
614 It--;
615}
616
617/// Decrement \p It until it points to a non-debug instruction or the range is
618/// empty.
Kyle Buttfe916822016-08-06 01:52:31 +0000619/// @param It Iterator to decrement.
David Majnemer70c93fa2016-08-06 08:37:12 +0000620/// @param Begin Iterator that points to beginning. Will be compared to It
Kyle Buttd76755e2016-08-18 22:09:23 +0000621/// @param Empty Set to true if the resulting range is Empty
622/// @returns the value of Empty as a convenience.
Kyle Buttfe916822016-08-06 01:52:31 +0000623static inline bool skipDebugInstructionsBackward(
Kyle Buttd76755e2016-08-18 22:09:23 +0000624 MachineBasicBlock::iterator &Begin,
Kyle Buttfe916822016-08-06 01:52:31 +0000625 MachineBasicBlock::iterator &It,
Kyle Buttd76755e2016-08-18 22:09:23 +0000626 bool &Empty) {
627 while (!Empty && It->isDebugValue())
628 shrinkInclusiveRange(Begin, It, Empty);
629 return Empty;
Kyle Buttfe916822016-08-06 01:52:31 +0000630}
631
Kyle Butt4f0e2872016-08-06 01:52:33 +0000632/// Count duplicated instructions and move the iterators to show where they
633/// are.
634/// @param TIB True Iterator Begin
635/// @param FIB False Iterator Begin
636/// These two iterators initially point to the first instruction of the two
637/// blocks, and finally point to the first non-shared instruction.
638/// @param TIE True Iterator End
639/// @param FIE False Iterator End
640/// These two iterators initially point to End() for the two blocks() and
641/// finally point to the first shared instruction in the tail.
642/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
643/// two blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000644/// @param Dups1 count of duplicated instructions at the beginning of the 2
645/// blocks.
646/// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
647/// @param SkipUnconditionalBranches if true, Don't make sure that
648/// unconditional branches at the end of the blocks are the same. True is
649/// passed when the blocks are analyzable to allow for fallthrough to be
650/// handled.
651/// @return false if the shared portion prevents if conversion.
652bool IfConverter::CountDuplicatedInstructions(
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000653 MachineBasicBlock::iterator &TIB,
654 MachineBasicBlock::iterator &FIB,
655 MachineBasicBlock::iterator &TIE,
656 MachineBasicBlock::iterator &FIE,
657 unsigned &Dups1, unsigned &Dups2,
658 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
Kyle Butt6262ca32016-08-24 21:34:24 +0000659 bool SkipUnconditionalBranches) const {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000660
Bob Wilsone1961fe2010-10-26 00:02:24 +0000661 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000662 // Skip dbg_value instructions. These do not count.
Kyle Buttfe916822016-08-06 01:52:31 +0000663 if(skipDebugInstructionsForward(TIB, TIE))
664 break;
665 if(skipDebugInstructionsForward(FIB, FIE))
666 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000667 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000668 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000669 // A pred-clobbering instruction in the shared portion prevents
670 // if-conversion.
671 std::vector<MachineOperand> PredDefs;
672 if (TII->DefinesPredicate(*TIB, PredDefs))
673 return false;
Kyle Butt93e94e82016-09-02 01:20:06 +0000674 // If we get all the way to the branch instructions, don't count them.
675 if (!TIB->isBranch())
676 ++Dups1;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000677 ++TIB;
678 ++FIB;
679 }
680
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000681 // Check for already containing all of the block.
682 if (TIB == TIE || FIB == FIE)
Kyle Butt6262ca32016-08-24 21:34:24 +0000683 return true;
Kyle Buttd76755e2016-08-18 22:09:23 +0000684 // Now, in preparation for counting duplicate instructions at the ends of the
685 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000686 --TIE;
687 --FIE;
Kyle Buttd76755e2016-08-18 22:09:23 +0000688
689 // After this point TIB and TIE define an inclusive range, which means that
690 // TIB == TIE is true when there is one more instruction to consider, not at
691 // the end. Because we may not be able to go before TIB, we need a flag to
692 // indicate a completely empty range.
693 bool TEmpty = false, FEmpty = false;
694
695 // Upon exit TIE and FIE will both point at the last non-shared instruction.
696 // They need to be moved forward to point past the last non-shared
697 // instruction if the range they delimit is non-empty.
698 auto IncrementEndIteratorsOnExit = make_scope_exit([&]() {
699 if (!TEmpty)
700 ++TIE;
701 if (!FEmpty)
702 ++FIE;
703 });
704
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000705 if (!TBB.succ_empty() || !FBB.succ_empty()) {
Kyle Butt6262ca32016-08-24 21:34:24 +0000706 if (SkipUnconditionalBranches) {
Kyle Buttd76755e2016-08-18 22:09:23 +0000707 while (!TEmpty && TIE->isUnconditionalBranch())
708 shrinkInclusiveRange(TIB, TIE, TEmpty);
709 while (!FEmpty && FIE->isUnconditionalBranch())
710 shrinkInclusiveRange(FIB, FIE, FEmpty);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000711 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000712 }
713
714 // If Dups1 includes all of a block, then don't count duplicate
715 // instructions at the end of the blocks.
Kyle Buttd76755e2016-08-18 22:09:23 +0000716 if (TEmpty || FEmpty)
Kyle Butt6262ca32016-08-24 21:34:24 +0000717 return true;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000718
719 // Count duplicate instructions at the ends of the blocks.
Kyle Buttd76755e2016-08-18 22:09:23 +0000720 while (!TEmpty && !FEmpty) {
Bob Wilsone1961fe2010-10-26 00:02:24 +0000721 // Skip dbg_value instructions. These do not count.
Kyle Buttd76755e2016-08-18 22:09:23 +0000722 if (skipDebugInstructionsBackward(TIB, TIE, TEmpty))
Kyle Buttfe916822016-08-06 01:52:31 +0000723 break;
Kyle Buttd76755e2016-08-18 22:09:23 +0000724 if (skipDebugInstructionsBackward(FIB, FIE, FEmpty))
Kyle Buttfe916822016-08-06 01:52:31 +0000725 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000726 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000727 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000728 // We have to verify that any branch instructions are the same, and then we
729 // don't count them toward the # of duplicate instructions.
730 if (!TIE->isBranch())
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000731 ++Dups2;
Kyle Buttd76755e2016-08-18 22:09:23 +0000732 shrinkInclusiveRange(TIB, TIE, TEmpty);
733 shrinkInclusiveRange(FIB, FIE, FEmpty);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000734 }
Kyle Butt6262ca32016-08-24 21:34:24 +0000735 return true;
736}
737
738/// RescanInstructions - Run ScanInstructions on a pair of blocks.
739/// @param TIB - True Iterator Begin, points to first non-shared instruction
740/// @param FIB - False Iterator Begin, points to first non-shared instruction
741/// @param TIE - True Iterator End, points past last non-shared instruction
742/// @param FIE - False Iterator End, points past last non-shared instruction
743/// @param TrueBBI - BBInfo to update for the true block.
744/// @param FalseBBI - BBInfo to update for the false block.
745/// @returns - false if either block cannot be predicated or if both blocks end
746/// with a predicate-clobbering instruction.
747bool IfConverter::RescanInstructions(
748 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
749 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
750 BBInfo &TrueBBI, BBInfo &FalseBBI) const {
751 bool BranchUnpredicable = true;
752 TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
753 ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
754 if (TrueBBI.IsUnpredicable)
755 return false;
756 ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
757 if (FalseBBI.IsUnpredicable)
758 return false;
759 if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
760 return false;
761 return true;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000762}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000763
Kyle Butt092c4dd2016-08-29 18:27:12 +0000764#ifndef NDEBUG
765static void verifySameBranchInstructions(
766 MachineBasicBlock *MBB1,
767 MachineBasicBlock *MBB2) {
768 MachineBasicBlock::iterator B1 = MBB1->begin();
769 MachineBasicBlock::iterator B2 = MBB2->begin();
770 MachineBasicBlock::iterator E1 = std::prev(MBB1->end());
771 MachineBasicBlock::iterator E2 = std::prev(MBB2->end());
772 bool Empty1 = false, Empty2 = false;
773 while (!Empty1 && !Empty2) {
774 skipDebugInstructionsBackward(B1, E1, Empty1);
775 skipDebugInstructionsBackward(B2, E2, Empty2);
776 if (Empty1 && Empty2)
777 break;
778
779 if (Empty1) {
780 assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
781 break;
782 }
783 if (Empty2) {
784 assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
785 break;
786 }
787
788 if (E1->isBranch() || E2->isBranch())
789 assert(E1->isIdenticalTo(*E2) &&
790 "Branch mis-match, branch instructions don't match.");
791 else
792 break;
793 shrinkInclusiveRange(B1, E1, Empty1);
794 shrinkInclusiveRange(B2, E2, Empty2);
795 }
796}
797#endif
798
Kyle Butta8c73712016-08-24 21:34:27 +0000799/// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
800/// with their common predecessor) form a diamond if a common tail block is
801/// extracted.
802/// While not strictly a diamond, this pattern would form a diamond if
803/// tail-merging had merged the shared tails.
804/// EBB
805/// _/ \_
806/// | |
807/// TBB FBB
808/// / \ / \
809/// FalseBB TrueBB FalseBB
810/// Currently only handles analyzable branches.
811/// Specifically excludes actual diamonds to avoid overlap.
812bool IfConverter::ValidForkedDiamond(
813 BBInfo &TrueBBI, BBInfo &FalseBBI,
814 unsigned &Dups1, unsigned &Dups2,
815 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
816 Dups1 = Dups2 = 0;
817 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
818 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
819 return false;
820
821 if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
822 return false;
823 // Don't IfConvert blocks that can't be folded into their predecessor.
824 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
825 return false;
826
827 // This function is specifically looking for conditional tails, as
828 // unconditional tails are already handled by the standard diamond case.
829 if (TrueBBI.BrCond.size() == 0 ||
830 FalseBBI.BrCond.size() == 0)
831 return false;
832
833 MachineBasicBlock *TT = TrueBBI.TrueBB;
834 MachineBasicBlock *TF = TrueBBI.FalseBB;
835 MachineBasicBlock *FT = FalseBBI.TrueBB;
836 MachineBasicBlock *FF = FalseBBI.FalseBB;
837
838 if (!TT)
839 TT = getNextBlock(*TrueBBI.BB);
840 if (!TF)
841 TF = getNextBlock(*TrueBBI.BB);
842 if (!FT)
843 FT = getNextBlock(*FalseBBI.BB);
844 if (!FF)
845 FF = getNextBlock(*FalseBBI.BB);
846
847 if (!TT || !TF)
848 return false;
849
850 // Check successors. If they don't match, bail.
851 if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
852 return false;
853
854 bool FalseReversed = false;
855 if (TF == FT && TT == FF) {
856 // If the branches are opposing, but we can't reverse, don't do it.
857 if (!FalseBBI.IsBrReversible)
858 return false;
859 FalseReversed = true;
860 ReverseBranchCondition(FalseBBI);
861 }
862 auto UnReverseOnExit = make_scope_exit([&]() {
863 if (FalseReversed)
864 ReverseBranchCondition(FalseBBI);
865 });
866
867 // Count duplicate instructions at the beginning of the true and false blocks.
868 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
869 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
870 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
871 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
872 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
873 *TrueBBI.BB, *FalseBBI.BB,
874 /* SkipUnconditionalBranches */ true))
875 return false;
876
877 TrueBBICalc.BB = TrueBBI.BB;
878 FalseBBICalc.BB = FalseBBI.BB;
879 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
880 return false;
881
882 // The size is used to decide whether to if-convert, and the shared portions
883 // are subtracted off. Because of the subtraction, we just use the size that
884 // was calculated by the original ScanInstructions, as it is correct.
885 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
886 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
887 return true;
888}
889
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000890/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
891/// with their common predecessor) forms a valid diamond shape for ifcvt.
Kyle Butt6262ca32016-08-24 21:34:24 +0000892bool IfConverter::ValidDiamond(
893 BBInfo &TrueBBI, BBInfo &FalseBBI,
894 unsigned &Dups1, unsigned &Dups2,
895 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000896 Dups1 = Dups2 = 0;
897 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
898 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
899 return false;
900
901 MachineBasicBlock *TT = TrueBBI.TrueBB;
902 MachineBasicBlock *FT = FalseBBI.TrueBB;
903
904 if (!TT && blockAlwaysFallThrough(TrueBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000905 TT = getNextBlock(*TrueBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000906 if (!FT && blockAlwaysFallThrough(FalseBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000907 FT = getNextBlock(*FalseBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000908 if (TT != FT)
909 return false;
910 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
911 return false;
912 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
913 return false;
914
915 // FIXME: Allow true block to have an early exit?
Kyle Butt6262ca32016-08-24 21:34:24 +0000916 if (TrueBBI.FalseBB || FalseBBI.FalseBB)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000917 return false;
918
919 // Count duplicate instructions at the beginning and end of the true and
920 // false blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000921 // Skip unconditional branches only if we are considering an analyzable
922 // diamond. Otherwise the branches must be the same.
923 bool SkipUnconditionalBranches =
924 TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000925 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
926 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
927 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
928 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
Kyle Butt6262ca32016-08-24 21:34:24 +0000929 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
930 *TrueBBI.BB, *FalseBBI.BB,
931 SkipUnconditionalBranches))
932 return false;
933
934 TrueBBICalc.BB = TrueBBI.BB;
935 FalseBBICalc.BB = FalseBBI.BB;
936 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
937 return false;
938 // The size is used to decide whether to if-convert, and the shared portions
939 // are subtracted off. Because of the subtraction, we just use the size that
940 // was calculated by the original ScanInstructions, as it is correct.
941 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
942 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000943 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000944}
945
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000946/// AnalyzeBranches - Look at the branches at the end of a block to determine if
947/// the block is predicable.
948void IfConverter::AnalyzeBranches(BBInfo &BBI) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000949 if (BBI.IsDone)
950 return;
951
Craig Topperc0196b12014-04-14 00:51:57 +0000952 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000953 BBI.BrCond.clear();
954 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000955 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Kyle Butta8c73712016-08-24 21:34:27 +0000956 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
957 BBI.IsBrReversible = (RevCond.size() == 0) ||
958 !TII->ReverseBranchCondition(RevCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000959 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000960
961 if (BBI.BrCond.size()) {
962 // No false branch. This BB must end with a conditional branch and a
963 // fallthrough.
964 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000965 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000966 if (!BBI.FalseBB) {
967 // Malformed bcc? True and false blocks are the same?
968 BBI.IsUnpredicable = true;
Evan Chengb9bff582009-06-15 21:24:34 +0000969 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000970 }
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000971}
Evan Cheng4dd31a72007-06-11 22:26:22 +0000972
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000973/// ScanInstructions - Scan all the instructions in the block to determine if
974/// the block is predicable. In most cases, that means all the instructions
975/// in the block are isPredicable(). Also checks if the block contains any
976/// instruction which can clobber a predicate (e.g. condition code register).
977/// If so, the block is not predicable unless it's the last instruction.
978void IfConverter::ScanInstructions(BBInfo &BBI,
979 MachineBasicBlock::iterator &Begin,
Kyle Butt6262ca32016-08-24 21:34:24 +0000980 MachineBasicBlock::iterator &End,
981 bool BranchUnpredicable) const {
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000982 if (BBI.IsDone || BBI.IsUnpredicable)
983 return;
984
985 bool AlreadyPredicated = !BBI.Predicate.empty();
986
Evan Cheng4dd31a72007-06-11 22:26:22 +0000987 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000988 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000989 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000990 BBI.ClobbersPred = false;
Matthias Braunb1e05582016-08-17 02:51:59 +0000991 for (MachineInstr &MI : make_range(Begin, End)) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000992 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000993 continue;
994
Justin Lebar7dba2e02016-04-15 01:38:41 +0000995 // It's unsafe to duplicate convergent instructions in this context, so set
996 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
997 // following CFG, which is subject to our "simple" transformation.
998 //
999 // BB0 // if (c1) goto BB1; else goto BB2;
1000 // / \
1001 // BB1 |
1002 // | BB2 // if (c2) goto TBB; else goto FBB;
1003 // | / |
1004 // | / |
1005 // TBB |
1006 // | |
1007 // | FBB
1008 // |
1009 // exit
1010 //
1011 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
1012 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
1013 // TBB contains a convergent instruction. This is safe iff doing so does
1014 // not add a control-flow dependency to the convergent instruction -- i.e.,
1015 // it's safe iff the set of control flows that leads us to the convergent
1016 // instruction does not get smaller after the transformation.
1017 //
1018 // Originally we executed TBB if c1 || c2. After the transformation, there
1019 // are two copies of TBB's instructions. We get to the first if c1, and we
1020 // get to the second if !c1 && c2.
1021 //
1022 // There are clearly fewer ways to satisfy the condition "c1" than
1023 // "c1 || c2". Since we've shrunk the set of control flows which lead to
1024 // our convergent instruction, the transformation is unsafe.
1025 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +00001026 BBI.CannotBeCopied = true;
1027
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001028 bool isPredicated = TII->isPredicated(MI);
1029 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +00001030
Kyle Butt6262ca32016-08-24 21:34:24 +00001031 if (BranchUnpredicable && MI.isBranch()) {
1032 BBI.IsUnpredicable = true;
1033 return;
1034 }
1035
Joey Goulya5153cb2013-09-09 14:21:49 +00001036 // A conditional branch is not predicable, but it may be eliminated.
1037 if (isCondBr)
1038 continue;
1039
1040 if (!isPredicated) {
1041 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001042 unsigned ExtraPredCost = TII->getPredicationCost(MI);
1043 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +00001044 if (NumCycles > 1)
1045 BBI.ExtraCost += NumCycles-1;
1046 BBI.ExtraCost2 += ExtraPredCost;
1047 } else if (!AlreadyPredicated) {
1048 // FIXME: This instruction is already predicated before the
1049 // if-conversion pass. It's probably something like a conditional move.
1050 // Mark this block unpredicable for now.
1051 BBI.IsUnpredicable = true;
1052 return;
Evan Cheng96c14572007-07-06 23:24:39 +00001053 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001054
1055 if (BBI.ClobbersPred && !isPredicated) {
1056 // Predicate modification instruction should end the block (except for
1057 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +00001058 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +00001059 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001060 BBI.IsUnpredicable = true;
1061 return;
1062 }
1063
Evan Chengfbc73092007-07-10 17:50:43 +00001064 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1065 // still potentially predicable.
1066 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001067 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001068 BBI.ClobbersPred = true;
1069
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001070 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001071 BBI.IsUnpredicable = true;
1072 return;
1073 }
1074 }
1075}
1076
Matthias Braun2c931792016-08-17 02:51:57 +00001077/// Determine if the block is a suitable candidate to be predicated by the
1078/// specified predicate.
Kyle Butt6262ca32016-08-24 21:34:24 +00001079/// @param BBI BBInfo for the block to check
1080/// @param Pred Predicate array for the branch that leads to BBI
1081/// @param isTriangle true if the Analysis is for a triangle
1082/// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1083/// case
1084/// @param hasCommonTail true if BBI shares a tail with a sibling block that
1085/// contains any instruction that would make the block unpredicable.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001086bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001087 SmallVectorImpl<MachineOperand> &Pred,
Kyle Butt6262ca32016-08-24 21:34:24 +00001088 bool isTriangle, bool RevBranch,
1089 bool hasCommonTail) {
Evan Cheng3a51c852007-06-16 09:34:52 +00001090 // If the block is dead or unpredicable, then it cannot be predicated.
Kyle Butt6262ca32016-08-24 21:34:24 +00001091 // Two blocks may share a common unpredicable tail, but this doesn't prevent
1092 // them from being if-converted. The non-shared portion is assumed to have
1093 // been checked
1094 if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001095 return false;
1096
Ahmed Bougacha7173b662015-03-21 01:23:15 +00001097 // If it is already predicated but we couldn't analyze its terminator, the
1098 // latter might fallthrough, but we can't determine where to.
1099 // Conservatively avoid if-converting again.
1100 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1101 return false;
1102
Quentin Colombetbdab2272013-07-24 20:20:37 +00001103 // If it is already predicated, check if the new predicate subsumes
1104 // its predicate.
1105 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001106 return false;
1107
Kyle Butt6262ca32016-08-24 21:34:24 +00001108 if (!hasCommonTail && BBI.BrCond.size()) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001109 if (!isTriangle)
1110 return false;
1111
Bob Wilson2371f4f2009-05-13 23:25:24 +00001112 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +00001113 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1114 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +00001115 if (RevBranch) {
1116 if (TII->ReverseBranchCondition(Cond))
1117 return false;
1118 }
1119 if (TII->ReverseBranchCondition(RevPred) ||
1120 !TII->SubsumesPredicate(Cond, RevPred))
1121 return false;
1122 }
1123
1124 return true;
1125}
1126
Matthias Braun2c931792016-08-17 02:51:57 +00001127/// Analyze the structure of the sub-CFG starting from the specified block.
1128/// Record its successors and whether it looks like an if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001129void IfConverter::AnalyzeBlock(
Matthias Braun08f47042016-08-17 02:52:01 +00001130 MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001131 struct BBState {
Matthias Braun08f47042016-08-17 02:52:01 +00001132 BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001133 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +00001134
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001135 /// This flag is true if MBB's successors have been analyzed.
1136 bool SuccsAnalyzed;
1137 };
Evan Cheng0f745da2007-05-18 00:20:58 +00001138
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001139 // Push MBB to the stack.
1140 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001141
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001142 while (!BBStack.empty()) {
1143 BBState &State = BBStack.back();
1144 MachineBasicBlock *BB = State.MBB;
1145 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +00001146
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001147 if (!State.SuccsAnalyzed) {
1148 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1149 BBStack.pop_back();
1150 continue;
1151 }
Evan Cheng9030b982007-06-06 10:16:17 +00001152
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001153 BBI.BB = BB;
1154 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +00001155
Kyle Butt54bf3ce2016-08-06 01:52:34 +00001156 AnalyzeBranches(BBI);
1157 MachineBasicBlock::iterator Begin = BBI.BB->begin();
1158 MachineBasicBlock::iterator End = BBI.BB->end();
1159 ScanInstructions(BBI, Begin, End);
Evan Chengb9bff582009-06-15 21:24:34 +00001160
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001161 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1162 // not considered for ifcvt anymore.
1163 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1164 BBI.IsBeingAnalyzed = false;
1165 BBI.IsAnalyzed = true;
1166 BBStack.pop_back();
1167 continue;
1168 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001169
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001170 // Do not ifcvt if either path is a back edge to the entry block.
1171 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1172 BBI.IsBeingAnalyzed = false;
1173 BBI.IsAnalyzed = true;
1174 BBStack.pop_back();
1175 continue;
1176 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001177
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001178 // Do not ifcvt if true and false fallthrough blocks are the same.
1179 if (!BBI.FalseBB) {
1180 BBI.IsBeingAnalyzed = false;
1181 BBI.IsAnalyzed = true;
1182 BBStack.pop_back();
1183 continue;
1184 }
Evan Cheng7783f822007-06-08 09:36:04 +00001185
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001186 // Push the False and True blocks to the stack.
1187 State.SuccsAnalyzed = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001188 BBStack.push_back(*BBI.FalseBB);
1189 BBStack.push_back(*BBI.TrueBB);
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001190 continue;
1191 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +00001192
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001193 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1194 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +00001195
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001196 if (TrueBBI.IsDone && FalseBBI.IsDone) {
1197 BBI.IsBeingAnalyzed = false;
1198 BBI.IsAnalyzed = true;
1199 BBStack.pop_back();
1200 continue;
1201 }
1202
1203 SmallVector<MachineOperand, 4>
1204 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1205 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
1206
1207 unsigned Dups = 0;
1208 unsigned Dups2 = 0;
1209 bool TNeedSub = !TrueBBI.Predicate.empty();
1210 bool FNeedSub = !FalseBBI.Predicate.empty();
1211 bool Enqueued = false;
1212
1213 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1214
Kyle Butt6262ca32016-08-24 21:34:24 +00001215 if (CanRevCond) {
1216 BBInfo TrueBBICalc, FalseBBICalc;
Kyle Butta8c73712016-08-24 21:34:27 +00001217 auto feasibleDiamond = [&]() {
1218 bool MeetsSize = MeetIfcvtSizeLimit(
1219 *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1220 TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1221 *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1222 FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1223 Prediction);
1224 bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1225 /* IsTriangle */ false, /* RevCond */ false,
1226 /* hasCommonTail */ true);
1227 bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1228 /* IsTriangle */ false, /* RevCond */ false,
1229 /* hasCommonTail */ true);
1230 return MeetsSize && TrueFeasible && FalseFeasible;
1231 };
1232
Kyle Butt6262ca32016-08-24 21:34:24 +00001233 if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
Kyle Butta8c73712016-08-24 21:34:27 +00001234 TrueBBICalc, FalseBBICalc)) {
1235 if (feasibleDiamond()) {
1236 // Diamond:
1237 // EBB
1238 // / \_
1239 // | |
1240 // TBB FBB
1241 // \ /
1242 // TailBB
1243 // Note TailBB can be empty.
1244 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1245 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1246 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1247 Enqueued = true;
1248 }
1249 } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1250 TrueBBICalc, FalseBBICalc)) {
1251 if (feasibleDiamond()) {
1252 // ForkedDiamond:
1253 // if TBB and FBB have a common tail that includes their conditional
1254 // branch instructions, then we can If Convert this pattern.
1255 // EBB
1256 // _/ \_
1257 // | |
1258 // TBB FBB
1259 // / \ / \
1260 // FalseBB TrueBB FalseBB
1261 //
1262 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1263 BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1264 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1265 Enqueued = true;
1266 }
Kyle Butt6262ca32016-08-24 21:34:24 +00001267 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001268 }
1269
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001270 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1271 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1272 TrueBBI.ExtraCost2, Prediction) &&
1273 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1274 // Triangle:
1275 // EBB
1276 // | \_
1277 // | |
1278 // | TBB
1279 // | /
1280 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001281 Tokens.push_back(
1282 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001283 Enqueued = true;
1284 }
1285
1286 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1287 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1288 TrueBBI.ExtraCost2, Prediction) &&
1289 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001290 Tokens.push_back(
1291 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001292 Enqueued = true;
1293 }
1294
1295 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1296 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1297 TrueBBI.ExtraCost2, Prediction) &&
1298 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1299 // Simple (split, no rejoin):
1300 // EBB
1301 // | \_
1302 // | |
1303 // | TBB---> exit
1304 // |
1305 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001306 Tokens.push_back(
1307 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001308 Enqueued = true;
1309 }
1310
1311 if (CanRevCond) {
1312 // Try the other path...
1313 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1314 Prediction.getCompl()) &&
1315 MeetIfcvtSizeLimit(*FalseBBI.BB,
1316 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1317 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1318 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001319 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1320 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001321 Enqueued = true;
1322 }
1323
1324 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1325 Prediction.getCompl()) &&
1326 MeetIfcvtSizeLimit(*FalseBBI.BB,
1327 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +00001328 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +00001329 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001330 Tokens.push_back(
1331 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001332 Enqueued = true;
1333 }
1334
1335 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1336 MeetIfcvtSizeLimit(*FalseBBI.BB,
1337 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1338 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1339 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001340 Tokens.push_back(
1341 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001342 Enqueued = true;
1343 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001344 }
1345
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001346 BBI.IsEnqueued = Enqueued;
1347 BBI.IsBeingAnalyzed = false;
1348 BBI.IsAnalyzed = true;
1349 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001350 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001351}
1352
Matthias Braun2c931792016-08-17 02:51:57 +00001353/// Analyze all blocks and find entries for all if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001354void IfConverter::AnalyzeBlocks(
1355 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001356 for (MachineBasicBlock &MBB : MF)
Matthias Braun08f47042016-08-17 02:52:01 +00001357 AnalyzeBlock(MBB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001358
Evan Cheng20e05992007-06-01 00:12:12 +00001359 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +00001360 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001361}
1362
Matthias Braun2c931792016-08-17 02:51:57 +00001363/// Returns true either if ToMBB is the next block after MBB or that all the
1364/// intervening blocks are empty (given MBB can fall through to its next block).
Matthias Braun08f47042016-08-17 02:52:01 +00001365static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1366 MachineFunction::iterator PI = MBB.getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001367 MachineFunction::iterator I = std::next(PI);
Matthias Braun08f47042016-08-17 02:52:01 +00001368 MachineFunction::iterator TI = ToMBB.getIterator();
1369 MachineFunction::iterator E = MBB.getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001370 while (I != TI) {
1371 // Check isSuccessor to avoid case where the next block is empty, but
1372 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001373 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001374 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001375 PI = I++;
1376 }
Evan Cheng312b7232007-06-04 06:47:22 +00001377 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001378}
1379
Matthias Braun2c931792016-08-17 02:51:57 +00001380/// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1381/// can be if-converted. If predecessor is already enqueued, dequeue it!
Matthias Braun08f47042016-08-17 02:52:01 +00001382void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1383 for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001384 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Matthias Braun08f47042016-08-17 02:52:01 +00001385 if (PBBI.IsDone || PBBI.BB == &MBB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001386 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001387 PBBI.IsAnalyzed = false;
1388 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001389 }
1390}
1391
Matthias Braun2c931792016-08-17 02:51:57 +00001392/// Inserts an unconditional branch from \p MBB to \p ToMBB.
Matthias Braun08f47042016-08-17 02:52:01 +00001393static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
Evan Chengc2237ce2007-05-29 22:31:16 +00001394 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001395 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001396 SmallVector<MachineOperand, 0> NoCond;
Matthias Braun08f47042016-08-17 02:52:01 +00001397 TII->InsertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001398}
1399
Matthias Braun2c931792016-08-17 02:51:57 +00001400/// Remove true / false edges if either / both are no longer successors.
Evan Cheng288f1542007-06-08 22:01:07 +00001401void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001402 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001403 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001404 if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
Evan Cheng0598b2d2007-06-18 22:44:57 +00001405 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001406}
1407
Matthias Braund616ccc2013-10-11 19:04:37 +00001408/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Jonas Paulsson196986c2016-08-03 05:46:35 +00001409/// values defined in MI which are also live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001410static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Jonas Paulsson196986c2016-08-03 05:46:35 +00001411 const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1412 ->getSubtarget().getRegisterInfo();
1413
1414 // Before stepping forward past MI, remember which regs were live
1415 // before MI. This is needed to set the Undef flag only when reg is
1416 // dead.
1417 SparseSet<unsigned> LiveBeforeMI;
1418 LiveBeforeMI.setUniverse(TRI->getNumRegs());
Matthias Braunb1e05582016-08-17 02:51:59 +00001419 for (unsigned Reg : Redefs)
Jonas Paulsson196986c2016-08-03 05:46:35 +00001420 LiveBeforeMI.insert(Reg);
1421
Pete Cooper7605e372015-05-05 20:14:22 +00001422 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001423 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001424
Pete Cooper7605e372015-05-05 20:14:22 +00001425 // Now add the implicit uses for each of the clobbered values.
Matthias Braun08f47042016-08-17 02:52:01 +00001426 for (auto Clobber : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001427 // FIXME: Const cast here is nasty, but better than making StepForward
1428 // take a mutable instruction instead of const.
Matthias Braun08f47042016-08-17 02:52:01 +00001429 unsigned Reg = Clobber.first;
1430 MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
Pete Cooper27483912015-05-06 22:51:04 +00001431 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001432 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001433 if (Op.isRegMask()) {
1434 // First handle regmasks. They clobber any entries in the mask which
1435 // means that we need a def for those registers.
Matthias Braun08f47042016-08-17 02:52:01 +00001436 if (LiveBeforeMI.count(Reg))
1437 MIB.addReg(Reg, RegState::Implicit);
Pete Cooperce9ad752015-05-05 22:09:41 +00001438
1439 // We also need to add an implicit def of this register for the later
1440 // use to read from.
1441 // For the register allocator to have allocated a register clobbered
1442 // by the call which is used later, it must be the case that
1443 // the call doesn't return.
Matthias Braun08f47042016-08-17 02:52:01 +00001444 MIB.addReg(Reg, RegState::Implicit | RegState::Define);
Pete Cooperce9ad752015-05-05 22:09:41 +00001445 continue;
1446 }
1447 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001448 if (Op.isDead()) {
1449 // If we found a dead def, but it needs to be live, then remove the dead
1450 // flag.
1451 if (Redefs.contains(Op.getReg()))
1452 Op.setIsDead(false);
1453 }
Matthias Braun08f47042016-08-17 02:52:01 +00001454 if (LiveBeforeMI.count(Reg))
1455 MIB.addReg(Reg, RegState::Implicit);
Matthias Braund616ccc2013-10-11 19:04:37 +00001456 }
1457}
1458
Matthias Braun2c931792016-08-17 02:51:57 +00001459/// Remove kill flags from operands with a registers in the \p DontKill set.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001460static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001461 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001462 if (!O->isReg() || !O->isKill())
1463 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001464 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001465 O->setIsKill(false);
1466 }
1467}
1468
Matthias Braun2c931792016-08-17 02:51:57 +00001469/// Walks a range of machine instructions and removes kill flags for registers
1470/// in the \p DontKill set.
Matthias Braund616ccc2013-10-11 19:04:37 +00001471static void RemoveKills(MachineBasicBlock::iterator I,
1472 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001473 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001474 const MCRegisterInfo &MCRI) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001475 for (MachineInstr &MI : make_range(I, E))
1476 RemoveKills(MI, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001477}
1478
Matthias Braun2c931792016-08-17 02:51:57 +00001479/// If convert a simple (split, no rejoin) sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001480bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001481 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1482 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1483 BBInfo *CvtBBI = &TrueBBI;
1484 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001485
Owen Anderson4f6bf042008-08-14 22:49:33 +00001486 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001487 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001488 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001489
Matthias Braun08f47042016-08-17 02:52:01 +00001490 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1491 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001492 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001493 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001494 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001495 BBI.IsAnalyzed = false;
1496 CvtBBI->IsAnalyzed = false;
1497 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001498 }
Evan Chengd0e66912007-05-23 07:23:16 +00001499
Matthias Braun08f47042016-08-17 02:52:01 +00001500 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001501 // Conservatively abort if-conversion if BB's address is taken.
1502 return false;
1503
Evan Cheng3a51c852007-06-16 09:34:52 +00001504 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001505 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001506 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001507
Bob Wilson45814342010-06-19 05:33:57 +00001508 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001509 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001510 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001511 Redefs.addLiveIns(CvtMBB);
1512 Redefs.addLiveIns(NextMBB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001513
1514 // Compute a set of registers which must not be killed by instructions in
1515 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001516 DontKill.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001517 DontKill.addLiveIns(NextMBB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001518
Matthias Braun08f47042016-08-17 02:52:01 +00001519 if (CvtMBB.pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001520 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001521 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001522 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001523 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001524
1525 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1526 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001527 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001528 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001529 RemoveKills(CvtMBB.begin(), CvtMBB.end(), DontKill, *TRI);
1530 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001531
Evan Cheng92fb5452007-06-15 07:36:12 +00001532 // Merge converted block into entry block.
1533 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1534 MergeBlocks(BBI, *CvtBBI);
1535 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001536
Evan Chenge4ec9182007-06-06 02:08:52 +00001537 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001538 if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1539 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001540 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001541 // Now ifcvt'd block will look like this:
1542 // BB:
1543 // ...
1544 // t, f = cmp
1545 // if t op
1546 // b BBf
1547 //
1548 // We cannot further ifcvt this block because the unconditional branch
1549 // will have to be predicated on the new condition, that will not be
1550 // available if cmp executes.
1551 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001552 }
Evan Chenge26c0912007-05-21 22:22:58 +00001553
Evan Cheng288f1542007-06-08 22:01:07 +00001554 RemoveExtraEdges(BBI);
1555
Evan Chengd0e66912007-05-23 07:23:16 +00001556 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001557 if (!IterIfcvt)
1558 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001559 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001560 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001561
1562 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001563 return true;
1564}
1565
Matthias Braun2c931792016-08-17 02:51:57 +00001566/// If convert a triangle sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001567bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001568 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001569 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1570 BBInfo *CvtBBI = &TrueBBI;
1571 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001572 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001573
Owen Anderson4f6bf042008-08-14 22:49:33 +00001574 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001575 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001576 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001577
Matthias Braun08f47042016-08-17 02:52:01 +00001578 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1579 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001580 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001581 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001582 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001583 BBI.IsAnalyzed = false;
1584 CvtBBI->IsAnalyzed = false;
1585 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001586 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001587
Matthias Braun08f47042016-08-17 02:52:01 +00001588 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001589 // Conservatively abort if-conversion if BB's address is taken.
1590 return false;
1591
Evan Cheng3a51c852007-06-16 09:34:52 +00001592 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001593 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001594 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001595
Evan Cheng3a51c852007-06-16 09:34:52 +00001596 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001597 if (ReverseBranchCondition(*CvtBBI)) {
1598 // BB has been changed, modify its predecessors (except for this
1599 // one) so they don't get ifcvt'ed based on bad intel.
Matthias Braun08f47042016-08-17 02:52:01 +00001600 for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001601 if (PBB == BBI.BB)
1602 continue;
1603 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1604 if (PBBI.IsEnqueued) {
1605 PBBI.IsAnalyzed = false;
1606 PBBI.IsEnqueued = false;
1607 }
Evan Chengadd97762007-06-14 23:34:09 +00001608 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001609 }
1610 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001611
Bob Wilson45814342010-06-19 05:33:57 +00001612 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001613 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001614 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001615 Redefs.addLiveIns(CvtMBB);
1616 Redefs.addLiveIns(NextMBB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001617
Andrew Trick276dd452013-10-14 20:45:17 +00001618 DontKill.clear();
1619
Craig Topperc0196b12014-04-14 00:51:57 +00001620 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001621 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001622
Manman Renb6819182014-01-29 23:18:47 +00001623 if (HasEarlyExit) {
Matthias Braun08f47042016-08-17 02:52:01 +00001624 // Get probabilities before modifying CvtMBB and BBI.BB.
1625 CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1626 CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1627 BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1628 BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
Manman Renb6819182014-01-29 23:18:47 +00001629 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001630
Matthias Braun08f47042016-08-17 02:52:01 +00001631 if (CvtMBB.pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001632 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001633 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001634 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001635 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001636
1637 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1638 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001639 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001640 } else {
1641 // Predicate the 'true' block after removing its branch.
Matthias Braun08f47042016-08-17 02:52:01 +00001642 CvtBBI->NonPredSize -= TII->RemoveBranch(CvtMBB);
1643 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001644
Evan Cheng0598b2d2007-06-18 22:44:57 +00001645 // Now merge the entry of the triangle with the true block.
1646 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001647 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001648 }
1649
Evan Cheng312b7232007-06-04 06:47:22 +00001650 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001651 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001652 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1653 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001654 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001655 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001656
Cong Houd97c1002015-12-01 05:29:22 +00001657 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
Matthias Braun08f47042016-08-17 02:52:01 +00001658 // NewNext = New_Prob(BBI.BB, NextMBB) =
1659 // Prob(BBI.BB, NextMBB) +
1660 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
Cong Houd97c1002015-12-01 05:29:22 +00001661 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
Matthias Braun08f47042016-08-17 02:52:01 +00001662 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1663 auto NewTrueBB = getNextBlock(*BBI.BB);
Cong Houd97c1002015-12-01 05:29:22 +00001664 auto NewNext = BBNext + BBCvt * CvtNext;
David Majnemer42531262016-08-12 03:55:06 +00001665 auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001666 if (NewTrueBBIter != BBI.BB->succ_end())
1667 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001668
1669 auto NewFalse = BBCvt * CvtFalse;
1670 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1671 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001672 }
Evan Cheng7783f822007-06-08 09:36:04 +00001673
1674 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001675 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001676 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001677 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001678 bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001679 if (!isFallThrough) {
1680 // Only merge them if the true block does not fallthrough to the false
1681 // block. By not merging them, we make it possible to iteratively
1682 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001683 if (!HasEarlyExit &&
Matthias Braun08f47042016-08-17 02:52:01 +00001684 NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
1685 !NextMBB.hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001686 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001687 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001688 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001689 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001690 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001691 }
Evan Cheng7783f822007-06-08 09:36:04 +00001692 // Mixed predicated and unpredicated code. This cannot be iteratively
1693 // predicated.
1694 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001695 }
Evan Chenge26c0912007-05-21 22:22:58 +00001696
Evan Cheng288f1542007-06-08 22:01:07 +00001697 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001698
Evan Chengd0e66912007-05-23 07:23:16 +00001699 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001700 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001701 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001702 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001703 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001704 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001705 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001706
1707 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001708 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001709}
1710
Kyle Butta8c73712016-08-24 21:34:27 +00001711/// Common code shared between diamond conversions.
1712/// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1713/// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1714/// and FalseBBI
1715/// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1716/// and \p FalseBBI
Kyle Butt092c4dd2016-08-29 18:27:12 +00001717/// \p RemoveBranch - Remove the common branch of the two blocks before
1718/// predicating. Only false for unanalyzable fallthrough
1719/// cases. The caller will replace the branch if necessary.
Kyle Butta8c73712016-08-24 21:34:27 +00001720/// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1721/// unanalyzable fallthrough
1722bool IfConverter::IfConvertDiamondCommon(
1723 BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1724 unsigned NumDups1, unsigned NumDups2,
1725 bool TClobbersPred, bool FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001726 bool RemoveBranch, bool MergeAddEdges) {
Evan Chenge26c0912007-05-21 22:22:58 +00001727
Evan Cheng51eb2c32007-06-18 08:37:25 +00001728 if (TrueBBI.IsDone || FalseBBI.IsDone ||
Kyle Butta8c73712016-08-24 21:34:27 +00001729 TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001730 // Something has changed. It's no longer safe to predicate these blocks.
1731 BBI.IsAnalyzed = false;
1732 TrueBBI.IsAnalyzed = false;
1733 FalseBBI.IsAnalyzed = false;
1734 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001735 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001736
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001737 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1738 // Conservatively abort if-conversion if either BB has its address taken.
1739 return false;
1740
Bob Wilson1e5da552010-06-29 00:55:23 +00001741 // Put the predicated instructions from the 'true' block before the
1742 // instructions from the 'false' block, unless the true block would clobber
1743 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001744 BBInfo *BBI1 = &TrueBBI;
1745 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001746 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001747 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001748 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001749 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1750 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001751
Evan Cheng3a51c852007-06-16 09:34:52 +00001752 // Figure out the more profitable ordering.
1753 bool DoSwap = false;
Kyle Butt6262ca32016-08-24 21:34:24 +00001754 if (TClobbersPred && !FClobbersPred)
Evan Cheng3a51c852007-06-16 09:34:52 +00001755 DoSwap = true;
Kyle Butte31cc842016-09-02 18:29:28 +00001756 else if (!TClobbersPred && !FClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001757 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001758 DoSwap = true;
Kyle Butte31cc842016-09-02 18:29:28 +00001759 } else if (TClobbersPred && FClobbersPred)
1760 llvm_unreachable("Predicate info cannot be clobbered by both sides.");
Evan Cheng3a51c852007-06-16 09:34:52 +00001761 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001762 std::swap(BBI1, BBI2);
1763 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001764 }
Evan Cheng79484222007-06-05 23:46:14 +00001765
Evan Cheng51eb2c32007-06-18 08:37:25 +00001766 // Remove the conditional branch from entry to the blocks.
1767 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1768
Matthias Braun08f47042016-08-17 02:52:01 +00001769 MachineBasicBlock &MBB1 = *BBI1->BB;
1770 MachineBasicBlock &MBB2 = *BBI2->BB;
1771
Krzysztof Parzyszeka003b762016-08-11 18:42:06 +00001772 // Initialize the Redefs:
1773 // - BB2 live-in regs need implicit uses before being redefined by BB1
1774 // instructions.
1775 // - BB1 live-out regs need implicit uses before being redefined by BB2
1776 // instructions. We start with BB1 live-ins so we have the live-out regs
1777 // after tracking the BB1 instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001778 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001779 Redefs.addLiveIns(MBB1);
1780 Redefs.addLiveIns(MBB2);
Evan Chengf128bdc2010-06-16 07:35:02 +00001781
Evan Cheng51eb2c32007-06-18 08:37:25 +00001782 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001783 // Skip dbg_value instructions
Matthias Braun08f47042016-08-17 02:52:01 +00001784 MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1785 MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001786 BBI1->NonPredSize -= NumDups1;
1787 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001788
1789 // Skip past the dups on each side separately since there may be
1790 // differing dbg_value entries.
1791 for (unsigned i = 0; i < NumDups1; ++DI1) {
1792 if (!DI1->isDebugValue())
1793 ++i;
1794 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001795 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001796 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001797 if (!DI2->isDebugValue())
1798 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001799 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001800
Matthias Braund616ccc2013-10-11 19:04:37 +00001801 // Compute a set of registers which must not be killed by instructions in BB1:
1802 // This is everything used+live in BB2 after the duplicated instructions. We
1803 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001804 DontKill.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001805 for (const MachineInstr &MI :
1806 make_range(MBB2.rbegin(), MachineBasicBlock::reverse_iterator(DI2)))
Matthias Braunb1e05582016-08-17 02:51:59 +00001807 DontKill.stepBackward(MI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001808
Matthias Braun08f47042016-08-17 02:52:01 +00001809 for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
Pete Cooper7605e372015-05-05 20:14:22 +00001810 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
Matthias Braunb1e05582016-08-17 02:51:59 +00001811 Redefs.stepForward(MI, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001812 }
Matthias Braun08f47042016-08-17 02:52:01 +00001813 BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1814 MBB2.erase(MBB2.begin(), DI2);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001815
Kyle Butt092c4dd2016-08-29 18:27:12 +00001816 // The branches have been checked to match, so it is safe to remove the branch
1817 // in BB1 and rely on the copy in BB2
1818#ifndef NDEBUG
1819 // Unanalyzable branches must match exactly. Check that now.
1820 if (!BBI1->IsBrAnalyzable)
1821 verifySameBranchInstructions(&MBB1, &MBB2);
1822#endif
1823 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001824 // Remove duplicated instructions.
Matthias Braun08f47042016-08-17 02:52:01 +00001825 DI1 = MBB1.end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001826 for (unsigned i = 0; i != NumDups2; ) {
1827 // NumDups2 only counted non-dbg_value instructions, so this won't
1828 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001829 assert(DI1 != MBB1.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001830 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001831 // skip dbg_value instructions
1832 if (!DI1->isDebugValue())
1833 ++i;
1834 }
Matthias Braun08f47042016-08-17 02:52:01 +00001835 MBB1.erase(DI1, MBB1.end());
Evan Cheng79484222007-06-05 23:46:14 +00001836
Matthias Braund616ccc2013-10-11 19:04:37 +00001837 // Kill flags in the true block for registers living into the false block
1838 // must be removed.
Matthias Braun08f47042016-08-17 02:52:01 +00001839 RemoveKills(MBB1.begin(), MBB1.end(), DontKill, *TRI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001840
Kyle Butta8c73712016-08-24 21:34:27 +00001841 DI2 = BBI2->BB->end();
Kyle Butt092c4dd2016-08-29 18:27:12 +00001842 // The branches have been checked to match. Skip over the branch in the false
1843 // block so that we don't try to predicate it.
1844 if (RemoveBranch)
1845 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1846 else {
1847 do {
1848 assert(DI2 != MBB2.begin());
1849 DI2--;
1850 } while (DI2->isBranch() || DI2->isDebugValue());
1851 DI2++;
1852 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001853 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001854 // NumDups2 only counted non-dbg_value instructions, so this won't
1855 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001856 assert(DI2 != MBB2.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001857 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001858 // skip dbg_value instructions
1859 if (!DI2->isDebugValue())
1860 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001861 }
Evan Cheng4266a792011-12-19 22:01:30 +00001862
1863 // Remember which registers would later be defined by the false block.
1864 // This allows us not to predicate instructions in the true block that would
1865 // later be re-defined. That is, rather than
1866 // subeq r0, r1, #1
1867 // addne r0, r1, #1
1868 // generate:
1869 // sub r0, r1, #1
1870 // addne r0, r1, #1
1871 SmallSet<unsigned, 4> RedefsByFalse;
1872 SmallSet<unsigned, 4> ExtUses;
Matthias Braun08f47042016-08-17 02:52:01 +00001873 if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1874 for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001875 if (FI.isDebugValue())
Evan Cheng4266a792011-12-19 22:01:30 +00001876 continue;
1877 SmallVector<unsigned, 4> Defs;
Matthias Braunb1e05582016-08-17 02:51:59 +00001878 for (const MachineOperand &MO : FI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001879 if (!MO.isReg())
1880 continue;
1881 unsigned Reg = MO.getReg();
1882 if (!Reg)
1883 continue;
1884 if (MO.isDef()) {
1885 Defs.push_back(Reg);
1886 } else if (!RedefsByFalse.count(Reg)) {
1887 // These are defined before ctrl flow reach the 'false' instructions.
1888 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001889 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1890 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001891 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001892 }
1893 }
1894
Matthias Braunb1e05582016-08-17 02:51:59 +00001895 for (unsigned Reg : Defs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001896 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001897 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1898 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001899 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001900 }
1901 }
1902 }
1903 }
1904
1905 // Predicate the 'true' block.
Matthias Braun08f47042016-08-17 02:52:01 +00001906 PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001907
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001908 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1909 // a non-predicated in BBI2, then we don't want to predicate the one from
1910 // BBI2. The reason is that if we merged these blocks, we would end up with
1911 // two predicated terminators in the same block.
Matthias Braun08f47042016-08-17 02:52:01 +00001912 if (!MBB2.empty() && (DI2 == MBB2.end())) {
1913 MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1914 MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1915 if (BBI1T != MBB1.end() && TII->isPredicated(*BBI1T) &&
1916 BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001917 --DI2;
1918 }
1919
Evan Cheng4266a792011-12-19 22:01:30 +00001920 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001921 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001922
Evan Cheng0598b2d2007-06-18 22:44:57 +00001923 // Merge the true block into the entry of the diamond.
Kyle Butta8c73712016-08-24 21:34:27 +00001924 MergeBlocks(BBI, *BBI1, MergeAddEdges);
1925 MergeBlocks(BBI, *BBI2, MergeAddEdges);
1926 return true;
1927}
1928
1929/// If convert an almost-diamond sub-CFG where the true
1930/// and false blocks share a common tail.
1931bool IfConverter::IfConvertForkedDiamond(
1932 BBInfo &BBI, IfcvtKind Kind,
1933 unsigned NumDups1, unsigned NumDups2,
1934 bool TClobbersPred, bool FClobbersPred) {
1935 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1936 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1937
1938 // Save the debug location for later.
1939 DebugLoc dl;
1940 MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1941 if (TIE != TrueBBI.BB->end())
1942 dl = TIE->getDebugLoc();
1943 // Removing branches from both blocks is safe, because we have already
1944 // determined that both blocks have the same branch instructions. The branch
1945 // will be added back at the end, unpredicated.
1946 if (!IfConvertDiamondCommon(
1947 BBI, TrueBBI, FalseBBI,
1948 NumDups1, NumDups2,
1949 TClobbersPred, FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001950 /* RemoveBranch */ true, /* MergeAddEdges */ true))
Kyle Butta8c73712016-08-24 21:34:27 +00001951 return false;
1952
1953 // Add back the branch.
1954 // Debug location saved above when removing the branch from BBI2
1955 TII->InsertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
1956 TrueBBI.BrCond, dl);
1957
1958 RemoveExtraEdges(BBI);
1959
1960 // Update block info.
1961 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1962 InvalidatePreds(*BBI.BB);
1963
1964 // FIXME: Must maintain LiveIns.
1965 return true;
1966}
1967
1968/// If convert a diamond sub-CFG.
1969bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1970 unsigned NumDups1, unsigned NumDups2,
1971 bool TClobbersPred, bool FClobbersPred) {
1972 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1973 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1974 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1975
1976 // True block must fall through or end with an unanalyzable terminator.
1977 if (!TailBB) {
1978 if (blockAlwaysFallThrough(TrueBBI))
1979 TailBB = FalseBBI.TrueBB;
1980 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1981 }
1982
1983 if (!IfConvertDiamondCommon(
1984 BBI, TrueBBI, FalseBBI,
1985 NumDups1, NumDups2,
Kyle Butt86999212016-09-02 18:29:26 +00001986 TClobbersPred, FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001987 /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
Kyle Butta8c73712016-08-24 21:34:27 +00001988 /* MergeAddEdges */ TailBB == nullptr))
1989 return false;
Evan Cheng30565992007-06-06 00:57:55 +00001990
Bob Wilson2371f4f2009-05-13 23:25:24 +00001991 // If the if-converted block falls through or unconditionally branches into
1992 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001993 // fold the tail block in as well. Otherwise, unless it falls through to the
1994 // tail, add a unconditional branch to it.
1995 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001996 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001997 bool CanMergeTail = !TailBBI.HasFallThrough &&
1998 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001999 // The if-converted block can still have a predicated terminator
2000 // (e.g. a predicated return). If that is the case, we cannot merge
2001 // it with the tail block.
2002 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002003 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002004 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00002005 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
2006 // check if there are any other predecessors besides those.
2007 unsigned NumPreds = TailBB->pred_size();
2008 if (NumPreds > 1)
2009 CanMergeTail = false;
2010 else if (NumPreds == 1 && CanMergeTail) {
2011 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
Kyle Butta8c73712016-08-24 21:34:27 +00002012 if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
Bob Wilson1e5da552010-06-29 00:55:23 +00002013 CanMergeTail = false;
2014 }
2015 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00002016 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00002017 TailBBI.IsDone = true;
2018 } else {
Cong Houd97c1002015-12-01 05:29:22 +00002019 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Matthias Braun08f47042016-08-17 02:52:01 +00002020 InsertUncondBranch(*BBI.BB, *TailBB, TII);
Evan Cheng0598b2d2007-06-18 22:44:57 +00002021 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00002022 }
Evan Chenge26c0912007-05-21 22:22:58 +00002023 }
2024
Bob Wilson1e5da552010-06-29 00:55:23 +00002025 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
2026 // which can happen here if TailBB is unanalyzable and is merged, so
2027 // explicitly remove BBI1 and BBI2 as successors.
Kyle Butta8c73712016-08-24 21:34:27 +00002028 BBI.BB->removeSuccessor(TrueBBI.BB);
2029 BBI.BB->removeSuccessor(FalseBBI.BB, /* NormalizeSuccessProbs */ true);
Evan Cheng288f1542007-06-08 22:01:07 +00002030 RemoveExtraEdges(BBI);
2031
Evan Cheng79484222007-06-05 23:46:14 +00002032 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00002033 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00002034 InvalidatePreds(*BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00002035
2036 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00002037 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00002038}
2039
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002040static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00002041 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00002042 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002043 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00002044 return false;
2045
Matthias Braunb1e05582016-08-17 02:51:59 +00002046 for (const MachineOperand &MO : MI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00002047 if (!MO.isReg())
2048 continue;
2049 unsigned Reg = MO.getReg();
2050 if (!Reg)
2051 continue;
2052 if (MO.isDef() && !LaterRedefs.count(Reg))
2053 return false;
2054 }
2055
2056 return true;
2057}
2058
Matthias Braun2c931792016-08-17 02:51:57 +00002059/// Predicate instructions from the start of the block to the specified end with
2060/// the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00002061void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00002062 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00002063 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00002064 SmallSet<unsigned, 4> *LaterRedefs) {
2065 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002066 bool MaySpec = LaterRedefs != nullptr;
Matthias Braunb1e05582016-08-17 02:51:59 +00002067 for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002068 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00002069 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00002070 // It may be possible not to predicate an instruction if it's the 'true'
2071 // side of a diamond and the 'false' side may re-define the instruction's
2072 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00002073 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00002074 AnyUnpred = true;
2075 continue;
2076 }
2077 // If any instruction is predicated, then every instruction after it must
2078 // be predicated.
2079 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002080 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00002081#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002082 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00002083#endif
Craig Topperc0196b12014-04-14 00:51:57 +00002084 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00002085 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002086
Bob Wilson45814342010-06-19 05:33:57 +00002087 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002088 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002089 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00002090 }
Evan Chengd0e66912007-05-23 07:23:16 +00002091
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002092 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00002093
Evan Cheng92fb5452007-06-15 07:36:12 +00002094 BBI.IsAnalyzed = false;
2095 BBI.NonPredSize = 0;
2096
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002097 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00002098 if (AnyUnpred)
2099 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00002100}
2101
Matthias Braun2c931792016-08-17 02:51:57 +00002102/// Copy and predicate instructions from source BB to the destination block.
2103/// Skip end of block branches if IgnoreBr is true.
Evan Cheng92fb5452007-06-15 07:36:12 +00002104void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00002105 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00002106 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00002107 MachineFunction &MF = *ToBBI.BB->getParent();
2108
Matthias Braun08f47042016-08-17 02:52:01 +00002109 MachineBasicBlock &FromMBB = *FromBBI.BB;
2110 for (MachineInstr &I : FromMBB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00002111 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002112 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00002113 break;
2114
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002115 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00002116 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00002117 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002118 unsigned ExtraPredCost = TII->getPredicationCost(I);
2119 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00002120 if (NumCycles > 1)
2121 ToBBI.ExtraCost += NumCycles-1;
2122 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00002123
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00002124 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002125 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00002126#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002127 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00002128#endif
Craig Topperc0196b12014-04-14 00:51:57 +00002129 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00002130 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002131 }
2132
Bob Wilson45814342010-06-19 05:33:57 +00002133 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002134 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002135 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00002136
2137 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00002138 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00002139 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00002140 }
2141
Bob Wilson1e5da552010-06-29 00:55:23 +00002142 if (!IgnoreBr) {
Matthias Braun08f47042016-08-17 02:52:01 +00002143 std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2144 FromMBB.succ_end());
2145 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00002146 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00002147
Matthias Braunb1e05582016-08-17 02:51:59 +00002148 for (MachineBasicBlock *Succ : Succs) {
Bob Wilson1e5da552010-06-29 00:55:23 +00002149 // Fallthrough edge can't be transferred.
2150 if (Succ == FallThrough)
2151 continue;
2152 ToBBI.BB->addSuccessor(Succ);
2153 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00002154 }
2155
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002156 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2157 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002158
2159 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2160 ToBBI.IsAnalyzed = false;
2161
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002162 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00002163}
2164
Matthias Braun2c931792016-08-17 02:51:57 +00002165/// Move all instructions from FromBB to the end of ToBB. This will leave
2166/// FromBB as an empty block, so remove all of its successor edges except for
2167/// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
2168/// being moved, add those successor edges to ToBBI.
Bob Wilson1e5da552010-06-29 00:55:23 +00002169void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Matthias Braun08f47042016-08-17 02:52:01 +00002170 MachineBasicBlock &FromMBB = *FromBBI.BB;
2171 assert(!FromMBB.hasAddressTaken() &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00002172 "Removing a BB whose address is taken!");
2173
Matthias Braun08f47042016-08-17 02:52:01 +00002174 // In case FromMBB contains terminators (e.g. return instruction),
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002175 // first move the non-terminator instructions, then the terminators.
Matthias Braun08f47042016-08-17 02:52:01 +00002176 MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002177 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
Matthias Braun08f47042016-08-17 02:52:01 +00002178 ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002179
2180 // If FromBB has non-predicated terminator we should copy it at the end.
Matthias Braun08f47042016-08-17 02:52:01 +00002181 if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002182 ToTI = ToBBI.BB->end();
Matthias Braun08f47042016-08-17 02:52:01 +00002183 ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
Evan Chengd0e66912007-05-23 07:23:16 +00002184
Cong Houb9e8d482015-12-17 01:29:08 +00002185 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2186 // unknown probabilities into known ones.
2187 // FIXME: This usage is too tricky and in the future we would like to
2188 // eliminate all unknown probabilities in MBB.
2189 ToBBI.BB->normalizeSuccProbs();
2190
Matthias Braun08f47042016-08-17 02:52:01 +00002191 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
2192 FromMBB.succ_end());
2193 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00002194 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Matthias Braun08f47042016-08-17 02:52:01 +00002195 // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2196 // AddEdges is true and FromMBB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00002197 auto To2FromProb = BranchProbability::getZero();
Matthias Braun08f47042016-08-17 02:52:01 +00002198 if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
2199 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
2200 // Set the edge probability from ToBBI.BB to FromMBB to zero to avoid the
Cong Houd97c1002015-12-01 05:29:22 +00002201 // edge probability being merged to other edges when this edge is removed
2202 // later.
Matthias Braun08f47042016-08-17 02:52:01 +00002203 ToBBI.BB->setSuccProbability(find(ToBBI.BB->successors(), &FromMBB),
David Majnemer42531262016-08-12 03:55:06 +00002204 BranchProbability::getZero());
Cong Houd97c1002015-12-01 05:29:22 +00002205 }
2206
Matthias Braunb1e05582016-08-17 02:51:59 +00002207 for (MachineBasicBlock *Succ : FromSuccs) {
Evan Cheng288f1542007-06-08 22:01:07 +00002208 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00002209 if (Succ == FallThrough)
2210 continue;
Cong Houd40105d2015-09-18 20:22:41 +00002211
Cong Houd97c1002015-12-01 05:29:22 +00002212 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00002213 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002214 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
Matthias Braun08f47042016-08-17 02:52:01 +00002215 // which is a portion of the edge probability from FromMBB to Succ. The
2216 // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
Cong Houd97c1002015-12-01 05:29:22 +00002217 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
Matthias Braun08f47042016-08-17 02:52:01 +00002218 NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002219
Matthias Braun08f47042016-08-17 02:52:01 +00002220 // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2221 // only happens when if-converting a diamond CFG and FromMBB is the
2222 // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
2223 // could just use the probabilities on FromMBB's out-edges when adding
Cong Houd97c1002015-12-01 05:29:22 +00002224 // new successors.
2225 if (!To2FromProb.isZero())
2226 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00002227 }
2228
Matthias Braun08f47042016-08-17 02:52:01 +00002229 FromMBB.removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002230
2231 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002232 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00002233 // probability of this edge by adding NewProb to it. An example is shown
Matthias Braun08f47042016-08-17 02:52:01 +00002234 // below, in which A is ToBBI.BB and B is FromMBB. In this case we
Cong Houd97c1002015-12-01 05:29:22 +00002235 // don't have to set C as A's successor as it already is. We only need to
2236 // update the edge probability on A->C. Note that B will not be
2237 // immediately removed from A's successors. It is possible that B->D is
2238 // not removed either if D is a fallthrough of B. Later the edge A->D
2239 // (generated here) and B->D will be combined into one edge. To maintain
2240 // correct edge probability of this combined edge, we need to set the edge
2241 // probability of A->B to zero, which is already done above. The edge
2242 // probability on A->D is calculated by scaling the original probability
2243 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00002244 //
2245 // Before ifcvt: After ifcvt (assume B->D is kept):
2246 //
2247 // A A
2248 // /| /|\
2249 // / B / B|
2250 // | /| | ||
2251 // |/ | | |/
2252 // C D C D
2253 //
2254 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00002255 ToBBI.BB->setSuccProbability(
David Majnemer42531262016-08-12 03:55:06 +00002256 find(ToBBI.BB->successors(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00002257 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002258 else
Cong Houd97c1002015-12-01 05:29:22 +00002259 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002260 }
Evan Chengbe9859e2007-06-07 02:12:15 +00002261 }
2262
Bob Wilson2371f4f2009-05-13 23:25:24 +00002263 // Now FromBBI always falls through to the next block!
Matthias Braun08f47042016-08-17 02:52:01 +00002264 if (NBB && !FromMBB.isSuccessor(NBB))
2265 FromMBB.addSuccessor(NBB);
Evan Cheng288f1542007-06-08 22:01:07 +00002266
Cong Houc1069892015-12-13 09:26:17 +00002267 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2268 // we've done above.
2269 ToBBI.BB->normalizeSuccProbs();
2270
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002271 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002272 FromBBI.Predicate.clear();
2273
Evan Chengd0e66912007-05-23 07:23:16 +00002274 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002275 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00002276 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00002277 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002278 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00002279 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00002280
Evan Cheng4dd31a72007-06-11 22:26:22 +00002281 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00002282 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00002283 ToBBI.IsAnalyzed = false;
2284 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00002285}
Akira Hatanaka4a616192015-06-08 18:50:43 +00002286
2287FunctionPass *
2288llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00002289 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00002290}