blob: 8b87aa16b8193c12dee3522e0e686652470a2577 [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;
Matthias Braun8b38ffa2016-10-24 23:23:02 +0000187 std::function<bool(const MachineFunction &)> PredicateFtor;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000188
Evan Chengf5e53a52007-05-16 02:00:57 +0000189 public:
190 static char ID;
Matthias Braun8b38ffa2016-10-24 23:23:02 +0000191 IfConverter(std::function<bool(const MachineFunction &)> 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:
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +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) {
Matthias Braun8b38ffa2016-10-24 23:23:02 +0000324 if (skipFunction(*MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000325 return false;
326
Eric Christopher3d4276f2015-01-27 07:31:29 +0000327 const TargetSubtargetInfo &ST = MF.getSubtarget();
328 TLI = ST.getTargetLowering();
329 TII = ST.getInstrInfo();
330 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000331 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000332 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000333 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000334 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000335
Evan Chengf5e53a52007-05-16 02:00:57 +0000336 if (!TII) return false;
337
Evan Chengc5adcca2012-06-08 21:53:50 +0000338 PreRegAlloc = MRI->isSSA();
339
340 bool BFChange = false;
341 if (!PreRegAlloc) {
342 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000343 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000344 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000345 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000346 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000347
David Greene72e47cd2010-01-04 22:02:01 +0000348 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000349 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000350
351 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000352 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000353 return false;
354 }
David Greene72e47cd2010-01-04 22:02:01 +0000355 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000356
Evan Chengf5e53a52007-05-16 02:00:57 +0000357 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000358 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000359
Justin Lebar3a7bc572016-02-22 17:51:28 +0000360 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000361 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000362 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
363 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
364 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000365 // Do an initial analysis for each basic block and find all the potential
366 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000367 bool Change = false;
368 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000369 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000370 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000371 Tokens.pop_back();
372 BBInfo &BBI = Token->BBI;
373 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000374 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000375 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000376
Evan Cheng4dd31a72007-06-11 22:26:22 +0000377 // If the block has been evicted out of the queue or it has already been
378 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000379 if (BBI.IsDone)
380 BBI.IsEnqueued = false;
381 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000382 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000383
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000384 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000385
Evan Cheng312b7232007-06-04 06:47:22 +0000386 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000387 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000388 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000389 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000390 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000391 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000392 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000393 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
394 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000395 << "): BB#" << BBI.BB->getNumber() << " ("
396 << ((Kind == ICSimpleFalse)
397 ? BBI.FalseBB->getNumber()
398 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000399 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000400 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000401 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000402 if (isFalse) ++NumSimpleFalse;
403 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000404 }
Evan Cheng312b7232007-06-04 06:47:22 +0000405 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000406 }
Evan Chengd0e66912007-05-23 07:23:16 +0000407 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000408 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000409 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000410 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000411 bool isFalse = Kind == ICTriangleFalse;
412 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000413 if (DisableTriangle && !isFalse && !isRev) break;
414 if (DisableTriangleR && !isFalse && isRev) break;
415 if (DisableTriangleF && isFalse && !isRev) break;
416 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000417 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000418 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000419 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000420 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000421 DEBUG(dbgs() << " rev");
422 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000423 << BBI.TrueBB->getNumber() << ",F:"
424 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000425 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000426 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000427 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000428 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000429 if (isRev) ++NumTriangleFRev;
430 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000431 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000432 if (isRev) ++NumTriangleRev;
433 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000434 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000435 }
Evan Chengd0e66912007-05-23 07:23:16 +0000436 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000437 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000438 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000439 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000440 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000441 << BBI.TrueBB->getNumber() << ",F:"
442 << BBI.FalseBB->getNumber() << ") ");
Kyle Butt6262ca32016-08-24 21:34:24 +0000443 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
444 Token->TClobbersPred,
445 Token->FClobbersPred);
David Greene72e47cd2010-01-04 22:02:01 +0000446 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000447 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000448 break;
449 }
Kyle Butta8c73712016-08-24 21:34:27 +0000450 case ICForkedDiamond: {
451 if (DisableForkedDiamond) break;
452 DEBUG(dbgs() << "Ifcvt (Forked Diamond): BB#"
453 << BBI.BB->getNumber() << " (T:"
454 << BBI.TrueBB->getNumber() << ",F:"
455 << BBI.FalseBB->getNumber() << ") ");
456 RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
457 Token->TClobbersPred,
458 Token->FClobbersPred);
459 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
460 if (RetVal) ++NumForkedDiamonds;
461 break;
462 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000463 }
464
Evan Cheng312b7232007-06-04 06:47:22 +0000465 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000466
Evan Cheng92fb5452007-06-15 07:36:12 +0000467 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
468 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
469 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000470 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000471 }
Evan Chengd0e66912007-05-23 07:23:16 +0000472
Evan Chengd0e66912007-05-23 07:23:16 +0000473 if (!Change)
474 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000475 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000476 }
Evan Cheng478b8052007-05-18 01:55:58 +0000477
Evan Cheng3a51c852007-06-16 09:34:52 +0000478 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000479 BBAnalysis.clear();
480
Evan Chengcf9e8a92010-06-18 22:17:13 +0000481 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000482 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000483 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000484 getAnalysisIfAvailable<MachineModuleInfo>());
485 }
486
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000487 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000488 return MadeChange;
489}
490
Matthias Braun2c931792016-08-17 02:51:57 +0000491/// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000492static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000493 MachineBasicBlock *TrueBB) {
Matthias Braunb1e05582016-08-17 02:51:59 +0000494 for (MachineBasicBlock *SuccBB : BB->successors()) {
Evan Cheng0f745da2007-05-18 00:20:58 +0000495 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000496 return SuccBB;
497 }
Craig Topperc0196b12014-04-14 00:51:57 +0000498 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000499}
500
Matthias Braun2c931792016-08-17 02:51:57 +0000501/// Reverse the condition of the end of the block branch. Swap block's 'true'
502/// and 'false' successors.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000503bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000504 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000505 if (!TII->reverseBranchCondition(BBI.BrCond)) {
506 TII->removeBranch(*BBI.BB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000507 TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000508 std::swap(BBI.TrueBB, BBI.FalseBB);
509 return true;
510 }
511 return false;
512}
513
Matthias Braun2c931792016-08-17 02:51:57 +0000514/// Returns the next block in the function blocks ordering. If it is the end,
515/// returns NULL.
Matthias Braun08f47042016-08-17 02:52:01 +0000516static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
517 MachineFunction::iterator I = MBB.getIterator();
518 MachineFunction::iterator E = MBB.getParent()->end();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000519 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000520 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000521 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000522}
523
Matthias Braun2c931792016-08-17 02:51:57 +0000524/// Returns true if the 'true' block (along with its predecessor) forms a valid
525/// simple shape for ifcvt. It also returns the number of instructions that the
526/// ifcvt would need to duplicate if performed in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000527bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000528 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000529 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000530 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000531 return false;
532
Evan Chenga955c022007-06-19 21:45:13 +0000533 if (TrueBBI.IsBrAnalyzable)
534 return false;
535
Evan Cheng23402fc2007-06-15 21:18:05 +0000536 if (TrueBBI.BB->pred_size() > 1) {
537 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000538 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000539 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000540 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000541 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000542 }
543
Evan Chenga955c022007-06-19 21:45:13 +0000544 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000545}
546
Matthias Braun2c931792016-08-17 02:51:57 +0000547/// Returns true if the 'true' and 'false' blocks (along with their common
548/// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
549/// true, it checks if 'true' block's false branch branches to the 'false' block
550/// rather than the other way around. It also returns the number of instructions
551/// that the ifcvt would need to duplicate if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000552bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000553 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000554 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000555 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000556 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000557 return false;
558
Evan Cheng23402fc2007-06-15 21:18:05 +0000559 if (TrueBBI.BB->pred_size() > 1) {
560 if (TrueBBI.CannotBeCopied)
561 return false;
562
Evan Cheng92fb5452007-06-15 07:36:12 +0000563 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000564 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000565 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000566 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000567 --Size;
568 else {
569 MachineBasicBlock *FExit = FalseBranch
570 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
571 if (FExit)
572 // Require a conditional branch
573 ++Size;
574 }
575 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000576 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000577 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000578 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000579 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000580
Evan Cheng7783f822007-06-08 09:36:04 +0000581 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
582 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000583 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000584 if (++I == TrueBBI.BB->getParent()->end())
585 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000586 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000587 }
Evan Cheng7783f822007-06-08 09:36:04 +0000588 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000589}
590
Kyle Butt4f0e2872016-08-06 01:52:33 +0000591/// Count duplicated instructions and move the iterators to show where they
592/// are.
593/// @param TIB True Iterator Begin
594/// @param FIB False Iterator Begin
595/// These two iterators initially point to the first instruction of the two
596/// blocks, and finally point to the first non-shared instruction.
597/// @param TIE True Iterator End
598/// @param FIE False Iterator End
599/// These two iterators initially point to End() for the two blocks() and
600/// finally point to the first shared instruction in the tail.
601/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
602/// two blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000603/// @param Dups1 count of duplicated instructions at the beginning of the 2
604/// blocks.
605/// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
606/// @param SkipUnconditionalBranches if true, Don't make sure that
607/// unconditional branches at the end of the blocks are the same. True is
608/// passed when the blocks are analyzable to allow for fallthrough to be
609/// handled.
610/// @return false if the shared portion prevents if conversion.
611bool IfConverter::CountDuplicatedInstructions(
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000612 MachineBasicBlock::iterator &TIB,
613 MachineBasicBlock::iterator &FIB,
614 MachineBasicBlock::iterator &TIE,
615 MachineBasicBlock::iterator &FIE,
616 unsigned &Dups1, unsigned &Dups2,
617 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
Kyle Butt6262ca32016-08-24 21:34:24 +0000618 bool SkipUnconditionalBranches) const {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000619
Bob Wilsone1961fe2010-10-26 00:02:24 +0000620 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000621 // Skip dbg_value instructions. These do not count.
Florian Hahn3c8b8c92016-12-16 11:10:26 +0000622 TIB = skipDebugInstructionsForward(TIB, TIE);
Florian Hahn3c8b8c92016-12-16 11:10:26 +0000623 FIB = skipDebugInstructionsForward(FIB, FIE);
Kyle Buttc4614b32017-01-26 20:02:47 +0000624 if (TIB == TIE || FIB == FIE)
Kyle Buttfe916822016-08-06 01:52:31 +0000625 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000626 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000627 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000628 // A pred-clobbering instruction in the shared portion prevents
629 // if-conversion.
630 std::vector<MachineOperand> PredDefs;
631 if (TII->DefinesPredicate(*TIB, PredDefs))
632 return false;
Kyle Butt93e94e82016-09-02 01:20:06 +0000633 // If we get all the way to the branch instructions, don't count them.
634 if (!TIB->isBranch())
635 ++Dups1;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000636 ++TIB;
637 ++FIB;
638 }
639
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000640 // Check for already containing all of the block.
641 if (TIB == TIE || FIB == FIE)
Kyle Butt6262ca32016-08-24 21:34:24 +0000642 return true;
Kyle Buttd76755e2016-08-18 22:09:23 +0000643 // Now, in preparation for counting duplicate instructions at the ends of the
Kyle Buttc4614b32017-01-26 20:02:47 +0000644 // blocks, switch to reverse_iterators. Note that getReverse() returns an
645 // iterator that points to the same instruction, unlike std::reverse_iterator.
646 // We have to do our own shifting so that we get the same range.
647 MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
648 MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
649 const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
650 const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
Kyle Buttd76755e2016-08-18 22:09:23 +0000651
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000652 if (!TBB.succ_empty() || !FBB.succ_empty()) {
Kyle Butt6262ca32016-08-24 21:34:24 +0000653 if (SkipUnconditionalBranches) {
Kyle Buttc4614b32017-01-26 20:02:47 +0000654 while (RTIE != RTIB && RTIE->isUnconditionalBranch())
655 ++RTIE;
656 while (RFIE != RFIB && RFIE->isUnconditionalBranch())
657 ++RFIE;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000658 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000659 }
660
Bob Wilsone1961fe2010-10-26 00:02:24 +0000661 // Count duplicate instructions at the ends of the blocks.
Kyle Buttc4614b32017-01-26 20:02:47 +0000662 while (RTIE != RTIB && RFIE != RFIB) {
Bob Wilsone1961fe2010-10-26 00:02:24 +0000663 // Skip dbg_value instructions. These do not count.
Kyle Buttc4614b32017-01-26 20:02:47 +0000664 // Note that these are reverse iterators going forward.
665 RTIE = skipDebugInstructionsForward(RTIE, RTIB);
666 RFIE = skipDebugInstructionsForward(RFIE, RFIB);
667 if (RTIE == RTIB || RFIE == RFIB)
Kyle Buttfe916822016-08-06 01:52:31 +0000668 break;
Kyle Buttc4614b32017-01-26 20:02:47 +0000669 if (!RTIE->isIdenticalTo(*RFIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000670 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000671 // We have to verify that any branch instructions are the same, and then we
672 // don't count them toward the # of duplicate instructions.
Kyle Buttc4614b32017-01-26 20:02:47 +0000673 if (!RTIE->isBranch())
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000674 ++Dups2;
Kyle Buttc4614b32017-01-26 20:02:47 +0000675 ++RTIE;
676 ++RFIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000677 }
Kyle Buttc4614b32017-01-26 20:02:47 +0000678 TIE = std::next(RTIE.getReverse());
679 FIE = std::next(RFIE.getReverse());
Kyle Butt6262ca32016-08-24 21:34:24 +0000680 return true;
681}
682
683/// RescanInstructions - Run ScanInstructions on a pair of blocks.
684/// @param TIB - True Iterator Begin, points to first non-shared instruction
685/// @param FIB - False Iterator Begin, points to first non-shared instruction
686/// @param TIE - True Iterator End, points past last non-shared instruction
687/// @param FIE - False Iterator End, points past last non-shared instruction
688/// @param TrueBBI - BBInfo to update for the true block.
689/// @param FalseBBI - BBInfo to update for the false block.
690/// @returns - false if either block cannot be predicated or if both blocks end
691/// with a predicate-clobbering instruction.
692bool IfConverter::RescanInstructions(
693 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
694 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
695 BBInfo &TrueBBI, BBInfo &FalseBBI) const {
696 bool BranchUnpredicable = true;
697 TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
698 ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
699 if (TrueBBI.IsUnpredicable)
700 return false;
701 ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
702 if (FalseBBI.IsUnpredicable)
703 return false;
704 if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
705 return false;
706 return true;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000707}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000708
Kyle Butt092c4dd2016-08-29 18:27:12 +0000709#ifndef NDEBUG
710static void verifySameBranchInstructions(
711 MachineBasicBlock *MBB1,
712 MachineBasicBlock *MBB2) {
Kyle Buttc4614b32017-01-26 20:02:47 +0000713 const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
714 const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
715 MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
716 MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
717 while (E1 != B1 && E2 != B2) {
718 skipDebugInstructionsForward(E1, B1);
719 skipDebugInstructionsForward(E2, B2);
720 if (E1 == B1 && E2 == B2)
Kyle Butt092c4dd2016-08-29 18:27:12 +0000721 break;
722
Kyle Buttc4614b32017-01-26 20:02:47 +0000723 if (E1 == B1) {
Kyle Butt092c4dd2016-08-29 18:27:12 +0000724 assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
725 break;
726 }
Kyle Buttc4614b32017-01-26 20:02:47 +0000727 if (E2 == B2) {
Kyle Butt092c4dd2016-08-29 18:27:12 +0000728 assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
729 break;
730 }
731
732 if (E1->isBranch() || E2->isBranch())
733 assert(E1->isIdenticalTo(*E2) &&
734 "Branch mis-match, branch instructions don't match.");
735 else
736 break;
Kyle Buttc4614b32017-01-26 20:02:47 +0000737 ++E1;
738 ++E2;
Kyle Butt092c4dd2016-08-29 18:27:12 +0000739 }
740}
741#endif
742
Kyle Butta8c73712016-08-24 21:34:27 +0000743/// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
744/// with their common predecessor) form a diamond if a common tail block is
745/// extracted.
746/// While not strictly a diamond, this pattern would form a diamond if
747/// tail-merging had merged the shared tails.
748/// EBB
749/// _/ \_
750/// | |
751/// TBB FBB
752/// / \ / \
753/// FalseBB TrueBB FalseBB
754/// Currently only handles analyzable branches.
755/// Specifically excludes actual diamonds to avoid overlap.
756bool IfConverter::ValidForkedDiamond(
757 BBInfo &TrueBBI, BBInfo &FalseBBI,
758 unsigned &Dups1, unsigned &Dups2,
759 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
760 Dups1 = Dups2 = 0;
761 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
762 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
763 return false;
764
765 if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
766 return false;
767 // Don't IfConvert blocks that can't be folded into their predecessor.
768 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
769 return false;
770
771 // This function is specifically looking for conditional tails, as
772 // unconditional tails are already handled by the standard diamond case.
773 if (TrueBBI.BrCond.size() == 0 ||
774 FalseBBI.BrCond.size() == 0)
775 return false;
776
777 MachineBasicBlock *TT = TrueBBI.TrueBB;
778 MachineBasicBlock *TF = TrueBBI.FalseBB;
779 MachineBasicBlock *FT = FalseBBI.TrueBB;
780 MachineBasicBlock *FF = FalseBBI.FalseBB;
781
782 if (!TT)
783 TT = getNextBlock(*TrueBBI.BB);
784 if (!TF)
785 TF = getNextBlock(*TrueBBI.BB);
786 if (!FT)
787 FT = getNextBlock(*FalseBBI.BB);
788 if (!FF)
789 FF = getNextBlock(*FalseBBI.BB);
790
791 if (!TT || !TF)
792 return false;
793
794 // Check successors. If they don't match, bail.
795 if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
796 return false;
797
798 bool FalseReversed = false;
799 if (TF == FT && TT == FF) {
800 // If the branches are opposing, but we can't reverse, don't do it.
801 if (!FalseBBI.IsBrReversible)
802 return false;
803 FalseReversed = true;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000804 reverseBranchCondition(FalseBBI);
Kyle Butta8c73712016-08-24 21:34:27 +0000805 }
806 auto UnReverseOnExit = make_scope_exit([&]() {
807 if (FalseReversed)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000808 reverseBranchCondition(FalseBBI);
Kyle Butta8c73712016-08-24 21:34:27 +0000809 });
810
811 // Count duplicate instructions at the beginning of the true and false blocks.
812 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
813 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
814 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
815 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
816 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
817 *TrueBBI.BB, *FalseBBI.BB,
818 /* SkipUnconditionalBranches */ true))
819 return false;
820
821 TrueBBICalc.BB = TrueBBI.BB;
822 FalseBBICalc.BB = FalseBBI.BB;
823 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
824 return false;
825
826 // The size is used to decide whether to if-convert, and the shared portions
827 // are subtracted off. Because of the subtraction, we just use the size that
828 // was calculated by the original ScanInstructions, as it is correct.
829 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
830 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
831 return true;
832}
833
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000834/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
835/// with their common predecessor) forms a valid diamond shape for ifcvt.
Kyle Butt6262ca32016-08-24 21:34:24 +0000836bool IfConverter::ValidDiamond(
837 BBInfo &TrueBBI, BBInfo &FalseBBI,
838 unsigned &Dups1, unsigned &Dups2,
839 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000840 Dups1 = Dups2 = 0;
841 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
842 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
843 return false;
844
845 MachineBasicBlock *TT = TrueBBI.TrueBB;
846 MachineBasicBlock *FT = FalseBBI.TrueBB;
847
848 if (!TT && blockAlwaysFallThrough(TrueBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000849 TT = getNextBlock(*TrueBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000850 if (!FT && blockAlwaysFallThrough(FalseBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000851 FT = getNextBlock(*FalseBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000852 if (TT != FT)
853 return false;
854 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
855 return false;
856 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
857 return false;
858
859 // FIXME: Allow true block to have an early exit?
Kyle Butt6262ca32016-08-24 21:34:24 +0000860 if (TrueBBI.FalseBB || FalseBBI.FalseBB)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000861 return false;
862
863 // Count duplicate instructions at the beginning and end of the true and
864 // false blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000865 // Skip unconditional branches only if we are considering an analyzable
866 // diamond. Otherwise the branches must be the same.
867 bool SkipUnconditionalBranches =
868 TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000869 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
870 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
871 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
872 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
Kyle Butt6262ca32016-08-24 21:34:24 +0000873 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
874 *TrueBBI.BB, *FalseBBI.BB,
875 SkipUnconditionalBranches))
876 return false;
877
878 TrueBBICalc.BB = TrueBBI.BB;
879 FalseBBICalc.BB = FalseBBI.BB;
880 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
881 return false;
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;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000887 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000888}
889
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000890/// AnalyzeBranches - Look at the branches at the end of a block to determine if
891/// the block is predicable.
892void IfConverter::AnalyzeBranches(BBInfo &BBI) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000893 if (BBI.IsDone)
894 return;
895
Craig Topperc0196b12014-04-14 00:51:57 +0000896 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000897 BBI.BrCond.clear();
898 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000899 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Kyle Butta8c73712016-08-24 21:34:27 +0000900 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
901 BBI.IsBrReversible = (RevCond.size() == 0) ||
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000902 !TII->reverseBranchCondition(RevCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000903 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000904
905 if (BBI.BrCond.size()) {
906 // No false branch. This BB must end with a conditional branch and a
907 // fallthrough.
908 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000909 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000910 if (!BBI.FalseBB) {
911 // Malformed bcc? True and false blocks are the same?
912 BBI.IsUnpredicable = true;
Evan Chengb9bff582009-06-15 21:24:34 +0000913 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000914 }
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000915}
Evan Cheng4dd31a72007-06-11 22:26:22 +0000916
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000917/// ScanInstructions - Scan all the instructions in the block to determine if
918/// the block is predicable. In most cases, that means all the instructions
919/// in the block are isPredicable(). Also checks if the block contains any
920/// instruction which can clobber a predicate (e.g. condition code register).
921/// If so, the block is not predicable unless it's the last instruction.
922void IfConverter::ScanInstructions(BBInfo &BBI,
923 MachineBasicBlock::iterator &Begin,
Kyle Butt6262ca32016-08-24 21:34:24 +0000924 MachineBasicBlock::iterator &End,
925 bool BranchUnpredicable) const {
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000926 if (BBI.IsDone || BBI.IsUnpredicable)
927 return;
928
929 bool AlreadyPredicated = !BBI.Predicate.empty();
930
Evan Cheng4dd31a72007-06-11 22:26:22 +0000931 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000932 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000933 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000934 BBI.ClobbersPred = false;
Matthias Braunb1e05582016-08-17 02:51:59 +0000935 for (MachineInstr &MI : make_range(Begin, End)) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000936 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000937 continue;
938
Justin Lebar7dba2e02016-04-15 01:38:41 +0000939 // It's unsafe to duplicate convergent instructions in this context, so set
940 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
941 // following CFG, which is subject to our "simple" transformation.
942 //
943 // BB0 // if (c1) goto BB1; else goto BB2;
944 // / \
945 // BB1 |
946 // | BB2 // if (c2) goto TBB; else goto FBB;
947 // | / |
948 // | / |
949 // TBB |
950 // | |
951 // | FBB
952 // |
953 // exit
954 //
955 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
956 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
957 // TBB contains a convergent instruction. This is safe iff doing so does
958 // not add a control-flow dependency to the convergent instruction -- i.e.,
959 // it's safe iff the set of control flows that leads us to the convergent
960 // instruction does not get smaller after the transformation.
961 //
962 // Originally we executed TBB if c1 || c2. After the transformation, there
963 // are two copies of TBB's instructions. We get to the first if c1, and we
964 // get to the second if !c1 && c2.
965 //
966 // There are clearly fewer ways to satisfy the condition "c1" than
967 // "c1 || c2". Since we've shrunk the set of control flows which lead to
968 // our convergent instruction, the transformation is unsafe.
969 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000970 BBI.CannotBeCopied = true;
971
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000972 bool isPredicated = TII->isPredicated(MI);
973 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000974
Kyle Butt6262ca32016-08-24 21:34:24 +0000975 if (BranchUnpredicable && MI.isBranch()) {
976 BBI.IsUnpredicable = true;
977 return;
978 }
979
Joey Goulya5153cb2013-09-09 14:21:49 +0000980 // A conditional branch is not predicable, but it may be eliminated.
981 if (isCondBr)
982 continue;
983
984 if (!isPredicated) {
985 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000986 unsigned ExtraPredCost = TII->getPredicationCost(MI);
987 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000988 if (NumCycles > 1)
989 BBI.ExtraCost += NumCycles-1;
990 BBI.ExtraCost2 += ExtraPredCost;
991 } else if (!AlreadyPredicated) {
992 // FIXME: This instruction is already predicated before the
993 // if-conversion pass. It's probably something like a conditional move.
994 // Mark this block unpredicable for now.
995 BBI.IsUnpredicable = true;
996 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000997 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000998
999 if (BBI.ClobbersPred && !isPredicated) {
1000 // Predicate modification instruction should end the block (except for
1001 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +00001002 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +00001003 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001004 BBI.IsUnpredicable = true;
1005 return;
1006 }
1007
Evan Chengfbc73092007-07-10 17:50:43 +00001008 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1009 // still potentially predicable.
1010 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001011 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001012 BBI.ClobbersPred = true;
1013
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001014 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001015 BBI.IsUnpredicable = true;
1016 return;
1017 }
1018 }
1019}
1020
Matthias Braun2c931792016-08-17 02:51:57 +00001021/// Determine if the block is a suitable candidate to be predicated by the
1022/// specified predicate.
Kyle Butt6262ca32016-08-24 21:34:24 +00001023/// @param BBI BBInfo for the block to check
1024/// @param Pred Predicate array for the branch that leads to BBI
1025/// @param isTriangle true if the Analysis is for a triangle
1026/// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1027/// case
1028/// @param hasCommonTail true if BBI shares a tail with a sibling block that
1029/// contains any instruction that would make the block unpredicable.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001030bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001031 SmallVectorImpl<MachineOperand> &Pred,
Kyle Butt6262ca32016-08-24 21:34:24 +00001032 bool isTriangle, bool RevBranch,
1033 bool hasCommonTail) {
Evan Cheng3a51c852007-06-16 09:34:52 +00001034 // If the block is dead or unpredicable, then it cannot be predicated.
Kyle Butt6262ca32016-08-24 21:34:24 +00001035 // Two blocks may share a common unpredicable tail, but this doesn't prevent
1036 // them from being if-converted. The non-shared portion is assumed to have
1037 // been checked
1038 if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001039 return false;
1040
Ahmed Bougacha7173b662015-03-21 01:23:15 +00001041 // If it is already predicated but we couldn't analyze its terminator, the
1042 // latter might fallthrough, but we can't determine where to.
1043 // Conservatively avoid if-converting again.
1044 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1045 return false;
1046
Quentin Colombetbdab2272013-07-24 20:20:37 +00001047 // If it is already predicated, check if the new predicate subsumes
1048 // its predicate.
1049 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001050 return false;
1051
Kyle Butt6262ca32016-08-24 21:34:24 +00001052 if (!hasCommonTail && BBI.BrCond.size()) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001053 if (!isTriangle)
1054 return false;
1055
Bob Wilson2371f4f2009-05-13 23:25:24 +00001056 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +00001057 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1058 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +00001059 if (RevBranch) {
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001060 if (TII->reverseBranchCondition(Cond))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001061 return false;
1062 }
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001063 if (TII->reverseBranchCondition(RevPred) ||
Evan Cheng4dd31a72007-06-11 22:26:22 +00001064 !TII->SubsumesPredicate(Cond, RevPred))
1065 return false;
1066 }
1067
1068 return true;
1069}
1070
Matthias Braun2c931792016-08-17 02:51:57 +00001071/// Analyze the structure of the sub-CFG starting from the specified block.
1072/// Record its successors and whether it looks like an if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001073void IfConverter::AnalyzeBlock(
Matthias Braun08f47042016-08-17 02:52:01 +00001074 MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001075 struct BBState {
Matthias Braun08f47042016-08-17 02:52:01 +00001076 BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001077 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +00001078
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001079 /// This flag is true if MBB's successors have been analyzed.
1080 bool SuccsAnalyzed;
1081 };
Evan Cheng0f745da2007-05-18 00:20:58 +00001082
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001083 // Push MBB to the stack.
1084 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001085
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001086 while (!BBStack.empty()) {
1087 BBState &State = BBStack.back();
1088 MachineBasicBlock *BB = State.MBB;
1089 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +00001090
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001091 if (!State.SuccsAnalyzed) {
1092 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1093 BBStack.pop_back();
1094 continue;
1095 }
Evan Cheng9030b982007-06-06 10:16:17 +00001096
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001097 BBI.BB = BB;
1098 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +00001099
Kyle Butt54bf3ce2016-08-06 01:52:34 +00001100 AnalyzeBranches(BBI);
1101 MachineBasicBlock::iterator Begin = BBI.BB->begin();
1102 MachineBasicBlock::iterator End = BBI.BB->end();
1103 ScanInstructions(BBI, Begin, End);
Evan Chengb9bff582009-06-15 21:24:34 +00001104
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001105 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1106 // not considered for ifcvt anymore.
1107 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1108 BBI.IsBeingAnalyzed = false;
1109 BBI.IsAnalyzed = true;
1110 BBStack.pop_back();
1111 continue;
1112 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001113
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001114 // Do not ifcvt if either path is a back edge to the entry block.
1115 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1116 BBI.IsBeingAnalyzed = false;
1117 BBI.IsAnalyzed = true;
1118 BBStack.pop_back();
1119 continue;
1120 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001121
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001122 // Do not ifcvt if true and false fallthrough blocks are the same.
1123 if (!BBI.FalseBB) {
1124 BBI.IsBeingAnalyzed = false;
1125 BBI.IsAnalyzed = true;
1126 BBStack.pop_back();
1127 continue;
1128 }
Evan Cheng7783f822007-06-08 09:36:04 +00001129
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001130 // Push the False and True blocks to the stack.
1131 State.SuccsAnalyzed = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001132 BBStack.push_back(*BBI.FalseBB);
1133 BBStack.push_back(*BBI.TrueBB);
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001134 continue;
1135 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +00001136
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001137 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1138 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +00001139
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001140 if (TrueBBI.IsDone && FalseBBI.IsDone) {
1141 BBI.IsBeingAnalyzed = false;
1142 BBI.IsAnalyzed = true;
1143 BBStack.pop_back();
1144 continue;
1145 }
1146
1147 SmallVector<MachineOperand, 4>
1148 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001149 bool CanRevCond = !TII->reverseBranchCondition(RevCond);
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001150
1151 unsigned Dups = 0;
1152 unsigned Dups2 = 0;
1153 bool TNeedSub = !TrueBBI.Predicate.empty();
1154 bool FNeedSub = !FalseBBI.Predicate.empty();
1155 bool Enqueued = false;
1156
1157 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1158
Kyle Butt6262ca32016-08-24 21:34:24 +00001159 if (CanRevCond) {
1160 BBInfo TrueBBICalc, FalseBBICalc;
Kyle Butta8c73712016-08-24 21:34:27 +00001161 auto feasibleDiamond = [&]() {
1162 bool MeetsSize = MeetIfcvtSizeLimit(
1163 *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1164 TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1165 *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1166 FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1167 Prediction);
1168 bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1169 /* IsTriangle */ false, /* RevCond */ false,
1170 /* hasCommonTail */ true);
1171 bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1172 /* IsTriangle */ false, /* RevCond */ false,
1173 /* hasCommonTail */ true);
1174 return MeetsSize && TrueFeasible && FalseFeasible;
1175 };
1176
Kyle Butt6262ca32016-08-24 21:34:24 +00001177 if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
Kyle Butta8c73712016-08-24 21:34:27 +00001178 TrueBBICalc, FalseBBICalc)) {
1179 if (feasibleDiamond()) {
1180 // Diamond:
1181 // EBB
1182 // / \_
1183 // | |
1184 // TBB FBB
1185 // \ /
1186 // TailBB
1187 // Note TailBB can be empty.
1188 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1189 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1190 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1191 Enqueued = true;
1192 }
1193 } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1194 TrueBBICalc, FalseBBICalc)) {
1195 if (feasibleDiamond()) {
1196 // ForkedDiamond:
1197 // if TBB and FBB have a common tail that includes their conditional
1198 // branch instructions, then we can If Convert this pattern.
1199 // EBB
1200 // _/ \_
1201 // | |
1202 // TBB FBB
1203 // / \ / \
1204 // FalseBB TrueBB FalseBB
1205 //
1206 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1207 BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1208 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1209 Enqueued = true;
1210 }
Kyle Butt6262ca32016-08-24 21:34:24 +00001211 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001212 }
1213
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001214 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1215 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1216 TrueBBI.ExtraCost2, Prediction) &&
1217 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1218 // Triangle:
1219 // EBB
1220 // | \_
1221 // | |
1222 // | TBB
1223 // | /
1224 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001225 Tokens.push_back(
1226 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001227 Enqueued = true;
1228 }
1229
1230 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1231 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1232 TrueBBI.ExtraCost2, Prediction) &&
1233 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001234 Tokens.push_back(
1235 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001236 Enqueued = true;
1237 }
1238
1239 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1240 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1241 TrueBBI.ExtraCost2, Prediction) &&
1242 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1243 // Simple (split, no rejoin):
1244 // EBB
1245 // | \_
1246 // | |
1247 // | TBB---> exit
1248 // |
1249 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001250 Tokens.push_back(
1251 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001252 Enqueued = true;
1253 }
1254
1255 if (CanRevCond) {
1256 // Try the other path...
1257 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1258 Prediction.getCompl()) &&
1259 MeetIfcvtSizeLimit(*FalseBBI.BB,
1260 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1261 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1262 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001263 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1264 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001265 Enqueued = true;
1266 }
1267
1268 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1269 Prediction.getCompl()) &&
1270 MeetIfcvtSizeLimit(*FalseBBI.BB,
1271 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +00001272 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +00001273 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001274 Tokens.push_back(
1275 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001276 Enqueued = true;
1277 }
1278
1279 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1280 MeetIfcvtSizeLimit(*FalseBBI.BB,
1281 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1282 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1283 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001284 Tokens.push_back(
1285 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001286 Enqueued = true;
1287 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001288 }
1289
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001290 BBI.IsEnqueued = Enqueued;
1291 BBI.IsBeingAnalyzed = false;
1292 BBI.IsAnalyzed = true;
1293 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001294 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001295}
1296
Matthias Braun2c931792016-08-17 02:51:57 +00001297/// Analyze all blocks and find entries for all if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001298void IfConverter::AnalyzeBlocks(
1299 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001300 for (MachineBasicBlock &MBB : MF)
Matthias Braun08f47042016-08-17 02:52:01 +00001301 AnalyzeBlock(MBB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001302
Evan Cheng20e05992007-06-01 00:12:12 +00001303 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +00001304 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001305}
1306
Matthias Braun2c931792016-08-17 02:51:57 +00001307/// Returns true either if ToMBB is the next block after MBB or that all the
1308/// intervening blocks are empty (given MBB can fall through to its next block).
Matthias Braun08f47042016-08-17 02:52:01 +00001309static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1310 MachineFunction::iterator PI = MBB.getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001311 MachineFunction::iterator I = std::next(PI);
Matthias Braun08f47042016-08-17 02:52:01 +00001312 MachineFunction::iterator TI = ToMBB.getIterator();
1313 MachineFunction::iterator E = MBB.getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001314 while (I != TI) {
1315 // Check isSuccessor to avoid case where the next block is empty, but
1316 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001317 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001318 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001319 PI = I++;
1320 }
Evan Cheng312b7232007-06-04 06:47:22 +00001321 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001322}
1323
Matthias Braun2c931792016-08-17 02:51:57 +00001324/// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1325/// can be if-converted. If predecessor is already enqueued, dequeue it!
Matthias Braun08f47042016-08-17 02:52:01 +00001326void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1327 for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001328 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Matthias Braun08f47042016-08-17 02:52:01 +00001329 if (PBBI.IsDone || PBBI.BB == &MBB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001330 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001331 PBBI.IsAnalyzed = false;
1332 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001333 }
1334}
1335
Matthias Braun2c931792016-08-17 02:51:57 +00001336/// Inserts an unconditional branch from \p MBB to \p ToMBB.
Matthias Braun08f47042016-08-17 02:52:01 +00001337static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
Evan Chengc2237ce2007-05-29 22:31:16 +00001338 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001339 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001340 SmallVector<MachineOperand, 0> NoCond;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001341 TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001342}
1343
Matthias Braun2c931792016-08-17 02:51:57 +00001344/// Remove true / false edges if either / both are no longer successors.
Evan Cheng288f1542007-06-08 22:01:07 +00001345void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001346 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001347 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001348 if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
Evan Cheng0598b2d2007-06-18 22:44:57 +00001349 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001350}
1351
Matthias Braund616ccc2013-10-11 19:04:37 +00001352/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Jonas Paulsson196986c2016-08-03 05:46:35 +00001353/// values defined in MI which are also live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001354static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Jonas Paulsson196986c2016-08-03 05:46:35 +00001355 const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1356 ->getSubtarget().getRegisterInfo();
1357
1358 // Before stepping forward past MI, remember which regs were live
1359 // before MI. This is needed to set the Undef flag only when reg is
1360 // dead.
1361 SparseSet<unsigned> LiveBeforeMI;
1362 LiveBeforeMI.setUniverse(TRI->getNumRegs());
Matthias Braunb1e05582016-08-17 02:51:59 +00001363 for (unsigned Reg : Redefs)
Jonas Paulsson196986c2016-08-03 05:46:35 +00001364 LiveBeforeMI.insert(Reg);
1365
Pete Cooper7605e372015-05-05 20:14:22 +00001366 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001367 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001368
Pete Cooper7605e372015-05-05 20:14:22 +00001369 // Now add the implicit uses for each of the clobbered values.
Matthias Braun08f47042016-08-17 02:52:01 +00001370 for (auto Clobber : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001371 // FIXME: Const cast here is nasty, but better than making StepForward
1372 // take a mutable instruction instead of const.
Matthias Braun08f47042016-08-17 02:52:01 +00001373 unsigned Reg = Clobber.first;
1374 MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
Pete Cooper27483912015-05-06 22:51:04 +00001375 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001376 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001377 if (Op.isRegMask()) {
1378 // First handle regmasks. They clobber any entries in the mask which
1379 // means that we need a def for those registers.
Matthias Braun08f47042016-08-17 02:52:01 +00001380 if (LiveBeforeMI.count(Reg))
1381 MIB.addReg(Reg, RegState::Implicit);
Pete Cooperce9ad752015-05-05 22:09:41 +00001382
1383 // We also need to add an implicit def of this register for the later
1384 // use to read from.
1385 // For the register allocator to have allocated a register clobbered
1386 // by the call which is used later, it must be the case that
1387 // the call doesn't return.
Matthias Braun08f47042016-08-17 02:52:01 +00001388 MIB.addReg(Reg, RegState::Implicit | RegState::Define);
Pete Cooperce9ad752015-05-05 22:09:41 +00001389 continue;
1390 }
1391 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001392 if (Op.isDead()) {
1393 // If we found a dead def, but it needs to be live, then remove the dead
1394 // flag.
1395 if (Redefs.contains(Op.getReg()))
1396 Op.setIsDead(false);
1397 }
Matthias Braun08f47042016-08-17 02:52:01 +00001398 if (LiveBeforeMI.count(Reg))
1399 MIB.addReg(Reg, RegState::Implicit);
Krzysztof Parzyszekdcb1bca2016-09-28 20:07:41 +00001400 else {
1401 bool HasLiveSubReg = false;
1402 for (MCSubRegIterator S(Reg, TRI); S.isValid(); ++S) {
1403 if (!LiveBeforeMI.count(*S))
1404 continue;
1405 HasLiveSubReg = true;
1406 break;
1407 }
1408 if (HasLiveSubReg)
1409 MIB.addReg(Reg, RegState::Implicit);
1410 }
Matthias Braund616ccc2013-10-11 19:04:37 +00001411 }
1412}
1413
Matthias Braun2c931792016-08-17 02:51:57 +00001414/// Remove kill flags from operands with a registers in the \p DontKill set.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001415static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001416 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001417 if (!O->isReg() || !O->isKill())
1418 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001419 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001420 O->setIsKill(false);
1421 }
1422}
1423
Matthias Braun2c931792016-08-17 02:51:57 +00001424/// Walks a range of machine instructions and removes kill flags for registers
1425/// in the \p DontKill set.
Matthias Braund616ccc2013-10-11 19:04:37 +00001426static void RemoveKills(MachineBasicBlock::iterator I,
1427 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001428 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001429 const MCRegisterInfo &MCRI) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001430 for (MachineInstr &MI : make_range(I, E))
1431 RemoveKills(MI, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001432}
1433
Matthias Braun2c931792016-08-17 02:51:57 +00001434/// If convert a simple (split, no rejoin) sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001435bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001436 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1437 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1438 BBInfo *CvtBBI = &TrueBBI;
1439 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001440
Owen Anderson4f6bf042008-08-14 22:49:33 +00001441 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001442 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001443 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001444
Matthias Braun08f47042016-08-17 02:52:01 +00001445 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1446 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001447 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001448 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001449 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001450 BBI.IsAnalyzed = false;
1451 CvtBBI->IsAnalyzed = false;
1452 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001453 }
Evan Chengd0e66912007-05-23 07:23:16 +00001454
Matthias Braun08f47042016-08-17 02:52:01 +00001455 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001456 // Conservatively abort if-conversion if BB's address is taken.
1457 return false;
1458
Evan Cheng3a51c852007-06-16 09:34:52 +00001459 if (Kind == ICSimpleFalse)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001460 if (TII->reverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001461 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001462
Matthias Braun0c989a82016-12-08 00:15:51 +00001463 Redefs.init(*TRI);
Matthias Braun0c989a82016-12-08 00:15:51 +00001464 DontKill.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001465
1466 if (MRI->tracksLiveness()) {
1467 // Initialize liveins to the first BB. These are potentiall redefined by
1468 // predicated instructions.
1469 Redefs.addLiveIns(CvtMBB);
1470 Redefs.addLiveIns(NextMBB);
1471 // Compute a set of registers which must not be killed by instructions in
1472 // BB1: This is everything live-in to BB2.
1473 DontKill.addLiveIns(NextMBB);
1474 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001475
Matthias Braun08f47042016-08-17 02:52:01 +00001476 if (CvtMBB.pred_size() > 1) {
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001477 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001478 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001479 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001480 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001481
1482 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1483 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001484 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001485 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001486 RemoveKills(CvtMBB.begin(), CvtMBB.end(), DontKill, *TRI);
1487 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001488
Evan Cheng92fb5452007-06-15 07:36:12 +00001489 // Merge converted block into entry block.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001490 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
Evan Cheng92fb5452007-06-15 07:36:12 +00001491 MergeBlocks(BBI, *CvtBBI);
1492 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001493
Evan Chenge4ec9182007-06-06 02:08:52 +00001494 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001495 if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1496 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001497 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001498 // Now ifcvt'd block will look like this:
1499 // BB:
1500 // ...
1501 // t, f = cmp
1502 // if t op
1503 // b BBf
1504 //
1505 // We cannot further ifcvt this block because the unconditional branch
1506 // will have to be predicated on the new condition, that will not be
1507 // available if cmp executes.
1508 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001509 }
Evan Chenge26c0912007-05-21 22:22:58 +00001510
Evan Cheng288f1542007-06-08 22:01:07 +00001511 RemoveExtraEdges(BBI);
1512
Evan Chengd0e66912007-05-23 07:23:16 +00001513 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001514 if (!IterIfcvt)
1515 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001516 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001517 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001518
1519 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001520 return true;
1521}
1522
Matthias Braun2c931792016-08-17 02:51:57 +00001523/// If convert a triangle sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001524bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001525 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001526 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1527 BBInfo *CvtBBI = &TrueBBI;
1528 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001529 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001530
Owen Anderson4f6bf042008-08-14 22:49:33 +00001531 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001532 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001533 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001534
Matthias Braun08f47042016-08-17 02:52:01 +00001535 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1536 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001537 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001538 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001539 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001540 BBI.IsAnalyzed = false;
1541 CvtBBI->IsAnalyzed = false;
1542 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001543 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001544
Matthias Braun08f47042016-08-17 02:52:01 +00001545 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001546 // Conservatively abort if-conversion if BB's address is taken.
1547 return false;
1548
Evan Cheng3a51c852007-06-16 09:34:52 +00001549 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001550 if (TII->reverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001551 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001552
Evan Cheng3a51c852007-06-16 09:34:52 +00001553 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001554 if (reverseBranchCondition(*CvtBBI)) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001555 // BB has been changed, modify its predecessors (except for this
1556 // one) so they don't get ifcvt'ed based on bad intel.
Matthias Braun08f47042016-08-17 02:52:01 +00001557 for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001558 if (PBB == BBI.BB)
1559 continue;
1560 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1561 if (PBBI.IsEnqueued) {
1562 PBBI.IsAnalyzed = false;
1563 PBBI.IsEnqueued = false;
1564 }
Evan Chengadd97762007-06-14 23:34:09 +00001565 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001566 }
1567 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001568
Bob Wilson45814342010-06-19 05:33:57 +00001569 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001570 // predicated instructions.
Matthias Braun0c989a82016-12-08 00:15:51 +00001571 Redefs.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001572 if (MRI->tracksLiveness()) {
1573 Redefs.addLiveIns(CvtMBB);
1574 Redefs.addLiveIns(NextMBB);
1575 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001576
Andrew Trick276dd452013-10-14 20:45:17 +00001577 DontKill.clear();
1578
Craig Topperc0196b12014-04-14 00:51:57 +00001579 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001580 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001581
Manman Renb6819182014-01-29 23:18:47 +00001582 if (HasEarlyExit) {
Matthias Braun08f47042016-08-17 02:52:01 +00001583 // Get probabilities before modifying CvtMBB and BBI.BB.
1584 CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1585 CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1586 BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1587 BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
Manman Renb6819182014-01-29 23:18:47 +00001588 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001589
Matthias Braun08f47042016-08-17 02:52:01 +00001590 if (CvtMBB.pred_size() > 1) {
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001591 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001592 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001593 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001594 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001595
1596 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1597 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001598 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001599 } else {
1600 // Predicate the 'true' block after removing its branch.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001601 CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
Matthias Braun08f47042016-08-17 02:52:01 +00001602 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001603
Evan Cheng0598b2d2007-06-18 22:44:57 +00001604 // Now merge the entry of the triangle with the true block.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001605 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001606 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001607 }
1608
Evan Cheng312b7232007-06-04 06:47:22 +00001609 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001610 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001611 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1612 CvtBBI->BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001613 if (TII->reverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001614 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001615
Cong Houd97c1002015-12-01 05:29:22 +00001616 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
Matthias Braun08f47042016-08-17 02:52:01 +00001617 // NewNext = New_Prob(BBI.BB, NextMBB) =
1618 // Prob(BBI.BB, NextMBB) +
1619 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
Cong Houd97c1002015-12-01 05:29:22 +00001620 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
Matthias Braun08f47042016-08-17 02:52:01 +00001621 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1622 auto NewTrueBB = getNextBlock(*BBI.BB);
Cong Houd97c1002015-12-01 05:29:22 +00001623 auto NewNext = BBNext + BBCvt * CvtNext;
David Majnemer42531262016-08-12 03:55:06 +00001624 auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001625 if (NewTrueBBIter != BBI.BB->succ_end())
1626 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001627
1628 auto NewFalse = BBCvt * CvtFalse;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001629 TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
Cong Houd97c1002015-12-01 05:29:22 +00001630 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001631 }
Evan Cheng7783f822007-06-08 09:36:04 +00001632
1633 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001634 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001635 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001636 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001637 bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001638 if (!isFallThrough) {
1639 // Only merge them if the true block does not fallthrough to the false
1640 // block. By not merging them, we make it possible to iteratively
1641 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001642 if (!HasEarlyExit &&
Matthias Braun08f47042016-08-17 02:52:01 +00001643 NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
1644 !NextMBB.hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001645 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001646 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001647 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001648 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001649 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001650 }
Evan Cheng7783f822007-06-08 09:36:04 +00001651 // Mixed predicated and unpredicated code. This cannot be iteratively
1652 // predicated.
1653 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001654 }
Evan Chenge26c0912007-05-21 22:22:58 +00001655
Evan Cheng288f1542007-06-08 22:01:07 +00001656 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001657
Evan Chengd0e66912007-05-23 07:23:16 +00001658 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001659 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001660 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001661 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001662 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001663 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001664 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001665
1666 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001667 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001668}
1669
Kyle Butta8c73712016-08-24 21:34:27 +00001670/// Common code shared between diamond conversions.
1671/// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1672/// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1673/// and FalseBBI
1674/// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1675/// and \p FalseBBI
Kyle Butt092c4dd2016-08-29 18:27:12 +00001676/// \p RemoveBranch - Remove the common branch of the two blocks before
1677/// predicating. Only false for unanalyzable fallthrough
1678/// cases. The caller will replace the branch if necessary.
Kyle Butta8c73712016-08-24 21:34:27 +00001679/// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1680/// unanalyzable fallthrough
1681bool IfConverter::IfConvertDiamondCommon(
1682 BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1683 unsigned NumDups1, unsigned NumDups2,
1684 bool TClobbersPred, bool FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001685 bool RemoveBranch, bool MergeAddEdges) {
Evan Chenge26c0912007-05-21 22:22:58 +00001686
Evan Cheng51eb2c32007-06-18 08:37:25 +00001687 if (TrueBBI.IsDone || FalseBBI.IsDone ||
Kyle Butta8c73712016-08-24 21:34:27 +00001688 TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001689 // Something has changed. It's no longer safe to predicate these blocks.
1690 BBI.IsAnalyzed = false;
1691 TrueBBI.IsAnalyzed = false;
1692 FalseBBI.IsAnalyzed = false;
1693 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001694 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001695
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001696 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1697 // Conservatively abort if-conversion if either BB has its address taken.
1698 return false;
1699
Bob Wilson1e5da552010-06-29 00:55:23 +00001700 // Put the predicated instructions from the 'true' block before the
1701 // instructions from the 'false' block, unless the true block would clobber
1702 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001703 BBInfo *BBI1 = &TrueBBI;
1704 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001705 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001706 if (TII->reverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001707 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001708 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1709 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001710
Evan Cheng3a51c852007-06-16 09:34:52 +00001711 // Figure out the more profitable ordering.
1712 bool DoSwap = false;
Kyle Butt6262ca32016-08-24 21:34:24 +00001713 if (TClobbersPred && !FClobbersPred)
Evan Cheng3a51c852007-06-16 09:34:52 +00001714 DoSwap = true;
Kyle Butte31cc842016-09-02 18:29:28 +00001715 else if (!TClobbersPred && !FClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001716 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001717 DoSwap = true;
Kyle Butte31cc842016-09-02 18:29:28 +00001718 } else if (TClobbersPred && FClobbersPred)
1719 llvm_unreachable("Predicate info cannot be clobbered by both sides.");
Evan Cheng3a51c852007-06-16 09:34:52 +00001720 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001721 std::swap(BBI1, BBI2);
1722 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001723 }
Evan Cheng79484222007-06-05 23:46:14 +00001724
Evan Cheng51eb2c32007-06-18 08:37:25 +00001725 // Remove the conditional branch from entry to the blocks.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001726 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001727
Matthias Braun08f47042016-08-17 02:52:01 +00001728 MachineBasicBlock &MBB1 = *BBI1->BB;
1729 MachineBasicBlock &MBB2 = *BBI2->BB;
1730
Krzysztof Parzyszeka003b762016-08-11 18:42:06 +00001731 // Initialize the Redefs:
1732 // - BB2 live-in regs need implicit uses before being redefined by BB1
1733 // instructions.
1734 // - BB1 live-out regs need implicit uses before being redefined by BB2
1735 // instructions. We start with BB1 live-ins so we have the live-out regs
1736 // after tracking the BB1 instructions.
Matthias Braun0c989a82016-12-08 00:15:51 +00001737 Redefs.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001738 if (MRI->tracksLiveness()) {
1739 Redefs.addLiveIns(MBB1);
1740 Redefs.addLiveIns(MBB2);
1741 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001742
Evan Cheng51eb2c32007-06-18 08:37:25 +00001743 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001744 // Skip dbg_value instructions
Matthias Braun08f47042016-08-17 02:52:01 +00001745 MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1746 MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001747 BBI1->NonPredSize -= NumDups1;
1748 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001749
1750 // Skip past the dups on each side separately since there may be
1751 // differing dbg_value entries.
1752 for (unsigned i = 0; i < NumDups1; ++DI1) {
1753 if (!DI1->isDebugValue())
1754 ++i;
1755 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001756 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001757 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001758 if (!DI2->isDebugValue())
1759 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001760 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001761
Matthias Braund616ccc2013-10-11 19:04:37 +00001762 // Compute a set of registers which must not be killed by instructions in BB1:
1763 // This is everything used+live in BB2 after the duplicated instructions. We
1764 // can compute this set by simulating liveness backwards from the end of BB2.
Matthias Braun0c989a82016-12-08 00:15:51 +00001765 DontKill.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001766 if (MRI->tracksLiveness()) {
1767 for (const MachineInstr &MI : make_range(MBB2.rbegin(), ++DI2.getReverse()))
1768 DontKill.stepBackward(MI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001769
Matthias Braun11723322017-01-05 20:01:19 +00001770 for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
1771 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Dummy;
1772 Redefs.stepForward(MI, Dummy);
1773 }
Matthias Braund616ccc2013-10-11 19:04:37 +00001774 }
Matthias Braun08f47042016-08-17 02:52:01 +00001775 BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1776 MBB2.erase(MBB2.begin(), DI2);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001777
Kyle Butt092c4dd2016-08-29 18:27:12 +00001778 // The branches have been checked to match, so it is safe to remove the branch
1779 // in BB1 and rely on the copy in BB2
1780#ifndef NDEBUG
1781 // Unanalyzable branches must match exactly. Check that now.
1782 if (!BBI1->IsBrAnalyzable)
1783 verifySameBranchInstructions(&MBB1, &MBB2);
1784#endif
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001785 BBI1->NonPredSize -= TII->removeBranch(*BBI1->BB);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001786 // Remove duplicated instructions.
Matthias Braun08f47042016-08-17 02:52:01 +00001787 DI1 = MBB1.end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001788 for (unsigned i = 0; i != NumDups2; ) {
1789 // NumDups2 only counted non-dbg_value instructions, so this won't
1790 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001791 assert(DI1 != MBB1.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001792 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001793 // skip dbg_value instructions
1794 if (!DI1->isDebugValue())
1795 ++i;
1796 }
Matthias Braun08f47042016-08-17 02:52:01 +00001797 MBB1.erase(DI1, MBB1.end());
Evan Cheng79484222007-06-05 23:46:14 +00001798
Matthias Braund616ccc2013-10-11 19:04:37 +00001799 // Kill flags in the true block for registers living into the false block
1800 // must be removed.
Matthias Braun08f47042016-08-17 02:52:01 +00001801 RemoveKills(MBB1.begin(), MBB1.end(), DontKill, *TRI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001802
Kyle Butta8c73712016-08-24 21:34:27 +00001803 DI2 = BBI2->BB->end();
Kyle Butt092c4dd2016-08-29 18:27:12 +00001804 // The branches have been checked to match. Skip over the branch in the false
1805 // block so that we don't try to predicate it.
1806 if (RemoveBranch)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001807 BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
Kyle Butt092c4dd2016-08-29 18:27:12 +00001808 else {
1809 do {
1810 assert(DI2 != MBB2.begin());
1811 DI2--;
1812 } while (DI2->isBranch() || DI2->isDebugValue());
1813 DI2++;
1814 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001815 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001816 // NumDups2 only counted non-dbg_value instructions, so this won't
1817 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001818 assert(DI2 != MBB2.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001819 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001820 // skip dbg_value instructions
1821 if (!DI2->isDebugValue())
1822 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001823 }
Evan Cheng4266a792011-12-19 22:01:30 +00001824
1825 // Remember which registers would later be defined by the false block.
1826 // This allows us not to predicate instructions in the true block that would
1827 // later be re-defined. That is, rather than
1828 // subeq r0, r1, #1
1829 // addne r0, r1, #1
1830 // generate:
1831 // sub r0, r1, #1
1832 // addne r0, r1, #1
1833 SmallSet<unsigned, 4> RedefsByFalse;
1834 SmallSet<unsigned, 4> ExtUses;
Matthias Braun08f47042016-08-17 02:52:01 +00001835 if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1836 for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001837 if (FI.isDebugValue())
Evan Cheng4266a792011-12-19 22:01:30 +00001838 continue;
1839 SmallVector<unsigned, 4> Defs;
Matthias Braunb1e05582016-08-17 02:51:59 +00001840 for (const MachineOperand &MO : FI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001841 if (!MO.isReg())
1842 continue;
1843 unsigned Reg = MO.getReg();
1844 if (!Reg)
1845 continue;
1846 if (MO.isDef()) {
1847 Defs.push_back(Reg);
1848 } else if (!RedefsByFalse.count(Reg)) {
1849 // These are defined before ctrl flow reach the 'false' instructions.
1850 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001851 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1852 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001853 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001854 }
1855 }
1856
Matthias Braunb1e05582016-08-17 02:51:59 +00001857 for (unsigned Reg : Defs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001858 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001859 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1860 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001861 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001862 }
1863 }
1864 }
1865 }
1866
1867 // Predicate the 'true' block.
Matthias Braun08f47042016-08-17 02:52:01 +00001868 PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001869
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001870 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1871 // a non-predicated in BBI2, then we don't want to predicate the one from
1872 // BBI2. The reason is that if we merged these blocks, we would end up with
1873 // two predicated terminators in the same block.
Matthias Braun08f47042016-08-17 02:52:01 +00001874 if (!MBB2.empty() && (DI2 == MBB2.end())) {
1875 MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1876 MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1877 if (BBI1T != MBB1.end() && TII->isPredicated(*BBI1T) &&
1878 BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001879 --DI2;
1880 }
1881
Evan Cheng4266a792011-12-19 22:01:30 +00001882 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001883 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001884
Evan Cheng0598b2d2007-06-18 22:44:57 +00001885 // Merge the true block into the entry of the diamond.
Kyle Butta8c73712016-08-24 21:34:27 +00001886 MergeBlocks(BBI, *BBI1, MergeAddEdges);
1887 MergeBlocks(BBI, *BBI2, MergeAddEdges);
1888 return true;
1889}
1890
1891/// If convert an almost-diamond sub-CFG where the true
1892/// and false blocks share a common tail.
1893bool IfConverter::IfConvertForkedDiamond(
1894 BBInfo &BBI, IfcvtKind Kind,
1895 unsigned NumDups1, unsigned NumDups2,
1896 bool TClobbersPred, bool FClobbersPred) {
1897 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1898 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1899
1900 // Save the debug location for later.
1901 DebugLoc dl;
1902 MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1903 if (TIE != TrueBBI.BB->end())
1904 dl = TIE->getDebugLoc();
1905 // Removing branches from both blocks is safe, because we have already
1906 // determined that both blocks have the same branch instructions. The branch
1907 // will be added back at the end, unpredicated.
1908 if (!IfConvertDiamondCommon(
1909 BBI, TrueBBI, FalseBBI,
1910 NumDups1, NumDups2,
1911 TClobbersPred, FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001912 /* RemoveBranch */ true, /* MergeAddEdges */ true))
Kyle Butta8c73712016-08-24 21:34:27 +00001913 return false;
1914
1915 // Add back the branch.
1916 // Debug location saved above when removing the branch from BBI2
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001917 TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
Kyle Butta8c73712016-08-24 21:34:27 +00001918 TrueBBI.BrCond, dl);
1919
1920 RemoveExtraEdges(BBI);
1921
1922 // Update block info.
1923 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1924 InvalidatePreds(*BBI.BB);
1925
1926 // FIXME: Must maintain LiveIns.
1927 return true;
1928}
1929
1930/// If convert a diamond sub-CFG.
1931bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1932 unsigned NumDups1, unsigned NumDups2,
1933 bool TClobbersPred, bool FClobbersPred) {
1934 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1935 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1936 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1937
1938 // True block must fall through or end with an unanalyzable terminator.
1939 if (!TailBB) {
1940 if (blockAlwaysFallThrough(TrueBBI))
1941 TailBB = FalseBBI.TrueBB;
1942 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1943 }
1944
1945 if (!IfConvertDiamondCommon(
1946 BBI, TrueBBI, FalseBBI,
1947 NumDups1, NumDups2,
Kyle Butt86999212016-09-02 18:29:26 +00001948 TClobbersPred, FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001949 /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
Kyle Butta8c73712016-08-24 21:34:27 +00001950 /* MergeAddEdges */ TailBB == nullptr))
1951 return false;
Evan Cheng30565992007-06-06 00:57:55 +00001952
Bob Wilson2371f4f2009-05-13 23:25:24 +00001953 // If the if-converted block falls through or unconditionally branches into
1954 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001955 // fold the tail block in as well. Otherwise, unless it falls through to the
1956 // tail, add a unconditional branch to it.
1957 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001958 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001959 bool CanMergeTail = !TailBBI.HasFallThrough &&
1960 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001961 // The if-converted block can still have a predicated terminator
1962 // (e.g. a predicated return). If that is the case, we cannot merge
1963 // it with the tail block.
1964 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001965 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001966 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001967 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1968 // check if there are any other predecessors besides those.
1969 unsigned NumPreds = TailBB->pred_size();
1970 if (NumPreds > 1)
1971 CanMergeTail = false;
1972 else if (NumPreds == 1 && CanMergeTail) {
1973 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
Kyle Butta8c73712016-08-24 21:34:27 +00001974 if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
Bob Wilson1e5da552010-06-29 00:55:23 +00001975 CanMergeTail = false;
1976 }
1977 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001978 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001979 TailBBI.IsDone = true;
1980 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001981 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Matthias Braun08f47042016-08-17 02:52:01 +00001982 InsertUncondBranch(*BBI.BB, *TailBB, TII);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001983 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001984 }
Evan Chenge26c0912007-05-21 22:22:58 +00001985 }
1986
Bob Wilson1e5da552010-06-29 00:55:23 +00001987 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1988 // which can happen here if TailBB is unanalyzable and is merged, so
1989 // explicitly remove BBI1 and BBI2 as successors.
Kyle Butta8c73712016-08-24 21:34:27 +00001990 BBI.BB->removeSuccessor(TrueBBI.BB);
1991 BBI.BB->removeSuccessor(FalseBBI.BB, /* NormalizeSuccessProbs */ true);
Evan Cheng288f1542007-06-08 22:01:07 +00001992 RemoveExtraEdges(BBI);
1993
Evan Cheng79484222007-06-05 23:46:14 +00001994 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001995 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001996 InvalidatePreds(*BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001997
1998 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001999 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00002000}
2001
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002002static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00002003 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00002004 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002005 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00002006 return false;
2007
Matthias Braunb1e05582016-08-17 02:51:59 +00002008 for (const MachineOperand &MO : MI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00002009 if (!MO.isReg())
2010 continue;
2011 unsigned Reg = MO.getReg();
2012 if (!Reg)
2013 continue;
2014 if (MO.isDef() && !LaterRedefs.count(Reg))
2015 return false;
2016 }
2017
2018 return true;
2019}
2020
Matthias Braun2c931792016-08-17 02:51:57 +00002021/// Predicate instructions from the start of the block to the specified end with
2022/// the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00002023void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00002024 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00002025 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00002026 SmallSet<unsigned, 4> *LaterRedefs) {
2027 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002028 bool MaySpec = LaterRedefs != nullptr;
Matthias Braunb1e05582016-08-17 02:51:59 +00002029 for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002030 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00002031 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00002032 // It may be possible not to predicate an instruction if it's the 'true'
2033 // side of a diamond and the 'false' side may re-define the instruction's
2034 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00002035 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00002036 AnyUnpred = true;
2037 continue;
2038 }
2039 // If any instruction is predicated, then every instruction after it must
2040 // be predicated.
2041 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002042 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00002043#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002044 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00002045#endif
Craig Topperc0196b12014-04-14 00:51:57 +00002046 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00002047 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002048
Bob Wilson45814342010-06-19 05:33:57 +00002049 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002050 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002051 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00002052 }
Evan Chengd0e66912007-05-23 07:23:16 +00002053
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002054 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00002055
Evan Cheng92fb5452007-06-15 07:36:12 +00002056 BBI.IsAnalyzed = false;
2057 BBI.NonPredSize = 0;
2058
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002059 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00002060 if (AnyUnpred)
2061 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00002062}
2063
Matthias Braun2c931792016-08-17 02:51:57 +00002064/// Copy and predicate instructions from source BB to the destination block.
2065/// Skip end of block branches if IgnoreBr is true.
Evan Cheng92fb5452007-06-15 07:36:12 +00002066void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00002067 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00002068 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00002069 MachineFunction &MF = *ToBBI.BB->getParent();
2070
Matthias Braun08f47042016-08-17 02:52:01 +00002071 MachineBasicBlock &FromMBB = *FromBBI.BB;
2072 for (MachineInstr &I : FromMBB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00002073 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002074 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00002075 break;
2076
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002077 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00002078 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00002079 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002080 unsigned ExtraPredCost = TII->getPredicationCost(I);
2081 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00002082 if (NumCycles > 1)
2083 ToBBI.ExtraCost += NumCycles-1;
2084 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00002085
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00002086 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002087 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00002088#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002089 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00002090#endif
Craig Topperc0196b12014-04-14 00:51:57 +00002091 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00002092 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002093 }
2094
Bob Wilson45814342010-06-19 05:33:57 +00002095 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002096 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002097 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00002098
2099 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00002100 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00002101 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00002102 }
2103
Bob Wilson1e5da552010-06-29 00:55:23 +00002104 if (!IgnoreBr) {
Matthias Braun08f47042016-08-17 02:52:01 +00002105 std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2106 FromMBB.succ_end());
2107 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00002108 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00002109
Matthias Braunb1e05582016-08-17 02:51:59 +00002110 for (MachineBasicBlock *Succ : Succs) {
Bob Wilson1e5da552010-06-29 00:55:23 +00002111 // Fallthrough edge can't be transferred.
2112 if (Succ == FallThrough)
2113 continue;
2114 ToBBI.BB->addSuccessor(Succ);
2115 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00002116 }
2117
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002118 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2119 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002120
2121 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2122 ToBBI.IsAnalyzed = false;
2123
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002124 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00002125}
2126
Matthias Braun2c931792016-08-17 02:51:57 +00002127/// Move all instructions from FromBB to the end of ToBB. This will leave
2128/// FromBB as an empty block, so remove all of its successor edges except for
2129/// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
2130/// being moved, add those successor edges to ToBBI.
Bob Wilson1e5da552010-06-29 00:55:23 +00002131void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Matthias Braun08f47042016-08-17 02:52:01 +00002132 MachineBasicBlock &FromMBB = *FromBBI.BB;
2133 assert(!FromMBB.hasAddressTaken() &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00002134 "Removing a BB whose address is taken!");
2135
Matthias Braun08f47042016-08-17 02:52:01 +00002136 // In case FromMBB contains terminators (e.g. return instruction),
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002137 // first move the non-terminator instructions, then the terminators.
Matthias Braun08f47042016-08-17 02:52:01 +00002138 MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002139 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
Matthias Braun08f47042016-08-17 02:52:01 +00002140 ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002141
2142 // If FromBB has non-predicated terminator we should copy it at the end.
Matthias Braun08f47042016-08-17 02:52:01 +00002143 if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002144 ToTI = ToBBI.BB->end();
Matthias Braun08f47042016-08-17 02:52:01 +00002145 ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
Evan Chengd0e66912007-05-23 07:23:16 +00002146
Cong Houb9e8d482015-12-17 01:29:08 +00002147 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2148 // unknown probabilities into known ones.
2149 // FIXME: This usage is too tricky and in the future we would like to
2150 // eliminate all unknown probabilities in MBB.
2151 ToBBI.BB->normalizeSuccProbs();
2152
Matthias Braun08f47042016-08-17 02:52:01 +00002153 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
2154 FromMBB.succ_end());
2155 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00002156 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Matthias Braun08f47042016-08-17 02:52:01 +00002157 // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2158 // AddEdges is true and FromMBB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00002159 auto To2FromProb = BranchProbability::getZero();
Matthias Braun08f47042016-08-17 02:52:01 +00002160 if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
2161 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
2162 // Set the edge probability from ToBBI.BB to FromMBB to zero to avoid the
Cong Houd97c1002015-12-01 05:29:22 +00002163 // edge probability being merged to other edges when this edge is removed
2164 // later.
Matthias Braun08f47042016-08-17 02:52:01 +00002165 ToBBI.BB->setSuccProbability(find(ToBBI.BB->successors(), &FromMBB),
David Majnemer42531262016-08-12 03:55:06 +00002166 BranchProbability::getZero());
Cong Houd97c1002015-12-01 05:29:22 +00002167 }
2168
Matthias Braunb1e05582016-08-17 02:51:59 +00002169 for (MachineBasicBlock *Succ : FromSuccs) {
Evan Cheng288f1542007-06-08 22:01:07 +00002170 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00002171 if (Succ == FallThrough)
2172 continue;
Cong Houd40105d2015-09-18 20:22:41 +00002173
Cong Houd97c1002015-12-01 05:29:22 +00002174 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00002175 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002176 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
Matthias Braun08f47042016-08-17 02:52:01 +00002177 // which is a portion of the edge probability from FromMBB to Succ. The
2178 // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
Cong Houd97c1002015-12-01 05:29:22 +00002179 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
Matthias Braun08f47042016-08-17 02:52:01 +00002180 NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002181
Matthias Braun08f47042016-08-17 02:52:01 +00002182 // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2183 // only happens when if-converting a diamond CFG and FromMBB is the
2184 // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
2185 // could just use the probabilities on FromMBB's out-edges when adding
Cong Houd97c1002015-12-01 05:29:22 +00002186 // new successors.
2187 if (!To2FromProb.isZero())
2188 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00002189 }
2190
Matthias Braun08f47042016-08-17 02:52:01 +00002191 FromMBB.removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002192
2193 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002194 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00002195 // probability of this edge by adding NewProb to it. An example is shown
Matthias Braun08f47042016-08-17 02:52:01 +00002196 // below, in which A is ToBBI.BB and B is FromMBB. In this case we
Cong Houd97c1002015-12-01 05:29:22 +00002197 // don't have to set C as A's successor as it already is. We only need to
2198 // update the edge probability on A->C. Note that B will not be
2199 // immediately removed from A's successors. It is possible that B->D is
2200 // not removed either if D is a fallthrough of B. Later the edge A->D
2201 // (generated here) and B->D will be combined into one edge. To maintain
2202 // correct edge probability of this combined edge, we need to set the edge
2203 // probability of A->B to zero, which is already done above. The edge
2204 // probability on A->D is calculated by scaling the original probability
2205 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00002206 //
2207 // Before ifcvt: After ifcvt (assume B->D is kept):
2208 //
2209 // A A
2210 // /| /|\
2211 // / B / B|
2212 // | /| | ||
2213 // |/ | | |/
2214 // C D C D
2215 //
2216 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00002217 ToBBI.BB->setSuccProbability(
David Majnemer42531262016-08-12 03:55:06 +00002218 find(ToBBI.BB->successors(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00002219 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002220 else
Cong Houd97c1002015-12-01 05:29:22 +00002221 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002222 }
Evan Chengbe9859e2007-06-07 02:12:15 +00002223 }
2224
Bob Wilson2371f4f2009-05-13 23:25:24 +00002225 // Now FromBBI always falls through to the next block!
Matthias Braun08f47042016-08-17 02:52:01 +00002226 if (NBB && !FromMBB.isSuccessor(NBB))
2227 FromMBB.addSuccessor(NBB);
Evan Cheng288f1542007-06-08 22:01:07 +00002228
Cong Houc1069892015-12-13 09:26:17 +00002229 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2230 // we've done above.
2231 ToBBI.BB->normalizeSuccProbs();
2232
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002233 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002234 FromBBI.Predicate.clear();
2235
Evan Chengd0e66912007-05-23 07:23:16 +00002236 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002237 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00002238 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00002239 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002240 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00002241 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00002242
Evan Cheng4dd31a72007-06-11 22:26:22 +00002243 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00002244 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00002245 ToBBI.IsAnalyzed = false;
2246 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00002247}
Akira Hatanaka4a616192015-06-08 18:50:43 +00002248
2249FunctionPass *
Matthias Braun8b38ffa2016-10-24 23:23:02 +00002250llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00002251 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00002252}