blob: 05600bbc0a877b9e3b6bd642cb25bd972fd4ea6b [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
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "BranchFolding.h"
16#include "llvm/ADT/STLExtras.h"
Kyle Buttd76755e2016-08-18 22:09:23 +000017#include "llvm/ADT/ScopeExit.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000020#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000021#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000022#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000027#include "llvm/CodeGen/Passes.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
Matthias Braun1527baa2017-05-25 21:26:32 +000042#define DEBUG_TYPE "if-converter"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000043
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;
Andrew Trick276dd452013-10-14 20:45:17 +0000182
Evan Chengc5adcca2012-06-08 21:53:50 +0000183 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000184 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000185 int FnNum;
Matthias Braun8b38ffa2016-10-24 23:23:02 +0000186 std::function<bool(const MachineFunction &)> PredicateFtor;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000187
Evan Chengf5e53a52007-05-16 02:00:57 +0000188 public:
189 static char ID;
Matthias Braun8b38ffa2016-10-24 23:23:02 +0000190 IfConverter(std::function<bool(const MachineFunction &)> Ftor = nullptr)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000191 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000192 initializeIfConverterPass(*PassRegistry::getPassRegistry());
193 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000194
Craig Topper4584cd52014-03-07 09:26:03 +0000195 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000196 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000197 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000198 MachineFunctionPass::getAnalysisUsage(AU);
199 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000200
Craig Topper4584cd52014-03-07 09:26:03 +0000201 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000202
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000203 MachineFunctionProperties getRequiredProperties() const override {
204 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000205 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000206 }
207
Evan Chengf5e53a52007-05-16 02:00:57 +0000208 private:
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000209 bool reverseBranchCondition(BBInfo &BBI) const;
Owen Andersonf31f33e2010-10-01 22:45:50 +0000210 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000211 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000212 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000213 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000214 BranchProbability Prediction) const;
Kyle Butt6262ca32016-08-24 21:34:24 +0000215 bool CountDuplicatedInstructions(
216 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
217 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
218 unsigned &Dups1, unsigned &Dups2,
219 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
220 bool SkipUnconditionalBranches) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000221 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
Kyle Butt6262ca32016-08-24 21:34:24 +0000222 unsigned &Dups1, unsigned &Dups2,
223 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butta8c73712016-08-24 21:34:27 +0000224 bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
225 unsigned &Dups1, unsigned &Dups2,
226 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000227 void AnalyzeBranches(BBInfo &BBI);
228 void ScanInstructions(BBInfo &BBI,
229 MachineBasicBlock::iterator &Begin,
Kyle Butt6262ca32016-08-24 21:34:24 +0000230 MachineBasicBlock::iterator &End,
231 bool BranchUnpredicable = false) const;
232 bool RescanInstructions(
233 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
234 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
235 BBInfo &TrueBBI, BBInfo &FalseBBI) const;
Matthias Braun08f47042016-08-17 02:52:01 +0000236 void AnalyzeBlock(MachineBasicBlock &MBB,
Justin Lebar3a7bc572016-02-22 17:51:28 +0000237 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000238 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Kyle Butt6262ca32016-08-24 21:34:24 +0000239 bool isTriangle = false, bool RevBranch = false,
240 bool hasCommonTail = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000241 void AnalyzeBlocks(MachineFunction &MF,
242 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Matthias Braun08f47042016-08-17 02:52:01 +0000243 void InvalidatePreds(MachineBasicBlock &MBB);
Evan Cheng3a51c852007-06-16 09:34:52 +0000244 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
245 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Kyle Butta8c73712016-08-24 21:34:27 +0000246 bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
247 unsigned NumDups1, unsigned NumDups2,
248 bool TClobbersPred, bool FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +0000249 bool RemoveBranch, bool MergeAddEdges);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000250 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
Kyle Butt6262ca32016-08-24 21:34:24 +0000251 unsigned NumDups1, unsigned NumDups2,
252 bool TClobbers, bool FClobbers);
Kyle Butta8c73712016-08-24 21:34:27 +0000253 bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
254 unsigned NumDups1, unsigned NumDups2,
255 bool TClobbers, bool FClobbers);
Evan Chengd0e66912007-05-23 07:23:16 +0000256 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000257 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000258 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000259 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000260 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000261 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000262 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000263 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000264
Evan Chengdebf9c52010-11-03 00:45:17 +0000265 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
266 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000267 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000268 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000269 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000270 }
271
Evan Chengdebf9c52010-11-03 00:45:17 +0000272 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
273 unsigned TCycle, unsigned TExtra,
274 MachineBasicBlock &FBB,
275 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000276 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000277 return TCycle > 0 && FCycle > 0 &&
278 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000279 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000280 }
281
Matthias Braun2c931792016-08-17 02:51:57 +0000282 /// Returns true if Block ends without a terminator.
Evan Chengbe9859e2007-06-07 02:12:15 +0000283 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000284 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000285 }
286
Matthias Braun2c931792016-08-17 02:51:57 +0000287 /// Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000288 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
289 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000290 int Incr1 = (C1->Kind == ICDiamond)
291 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
292 int Incr2 = (C2->Kind == ICDiamond)
293 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
294 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000295 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000296 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000297 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000298 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000299 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000300 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000301 // Favors diamond over triangle, etc.
302 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
303 return true;
304 else if (C1->Kind == C2->Kind)
305 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
306 }
307 }
308 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000309 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000310 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000311
Evan Chengf5e53a52007-05-16 02:00:57 +0000312 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000313}
Evan Chengf5e53a52007-05-16 02:00:57 +0000314
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000315char &llvm::IfConverterID = IfConverter::ID;
316
Matthias Braun1527baa2017-05-25 21:26:32 +0000317INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000318INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Matthias Braun1527baa2017-05-25 21:26:32 +0000319INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000320
Evan Chengf5e53a52007-05-16 02:00:57 +0000321bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Matthias Braun8b38ffa2016-10-24 23:23:02 +0000322 if (skipFunction(*MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000323 return false;
324
Eric Christopher3d4276f2015-01-27 07:31:29 +0000325 const TargetSubtargetInfo &ST = MF.getSubtarget();
326 TLI = ST.getTargetLowering();
327 TII = ST.getInstrInfo();
328 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000329 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000330 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000331 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000332 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000333
Evan Chengf5e53a52007-05-16 02:00:57 +0000334 if (!TII) return false;
335
Evan Chengc5adcca2012-06-08 21:53:50 +0000336 PreRegAlloc = MRI->isSSA();
337
338 bool BFChange = false;
339 if (!PreRegAlloc) {
340 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000341 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000342 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000343 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000344 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000345
David Greene72e47cd2010-01-04 22:02:01 +0000346 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000347 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000348
349 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000350 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000351 return false;
352 }
David Greene72e47cd2010-01-04 22:02:01 +0000353 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000354
Evan Chengf5e53a52007-05-16 02:00:57 +0000355 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000356 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000357
Justin Lebar3a7bc572016-02-22 17:51:28 +0000358 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000359 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000360 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
361 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
362 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000363 // Do an initial analysis for each basic block and find all the potential
364 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000365 bool Change = false;
366 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000367 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000368 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000369 Tokens.pop_back();
370 BBInfo &BBI = Token->BBI;
371 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000372 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000373 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000374
Evan Cheng4dd31a72007-06-11 22:26:22 +0000375 // If the block has been evicted out of the queue or it has already been
376 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000377 if (BBI.IsDone)
378 BBI.IsEnqueued = false;
379 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000380 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000381
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000382 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000383
Evan Cheng312b7232007-06-04 06:47:22 +0000384 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000385 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000386 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000387 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000388 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000389 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000390 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000391 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
392 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000393 << "): BB#" << BBI.BB->getNumber() << " ("
394 << ((Kind == ICSimpleFalse)
395 ? BBI.FalseBB->getNumber()
396 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000397 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000398 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000399 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000400 if (isFalse) ++NumSimpleFalse;
401 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000402 }
Evan Cheng312b7232007-06-04 06:47:22 +0000403 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000404 }
Evan Chengd0e66912007-05-23 07:23:16 +0000405 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000406 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000407 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000408 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000409 bool isFalse = Kind == ICTriangleFalse;
410 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000411 if (DisableTriangle && !isFalse && !isRev) break;
412 if (DisableTriangleR && !isFalse && isRev) break;
413 if (DisableTriangleF && isFalse && !isRev) break;
414 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000415 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000416 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000417 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000418 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000419 DEBUG(dbgs() << " rev");
420 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000421 << BBI.TrueBB->getNumber() << ",F:"
422 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000423 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000424 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000425 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000426 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000427 if (isRev) ++NumTriangleFRev;
428 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000429 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000430 if (isRev) ++NumTriangleRev;
431 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000432 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000433 }
Evan Chengd0e66912007-05-23 07:23:16 +0000434 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000435 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000436 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000437 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000438 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000439 << BBI.TrueBB->getNumber() << ",F:"
440 << BBI.FalseBB->getNumber() << ") ");
Kyle Butt6262ca32016-08-24 21:34:24 +0000441 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
442 Token->TClobbersPred,
443 Token->FClobbersPred);
David Greene72e47cd2010-01-04 22:02:01 +0000444 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000445 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000446 break;
447 }
Kyle Butta8c73712016-08-24 21:34:27 +0000448 case ICForkedDiamond: {
449 if (DisableForkedDiamond) break;
450 DEBUG(dbgs() << "Ifcvt (Forked Diamond): BB#"
451 << BBI.BB->getNumber() << " (T:"
452 << BBI.TrueBB->getNumber() << ",F:"
453 << BBI.FalseBB->getNumber() << ") ");
454 RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
455 Token->TClobbersPred,
456 Token->FClobbersPred);
457 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
458 if (RetVal) ++NumForkedDiamonds;
459 break;
460 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000461 }
462
Krzysztof Parzyszek6ca02b22017-09-14 15:53:11 +0000463 if (RetVal && MRI->tracksLiveness())
464 recomputeLivenessFlags(*BBI.BB);
465
Evan Cheng312b7232007-06-04 06:47:22 +0000466 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000467
Evan Cheng92fb5452007-06-15 07:36:12 +0000468 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
469 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
470 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000471 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000472 }
Evan Chengd0e66912007-05-23 07:23:16 +0000473
Evan Chengd0e66912007-05-23 07:23:16 +0000474 if (!Change)
475 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000476 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000477 }
Evan Cheng478b8052007-05-18 01:55:58 +0000478
Evan Cheng3a51c852007-06-16 09:34:52 +0000479 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000480 BBAnalysis.clear();
481
Evan Chengcf9e8a92010-06-18 22:17:13 +0000482 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000483 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000484 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000485 getAnalysisIfAvailable<MachineModuleInfo>());
486 }
487
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000488 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000489 return MadeChange;
490}
491
Matthias Braun2c931792016-08-17 02:51:57 +0000492/// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000493static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000494 MachineBasicBlock *TrueBB) {
Matthias Braunb1e05582016-08-17 02:51:59 +0000495 for (MachineBasicBlock *SuccBB : BB->successors()) {
Evan Cheng0f745da2007-05-18 00:20:58 +0000496 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000497 return SuccBB;
498 }
Craig Topperc0196b12014-04-14 00:51:57 +0000499 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000500}
501
Matthias Braun2c931792016-08-17 02:51:57 +0000502/// Reverse the condition of the end of the block branch. Swap block's 'true'
503/// and 'false' successors.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000504bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000505 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000506 if (!TII->reverseBranchCondition(BBI.BrCond)) {
507 TII->removeBranch(*BBI.BB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000508 TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000509 std::swap(BBI.TrueBB, BBI.FalseBB);
510 return true;
511 }
512 return false;
513}
514
Matthias Braun2c931792016-08-17 02:51:57 +0000515/// Returns the next block in the function blocks ordering. If it is the end,
516/// returns NULL.
Matthias Braun08f47042016-08-17 02:52:01 +0000517static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
518 MachineFunction::iterator I = MBB.getIterator();
519 MachineFunction::iterator E = MBB.getParent()->end();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000520 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000521 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000522 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000523}
524
Matthias Braun2c931792016-08-17 02:51:57 +0000525/// Returns true if the 'true' block (along with its predecessor) forms a valid
526/// simple shape for ifcvt. It also returns the number of instructions that the
527/// ifcvt would need to duplicate if performed in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000528bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000529 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000530 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000531 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000532 return false;
533
Evan Chenga955c022007-06-19 21:45:13 +0000534 if (TrueBBI.IsBrAnalyzable)
535 return false;
536
Evan Cheng23402fc2007-06-15 21:18:05 +0000537 if (TrueBBI.BB->pred_size() > 1) {
538 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000539 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000540 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000541 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000542 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000543 }
544
Evan Chenga955c022007-06-19 21:45:13 +0000545 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000546}
547
Matthias Braun2c931792016-08-17 02:51:57 +0000548/// Returns true if the 'true' and 'false' blocks (along with their common
549/// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
550/// true, it checks if 'true' block's false branch branches to the 'false' block
551/// rather than the other way around. It also returns the number of instructions
552/// that the ifcvt would need to duplicate if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000553bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000554 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000555 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000556 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000557 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000558 return false;
559
Evan Cheng23402fc2007-06-15 21:18:05 +0000560 if (TrueBBI.BB->pred_size() > 1) {
561 if (TrueBBI.CannotBeCopied)
562 return false;
563
Evan Cheng92fb5452007-06-15 07:36:12 +0000564 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000565 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000566 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000567 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000568 --Size;
569 else {
570 MachineBasicBlock *FExit = FalseBranch
571 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
572 if (FExit)
573 // Require a conditional branch
574 ++Size;
575 }
576 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000577 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000578 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000579 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000580 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000581
Evan Cheng7783f822007-06-08 09:36:04 +0000582 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
583 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000584 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000585 if (++I == TrueBBI.BB->getParent()->end())
586 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000587 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000588 }
Evan Cheng7783f822007-06-08 09:36:04 +0000589 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000590}
591
Kyle Butt4f0e2872016-08-06 01:52:33 +0000592/// Count duplicated instructions and move the iterators to show where they
593/// are.
594/// @param TIB True Iterator Begin
595/// @param FIB False Iterator Begin
596/// These two iterators initially point to the first instruction of the two
597/// blocks, and finally point to the first non-shared instruction.
598/// @param TIE True Iterator End
599/// @param FIE False Iterator End
600/// These two iterators initially point to End() for the two blocks() and
601/// finally point to the first shared instruction in the tail.
602/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
603/// two blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000604/// @param Dups1 count of duplicated instructions at the beginning of the 2
605/// blocks.
606/// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
607/// @param SkipUnconditionalBranches if true, Don't make sure that
608/// unconditional branches at the end of the blocks are the same. True is
609/// passed when the blocks are analyzable to allow for fallthrough to be
610/// handled.
611/// @return false if the shared portion prevents if conversion.
612bool IfConverter::CountDuplicatedInstructions(
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000613 MachineBasicBlock::iterator &TIB,
614 MachineBasicBlock::iterator &FIB,
615 MachineBasicBlock::iterator &TIE,
616 MachineBasicBlock::iterator &FIE,
617 unsigned &Dups1, unsigned &Dups2,
618 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
Kyle Butt6262ca32016-08-24 21:34:24 +0000619 bool SkipUnconditionalBranches) const {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000620
Bob Wilsone1961fe2010-10-26 00:02:24 +0000621 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000622 // Skip dbg_value instructions. These do not count.
Florian Hahn3c8b8c92016-12-16 11:10:26 +0000623 TIB = skipDebugInstructionsForward(TIB, TIE);
Florian Hahn3c8b8c92016-12-16 11:10:26 +0000624 FIB = skipDebugInstructionsForward(FIB, FIE);
Kyle Buttc4614b32017-01-26 20:02:47 +0000625 if (TIB == TIE || FIB == FIE)
Kyle Buttfe916822016-08-06 01:52:31 +0000626 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000627 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000628 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000629 // A pred-clobbering instruction in the shared portion prevents
630 // if-conversion.
631 std::vector<MachineOperand> PredDefs;
632 if (TII->DefinesPredicate(*TIB, PredDefs))
633 return false;
Kyle Butt93e94e82016-09-02 01:20:06 +0000634 // If we get all the way to the branch instructions, don't count them.
635 if (!TIB->isBranch())
636 ++Dups1;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000637 ++TIB;
638 ++FIB;
639 }
640
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000641 // Check for already containing all of the block.
642 if (TIB == TIE || FIB == FIE)
Kyle Butt6262ca32016-08-24 21:34:24 +0000643 return true;
Kyle Buttd76755e2016-08-18 22:09:23 +0000644 // Now, in preparation for counting duplicate instructions at the ends of the
Kyle Buttc4614b32017-01-26 20:02:47 +0000645 // blocks, switch to reverse_iterators. Note that getReverse() returns an
646 // iterator that points to the same instruction, unlike std::reverse_iterator.
647 // We have to do our own shifting so that we get the same range.
648 MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
649 MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
650 const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
651 const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
Kyle Buttd76755e2016-08-18 22:09:23 +0000652
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000653 if (!TBB.succ_empty() || !FBB.succ_empty()) {
Kyle Butt6262ca32016-08-24 21:34:24 +0000654 if (SkipUnconditionalBranches) {
Kyle Buttc4614b32017-01-26 20:02:47 +0000655 while (RTIE != RTIB && RTIE->isUnconditionalBranch())
656 ++RTIE;
657 while (RFIE != RFIB && RFIE->isUnconditionalBranch())
658 ++RFIE;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000659 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000660 }
661
Bob Wilsone1961fe2010-10-26 00:02:24 +0000662 // Count duplicate instructions at the ends of the blocks.
Kyle Buttc4614b32017-01-26 20:02:47 +0000663 while (RTIE != RTIB && RFIE != RFIB) {
Bob Wilsone1961fe2010-10-26 00:02:24 +0000664 // Skip dbg_value instructions. These do not count.
Kyle Buttc4614b32017-01-26 20:02:47 +0000665 // Note that these are reverse iterators going forward.
666 RTIE = skipDebugInstructionsForward(RTIE, RTIB);
667 RFIE = skipDebugInstructionsForward(RFIE, RFIB);
668 if (RTIE == RTIB || RFIE == RFIB)
Kyle Buttfe916822016-08-06 01:52:31 +0000669 break;
Kyle Buttc4614b32017-01-26 20:02:47 +0000670 if (!RTIE->isIdenticalTo(*RFIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000671 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000672 // We have to verify that any branch instructions are the same, and then we
673 // don't count them toward the # of duplicate instructions.
Kyle Buttc4614b32017-01-26 20:02:47 +0000674 if (!RTIE->isBranch())
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000675 ++Dups2;
Kyle Buttc4614b32017-01-26 20:02:47 +0000676 ++RTIE;
677 ++RFIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000678 }
Kyle Buttc4614b32017-01-26 20:02:47 +0000679 TIE = std::next(RTIE.getReverse());
680 FIE = std::next(RFIE.getReverse());
Kyle Butt6262ca32016-08-24 21:34:24 +0000681 return true;
682}
683
684/// RescanInstructions - Run ScanInstructions on a pair of blocks.
685/// @param TIB - True Iterator Begin, points to first non-shared instruction
686/// @param FIB - False Iterator Begin, points to first non-shared instruction
687/// @param TIE - True Iterator End, points past last non-shared instruction
688/// @param FIE - False Iterator End, points past last non-shared instruction
689/// @param TrueBBI - BBInfo to update for the true block.
690/// @param FalseBBI - BBInfo to update for the false block.
691/// @returns - false if either block cannot be predicated or if both blocks end
692/// with a predicate-clobbering instruction.
693bool IfConverter::RescanInstructions(
694 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
695 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
696 BBInfo &TrueBBI, BBInfo &FalseBBI) const {
697 bool BranchUnpredicable = true;
698 TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
699 ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
700 if (TrueBBI.IsUnpredicable)
701 return false;
702 ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
703 if (FalseBBI.IsUnpredicable)
704 return false;
705 if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
706 return false;
707 return true;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000708}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000709
Kyle Butt092c4dd2016-08-29 18:27:12 +0000710#ifndef NDEBUG
711static void verifySameBranchInstructions(
712 MachineBasicBlock *MBB1,
713 MachineBasicBlock *MBB2) {
Kyle Buttc4614b32017-01-26 20:02:47 +0000714 const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
715 const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
716 MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
717 MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
718 while (E1 != B1 && E2 != B2) {
719 skipDebugInstructionsForward(E1, B1);
720 skipDebugInstructionsForward(E2, B2);
721 if (E1 == B1 && E2 == B2)
Kyle Butt092c4dd2016-08-29 18:27:12 +0000722 break;
723
Kyle Buttc4614b32017-01-26 20:02:47 +0000724 if (E1 == B1) {
Kyle Butt092c4dd2016-08-29 18:27:12 +0000725 assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
726 break;
727 }
Kyle Buttc4614b32017-01-26 20:02:47 +0000728 if (E2 == B2) {
Kyle Butt092c4dd2016-08-29 18:27:12 +0000729 assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
730 break;
731 }
732
733 if (E1->isBranch() || E2->isBranch())
734 assert(E1->isIdenticalTo(*E2) &&
735 "Branch mis-match, branch instructions don't match.");
736 else
737 break;
Kyle Buttc4614b32017-01-26 20:02:47 +0000738 ++E1;
739 ++E2;
Kyle Butt092c4dd2016-08-29 18:27:12 +0000740 }
741}
742#endif
743
Kyle Butta8c73712016-08-24 21:34:27 +0000744/// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
745/// with their common predecessor) form a diamond if a common tail block is
746/// extracted.
747/// While not strictly a diamond, this pattern would form a diamond if
748/// tail-merging had merged the shared tails.
749/// EBB
750/// _/ \_
751/// | |
752/// TBB FBB
753/// / \ / \
754/// FalseBB TrueBB FalseBB
755/// Currently only handles analyzable branches.
756/// Specifically excludes actual diamonds to avoid overlap.
757bool IfConverter::ValidForkedDiamond(
758 BBInfo &TrueBBI, BBInfo &FalseBBI,
759 unsigned &Dups1, unsigned &Dups2,
760 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
761 Dups1 = Dups2 = 0;
762 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
763 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
764 return false;
765
766 if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
767 return false;
768 // Don't IfConvert blocks that can't be folded into their predecessor.
769 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
770 return false;
771
772 // This function is specifically looking for conditional tails, as
773 // unconditional tails are already handled by the standard diamond case.
774 if (TrueBBI.BrCond.size() == 0 ||
775 FalseBBI.BrCond.size() == 0)
776 return false;
777
778 MachineBasicBlock *TT = TrueBBI.TrueBB;
779 MachineBasicBlock *TF = TrueBBI.FalseBB;
780 MachineBasicBlock *FT = FalseBBI.TrueBB;
781 MachineBasicBlock *FF = FalseBBI.FalseBB;
782
783 if (!TT)
784 TT = getNextBlock(*TrueBBI.BB);
785 if (!TF)
786 TF = getNextBlock(*TrueBBI.BB);
787 if (!FT)
788 FT = getNextBlock(*FalseBBI.BB);
789 if (!FF)
790 FF = getNextBlock(*FalseBBI.BB);
791
792 if (!TT || !TF)
793 return false;
794
795 // Check successors. If they don't match, bail.
796 if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
797 return false;
798
799 bool FalseReversed = false;
800 if (TF == FT && TT == FF) {
801 // If the branches are opposing, but we can't reverse, don't do it.
802 if (!FalseBBI.IsBrReversible)
803 return false;
804 FalseReversed = true;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000805 reverseBranchCondition(FalseBBI);
Kyle Butta8c73712016-08-24 21:34:27 +0000806 }
807 auto UnReverseOnExit = make_scope_exit([&]() {
808 if (FalseReversed)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000809 reverseBranchCondition(FalseBBI);
Kyle Butta8c73712016-08-24 21:34:27 +0000810 });
811
812 // Count duplicate instructions at the beginning of the true and false blocks.
813 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
814 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
815 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
816 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
817 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
818 *TrueBBI.BB, *FalseBBI.BB,
819 /* SkipUnconditionalBranches */ true))
820 return false;
821
822 TrueBBICalc.BB = TrueBBI.BB;
823 FalseBBICalc.BB = FalseBBI.BB;
824 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
825 return false;
826
827 // The size is used to decide whether to if-convert, and the shared portions
828 // are subtracted off. Because of the subtraction, we just use the size that
829 // was calculated by the original ScanInstructions, as it is correct.
830 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
831 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
832 return true;
833}
834
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000835/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
836/// with their common predecessor) forms a valid diamond shape for ifcvt.
Kyle Butt6262ca32016-08-24 21:34:24 +0000837bool IfConverter::ValidDiamond(
838 BBInfo &TrueBBI, BBInfo &FalseBBI,
839 unsigned &Dups1, unsigned &Dups2,
840 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000841 Dups1 = Dups2 = 0;
842 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
843 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
844 return false;
845
846 MachineBasicBlock *TT = TrueBBI.TrueBB;
847 MachineBasicBlock *FT = FalseBBI.TrueBB;
848
849 if (!TT && blockAlwaysFallThrough(TrueBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000850 TT = getNextBlock(*TrueBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000851 if (!FT && blockAlwaysFallThrough(FalseBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000852 FT = getNextBlock(*FalseBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000853 if (TT != FT)
854 return false;
855 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
856 return false;
857 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
858 return false;
859
860 // FIXME: Allow true block to have an early exit?
Kyle Butt6262ca32016-08-24 21:34:24 +0000861 if (TrueBBI.FalseBB || FalseBBI.FalseBB)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000862 return false;
863
864 // Count duplicate instructions at the beginning and end of the true and
865 // false blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000866 // Skip unconditional branches only if we are considering an analyzable
867 // diamond. Otherwise the branches must be the same.
868 bool SkipUnconditionalBranches =
869 TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000870 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
871 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
872 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
873 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
Kyle Butt6262ca32016-08-24 21:34:24 +0000874 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
875 *TrueBBI.BB, *FalseBBI.BB,
876 SkipUnconditionalBranches))
877 return false;
878
879 TrueBBICalc.BB = TrueBBI.BB;
880 FalseBBICalc.BB = FalseBBI.BB;
881 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
882 return false;
883 // The size is used to decide whether to if-convert, and the shared portions
884 // are subtracted off. Because of the subtraction, we just use the size that
885 // was calculated by the original ScanInstructions, as it is correct.
886 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
887 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000888 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000889}
890
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000891/// AnalyzeBranches - Look at the branches at the end of a block to determine if
892/// the block is predicable.
893void IfConverter::AnalyzeBranches(BBInfo &BBI) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000894 if (BBI.IsDone)
895 return;
896
Craig Topperc0196b12014-04-14 00:51:57 +0000897 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000898 BBI.BrCond.clear();
899 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000900 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Kyle Butta8c73712016-08-24 21:34:27 +0000901 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
902 BBI.IsBrReversible = (RevCond.size() == 0) ||
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000903 !TII->reverseBranchCondition(RevCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000904 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000905
906 if (BBI.BrCond.size()) {
907 // No false branch. This BB must end with a conditional branch and a
908 // fallthrough.
909 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000910 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000911 if (!BBI.FalseBB) {
912 // Malformed bcc? True and false blocks are the same?
913 BBI.IsUnpredicable = true;
Evan Chengb9bff582009-06-15 21:24:34 +0000914 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000915 }
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000916}
Evan Cheng4dd31a72007-06-11 22:26:22 +0000917
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000918/// ScanInstructions - Scan all the instructions in the block to determine if
919/// the block is predicable. In most cases, that means all the instructions
920/// in the block are isPredicable(). Also checks if the block contains any
921/// instruction which can clobber a predicate (e.g. condition code register).
922/// If so, the block is not predicable unless it's the last instruction.
923void IfConverter::ScanInstructions(BBInfo &BBI,
924 MachineBasicBlock::iterator &Begin,
Kyle Butt6262ca32016-08-24 21:34:24 +0000925 MachineBasicBlock::iterator &End,
926 bool BranchUnpredicable) const {
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000927 if (BBI.IsDone || BBI.IsUnpredicable)
928 return;
929
930 bool AlreadyPredicated = !BBI.Predicate.empty();
931
Evan Cheng4dd31a72007-06-11 22:26:22 +0000932 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000933 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000934 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000935 BBI.ClobbersPred = false;
Matthias Braunb1e05582016-08-17 02:51:59 +0000936 for (MachineInstr &MI : make_range(Begin, End)) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000937 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000938 continue;
939
Justin Lebar7dba2e02016-04-15 01:38:41 +0000940 // It's unsafe to duplicate convergent instructions in this context, so set
941 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
942 // following CFG, which is subject to our "simple" transformation.
943 //
944 // BB0 // if (c1) goto BB1; else goto BB2;
945 // / \
946 // BB1 |
947 // | BB2 // if (c2) goto TBB; else goto FBB;
948 // | / |
949 // | / |
950 // TBB |
951 // | |
952 // | FBB
953 // |
954 // exit
955 //
956 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
957 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
958 // TBB contains a convergent instruction. This is safe iff doing so does
959 // not add a control-flow dependency to the convergent instruction -- i.e.,
960 // it's safe iff the set of control flows that leads us to the convergent
961 // instruction does not get smaller after the transformation.
962 //
963 // Originally we executed TBB if c1 || c2. After the transformation, there
964 // are two copies of TBB's instructions. We get to the first if c1, and we
965 // get to the second if !c1 && c2.
966 //
967 // There are clearly fewer ways to satisfy the condition "c1" than
968 // "c1 || c2". Since we've shrunk the set of control flows which lead to
969 // our convergent instruction, the transformation is unsafe.
970 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000971 BBI.CannotBeCopied = true;
972
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000973 bool isPredicated = TII->isPredicated(MI);
974 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000975
Kyle Butt6262ca32016-08-24 21:34:24 +0000976 if (BranchUnpredicable && MI.isBranch()) {
977 BBI.IsUnpredicable = true;
978 return;
979 }
980
Joey Goulya5153cb2013-09-09 14:21:49 +0000981 // A conditional branch is not predicable, but it may be eliminated.
982 if (isCondBr)
983 continue;
984
985 if (!isPredicated) {
986 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000987 unsigned ExtraPredCost = TII->getPredicationCost(MI);
988 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000989 if (NumCycles > 1)
990 BBI.ExtraCost += NumCycles-1;
991 BBI.ExtraCost2 += ExtraPredCost;
992 } else if (!AlreadyPredicated) {
993 // FIXME: This instruction is already predicated before the
994 // if-conversion pass. It's probably something like a conditional move.
995 // Mark this block unpredicable for now.
996 BBI.IsUnpredicable = true;
997 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000998 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000999
1000 if (BBI.ClobbersPred && !isPredicated) {
1001 // Predicate modification instruction should end the block (except for
1002 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +00001003 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +00001004 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001005 BBI.IsUnpredicable = true;
1006 return;
1007 }
1008
Evan Chengfbc73092007-07-10 17:50:43 +00001009 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1010 // still potentially predicable.
1011 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001012 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001013 BBI.ClobbersPred = true;
1014
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001015 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001016 BBI.IsUnpredicable = true;
1017 return;
1018 }
1019 }
1020}
1021
Matthias Braun2c931792016-08-17 02:51:57 +00001022/// Determine if the block is a suitable candidate to be predicated by the
1023/// specified predicate.
Kyle Butt6262ca32016-08-24 21:34:24 +00001024/// @param BBI BBInfo for the block to check
1025/// @param Pred Predicate array for the branch that leads to BBI
1026/// @param isTriangle true if the Analysis is for a triangle
1027/// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1028/// case
1029/// @param hasCommonTail true if BBI shares a tail with a sibling block that
1030/// contains any instruction that would make the block unpredicable.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001031bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001032 SmallVectorImpl<MachineOperand> &Pred,
Kyle Butt6262ca32016-08-24 21:34:24 +00001033 bool isTriangle, bool RevBranch,
1034 bool hasCommonTail) {
Evan Cheng3a51c852007-06-16 09:34:52 +00001035 // If the block is dead or unpredicable, then it cannot be predicated.
Kyle Butt6262ca32016-08-24 21:34:24 +00001036 // Two blocks may share a common unpredicable tail, but this doesn't prevent
1037 // them from being if-converted. The non-shared portion is assumed to have
1038 // been checked
1039 if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001040 return false;
1041
Ahmed Bougacha7173b662015-03-21 01:23:15 +00001042 // If it is already predicated but we couldn't analyze its terminator, the
1043 // latter might fallthrough, but we can't determine where to.
1044 // Conservatively avoid if-converting again.
1045 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1046 return false;
1047
Quentin Colombetbdab2272013-07-24 20:20:37 +00001048 // If it is already predicated, check if the new predicate subsumes
1049 // its predicate.
1050 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001051 return false;
1052
Kyle Butt6262ca32016-08-24 21:34:24 +00001053 if (!hasCommonTail && BBI.BrCond.size()) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001054 if (!isTriangle)
1055 return false;
1056
Bob Wilson2371f4f2009-05-13 23:25:24 +00001057 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +00001058 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1059 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +00001060 if (RevBranch) {
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001061 if (TII->reverseBranchCondition(Cond))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001062 return false;
1063 }
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001064 if (TII->reverseBranchCondition(RevPred) ||
Evan Cheng4dd31a72007-06-11 22:26:22 +00001065 !TII->SubsumesPredicate(Cond, RevPred))
1066 return false;
1067 }
1068
1069 return true;
1070}
1071
Matthias Braun2c931792016-08-17 02:51:57 +00001072/// Analyze the structure of the sub-CFG starting from the specified block.
1073/// Record its successors and whether it looks like an if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001074void IfConverter::AnalyzeBlock(
Matthias Braun08f47042016-08-17 02:52:01 +00001075 MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001076 struct BBState {
Matthias Braun08f47042016-08-17 02:52:01 +00001077 BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001078 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +00001079
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001080 /// This flag is true if MBB's successors have been analyzed.
1081 bool SuccsAnalyzed;
1082 };
Evan Cheng0f745da2007-05-18 00:20:58 +00001083
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001084 // Push MBB to the stack.
1085 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001086
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001087 while (!BBStack.empty()) {
1088 BBState &State = BBStack.back();
1089 MachineBasicBlock *BB = State.MBB;
1090 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +00001091
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001092 if (!State.SuccsAnalyzed) {
1093 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1094 BBStack.pop_back();
1095 continue;
1096 }
Evan Cheng9030b982007-06-06 10:16:17 +00001097
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001098 BBI.BB = BB;
1099 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +00001100
Kyle Butt54bf3ce2016-08-06 01:52:34 +00001101 AnalyzeBranches(BBI);
1102 MachineBasicBlock::iterator Begin = BBI.BB->begin();
1103 MachineBasicBlock::iterator End = BBI.BB->end();
1104 ScanInstructions(BBI, Begin, End);
Evan Chengb9bff582009-06-15 21:24:34 +00001105
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001106 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1107 // not considered for ifcvt anymore.
1108 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1109 BBI.IsBeingAnalyzed = false;
1110 BBI.IsAnalyzed = true;
1111 BBStack.pop_back();
1112 continue;
1113 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001114
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001115 // Do not ifcvt if either path is a back edge to the entry block.
1116 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1117 BBI.IsBeingAnalyzed = false;
1118 BBI.IsAnalyzed = true;
1119 BBStack.pop_back();
1120 continue;
1121 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001122
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001123 // Do not ifcvt if true and false fallthrough blocks are the same.
1124 if (!BBI.FalseBB) {
1125 BBI.IsBeingAnalyzed = false;
1126 BBI.IsAnalyzed = true;
1127 BBStack.pop_back();
1128 continue;
1129 }
Evan Cheng7783f822007-06-08 09:36:04 +00001130
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001131 // Push the False and True blocks to the stack.
1132 State.SuccsAnalyzed = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001133 BBStack.push_back(*BBI.FalseBB);
1134 BBStack.push_back(*BBI.TrueBB);
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001135 continue;
1136 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +00001137
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001138 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1139 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +00001140
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001141 if (TrueBBI.IsDone && FalseBBI.IsDone) {
1142 BBI.IsBeingAnalyzed = false;
1143 BBI.IsAnalyzed = true;
1144 BBStack.pop_back();
1145 continue;
1146 }
1147
1148 SmallVector<MachineOperand, 4>
1149 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001150 bool CanRevCond = !TII->reverseBranchCondition(RevCond);
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001151
1152 unsigned Dups = 0;
1153 unsigned Dups2 = 0;
1154 bool TNeedSub = !TrueBBI.Predicate.empty();
1155 bool FNeedSub = !FalseBBI.Predicate.empty();
1156 bool Enqueued = false;
1157
1158 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1159
Kyle Butt6262ca32016-08-24 21:34:24 +00001160 if (CanRevCond) {
1161 BBInfo TrueBBICalc, FalseBBICalc;
Kyle Butta8c73712016-08-24 21:34:27 +00001162 auto feasibleDiamond = [&]() {
1163 bool MeetsSize = MeetIfcvtSizeLimit(
1164 *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1165 TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1166 *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1167 FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1168 Prediction);
1169 bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1170 /* IsTriangle */ false, /* RevCond */ false,
1171 /* hasCommonTail */ true);
1172 bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1173 /* IsTriangle */ false, /* RevCond */ false,
1174 /* hasCommonTail */ true);
1175 return MeetsSize && TrueFeasible && FalseFeasible;
1176 };
1177
Kyle Butt6262ca32016-08-24 21:34:24 +00001178 if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
Kyle Butta8c73712016-08-24 21:34:27 +00001179 TrueBBICalc, FalseBBICalc)) {
1180 if (feasibleDiamond()) {
1181 // Diamond:
1182 // EBB
1183 // / \_
1184 // | |
1185 // TBB FBB
1186 // \ /
1187 // TailBB
1188 // Note TailBB can be empty.
1189 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1190 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1191 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1192 Enqueued = true;
1193 }
1194 } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1195 TrueBBICalc, FalseBBICalc)) {
1196 if (feasibleDiamond()) {
1197 // ForkedDiamond:
1198 // if TBB and FBB have a common tail that includes their conditional
1199 // branch instructions, then we can If Convert this pattern.
1200 // EBB
1201 // _/ \_
1202 // | |
1203 // TBB FBB
1204 // / \ / \
1205 // FalseBB TrueBB FalseBB
1206 //
1207 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1208 BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1209 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1210 Enqueued = true;
1211 }
Kyle Butt6262ca32016-08-24 21:34:24 +00001212 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001213 }
1214
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001215 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1216 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1217 TrueBBI.ExtraCost2, Prediction) &&
1218 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1219 // Triangle:
1220 // EBB
1221 // | \_
1222 // | |
1223 // | TBB
1224 // | /
1225 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001226 Tokens.push_back(
1227 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001228 Enqueued = true;
1229 }
1230
1231 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1232 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1233 TrueBBI.ExtraCost2, Prediction) &&
1234 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001235 Tokens.push_back(
1236 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001237 Enqueued = true;
1238 }
1239
1240 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1241 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1242 TrueBBI.ExtraCost2, Prediction) &&
1243 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1244 // Simple (split, no rejoin):
1245 // EBB
1246 // | \_
1247 // | |
1248 // | TBB---> exit
1249 // |
1250 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001251 Tokens.push_back(
1252 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001253 Enqueued = true;
1254 }
1255
1256 if (CanRevCond) {
1257 // Try the other path...
1258 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1259 Prediction.getCompl()) &&
1260 MeetIfcvtSizeLimit(*FalseBBI.BB,
1261 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1262 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1263 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001264 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1265 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001266 Enqueued = true;
1267 }
1268
1269 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1270 Prediction.getCompl()) &&
1271 MeetIfcvtSizeLimit(*FalseBBI.BB,
1272 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +00001273 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +00001274 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001275 Tokens.push_back(
1276 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001277 Enqueued = true;
1278 }
1279
1280 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1281 MeetIfcvtSizeLimit(*FalseBBI.BB,
1282 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1283 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1284 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001285 Tokens.push_back(
1286 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001287 Enqueued = true;
1288 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001289 }
1290
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001291 BBI.IsEnqueued = Enqueued;
1292 BBI.IsBeingAnalyzed = false;
1293 BBI.IsAnalyzed = true;
1294 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001295 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001296}
1297
Matthias Braun2c931792016-08-17 02:51:57 +00001298/// Analyze all blocks and find entries for all if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001299void IfConverter::AnalyzeBlocks(
1300 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001301 for (MachineBasicBlock &MBB : MF)
Matthias Braun08f47042016-08-17 02:52:01 +00001302 AnalyzeBlock(MBB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001303
Evan Cheng20e05992007-06-01 00:12:12 +00001304 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +00001305 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001306}
1307
Matthias Braun2c931792016-08-17 02:51:57 +00001308/// Returns true either if ToMBB is the next block after MBB or that all the
1309/// intervening blocks are empty (given MBB can fall through to its next block).
Matthias Braun08f47042016-08-17 02:52:01 +00001310static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1311 MachineFunction::iterator PI = MBB.getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001312 MachineFunction::iterator I = std::next(PI);
Matthias Braun08f47042016-08-17 02:52:01 +00001313 MachineFunction::iterator TI = ToMBB.getIterator();
1314 MachineFunction::iterator E = MBB.getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001315 while (I != TI) {
1316 // Check isSuccessor to avoid case where the next block is empty, but
1317 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001318 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001319 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001320 PI = I++;
1321 }
Mikael Holmen21c867c2017-05-10 13:06:13 +00001322 // Finally see if the last I is indeed a successor to PI.
1323 return PI->isSuccessor(&*I);
Evan Chenge26c0912007-05-21 22:22:58 +00001324}
1325
Matthias Braun2c931792016-08-17 02:51:57 +00001326/// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1327/// can be if-converted. If predecessor is already enqueued, dequeue it!
Matthias Braun08f47042016-08-17 02:52:01 +00001328void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1329 for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001330 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Matthias Braun08f47042016-08-17 02:52:01 +00001331 if (PBBI.IsDone || PBBI.BB == &MBB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001332 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001333 PBBI.IsAnalyzed = false;
1334 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001335 }
1336}
1337
Matthias Braun2c931792016-08-17 02:51:57 +00001338/// Inserts an unconditional branch from \p MBB to \p ToMBB.
Matthias Braun08f47042016-08-17 02:52:01 +00001339static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
Evan Chengc2237ce2007-05-29 22:31:16 +00001340 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001341 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001342 SmallVector<MachineOperand, 0> NoCond;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001343 TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001344}
1345
Matthias Braund616ccc2013-10-11 19:04:37 +00001346/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Jonas Paulsson196986c2016-08-03 05:46:35 +00001347/// values defined in MI which are also live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001348static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Jonas Paulsson196986c2016-08-03 05:46:35 +00001349 const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1350 ->getSubtarget().getRegisterInfo();
1351
1352 // Before stepping forward past MI, remember which regs were live
1353 // before MI. This is needed to set the Undef flag only when reg is
1354 // dead.
1355 SparseSet<unsigned> LiveBeforeMI;
1356 LiveBeforeMI.setUniverse(TRI->getNumRegs());
Matthias Braunb1e05582016-08-17 02:51:59 +00001357 for (unsigned Reg : Redefs)
Jonas Paulsson196986c2016-08-03 05:46:35 +00001358 LiveBeforeMI.insert(Reg);
1359
Pete Cooper7605e372015-05-05 20:14:22 +00001360 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001361 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001362
Pete Cooper7605e372015-05-05 20:14:22 +00001363 // Now add the implicit uses for each of the clobbered values.
Matthias Braun08f47042016-08-17 02:52:01 +00001364 for (auto Clobber : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001365 // FIXME: Const cast here is nasty, but better than making StepForward
1366 // take a mutable instruction instead of const.
Matthias Braun08f47042016-08-17 02:52:01 +00001367 unsigned Reg = Clobber.first;
1368 MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
Pete Cooper27483912015-05-06 22:51:04 +00001369 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001370 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001371 if (Op.isRegMask()) {
1372 // First handle regmasks. They clobber any entries in the mask which
1373 // means that we need a def for those registers.
Matthias Braun08f47042016-08-17 02:52:01 +00001374 if (LiveBeforeMI.count(Reg))
1375 MIB.addReg(Reg, RegState::Implicit);
Pete Cooperce9ad752015-05-05 22:09:41 +00001376
1377 // We also need to add an implicit def of this register for the later
1378 // use to read from.
1379 // For the register allocator to have allocated a register clobbered
1380 // by the call which is used later, it must be the case that
1381 // the call doesn't return.
Matthias Braun08f47042016-08-17 02:52:01 +00001382 MIB.addReg(Reg, RegState::Implicit | RegState::Define);
Pete Cooperce9ad752015-05-05 22:09:41 +00001383 continue;
1384 }
Matthias Braun08f47042016-08-17 02:52:01 +00001385 if (LiveBeforeMI.count(Reg))
1386 MIB.addReg(Reg, RegState::Implicit);
Krzysztof Parzyszekdcb1bca2016-09-28 20:07:41 +00001387 else {
1388 bool HasLiveSubReg = false;
1389 for (MCSubRegIterator S(Reg, TRI); S.isValid(); ++S) {
1390 if (!LiveBeforeMI.count(*S))
1391 continue;
1392 HasLiveSubReg = true;
1393 break;
1394 }
1395 if (HasLiveSubReg)
1396 MIB.addReg(Reg, RegState::Implicit);
1397 }
Matthias Braund616ccc2013-10-11 19:04:37 +00001398 }
1399}
1400
Matthias Braun2c931792016-08-17 02:51:57 +00001401/// If convert a simple (split, no rejoin) sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001402bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001403 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1404 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1405 BBInfo *CvtBBI = &TrueBBI;
1406 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001407
Owen Anderson4f6bf042008-08-14 22:49:33 +00001408 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001409 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001410 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001411
Matthias Braun08f47042016-08-17 02:52:01 +00001412 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1413 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001414 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001415 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001416 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001417 BBI.IsAnalyzed = false;
1418 CvtBBI->IsAnalyzed = false;
1419 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001420 }
Evan Chengd0e66912007-05-23 07:23:16 +00001421
Matthias Braun08f47042016-08-17 02:52:01 +00001422 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001423 // Conservatively abort if-conversion if BB's address is taken.
1424 return false;
1425
Evan Cheng3a51c852007-06-16 09:34:52 +00001426 if (Kind == ICSimpleFalse)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001427 if (TII->reverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001428 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001429
Matthias Braun0c989a82016-12-08 00:15:51 +00001430 Redefs.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001431
1432 if (MRI->tracksLiveness()) {
1433 // Initialize liveins to the first BB. These are potentiall redefined by
1434 // predicated instructions.
1435 Redefs.addLiveIns(CvtMBB);
1436 Redefs.addLiveIns(NextMBB);
Matthias Braun11723322017-01-05 20:01:19 +00001437 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001438
Mikael Holmen45bd32f2017-06-26 09:33:04 +00001439 // Remove the branches from the entry so we can add the contents of the true
1440 // block to it.
1441 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1442
Matthias Braun08f47042016-08-17 02:52:01 +00001443 if (CvtMBB.pred_size() > 1) {
Bob Wilson2371f4f2009-05-13 23:25:24 +00001444 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001445 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001446 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001447
Mikael Holmen8b106802017-08-11 06:57:08 +00001448 // Keep the CFG updated.
Matthias Braun08f47042016-08-17 02:52:01 +00001449 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001450 } else {
Mikael Holmen45bd32f2017-06-26 09:33:04 +00001451 // Predicate the instructions in the true block.
Matthias Braun08f47042016-08-17 02:52:01 +00001452 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001453
Mikael Holmen8b106802017-08-11 06:57:08 +00001454 // Merge converted block into entry block. The BB to Cvt edge is removed
1455 // by MergeBlocks.
Evan Cheng92fb5452007-06-15 07:36:12 +00001456 MergeBlocks(BBI, *CvtBBI);
1457 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001458
Evan Chenge4ec9182007-06-06 02:08:52 +00001459 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001460 if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1461 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001462 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001463 // Now ifcvt'd block will look like this:
1464 // BB:
1465 // ...
1466 // t, f = cmp
1467 // if t op
1468 // b BBf
1469 //
1470 // We cannot further ifcvt this block because the unconditional branch
1471 // will have to be predicated on the new condition, that will not be
1472 // available if cmp executes.
1473 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001474 }
Evan Chenge26c0912007-05-21 22:22:58 +00001475
Evan Chengd0e66912007-05-23 07:23:16 +00001476 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001477 if (!IterIfcvt)
1478 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001479 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001480 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001481
1482 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001483 return true;
1484}
1485
Matthias Braun2c931792016-08-17 02:51:57 +00001486/// If convert a triangle sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001487bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001488 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001489 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1490 BBInfo *CvtBBI = &TrueBBI;
1491 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001492 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001493
Owen Anderson4f6bf042008-08-14 22:49:33 +00001494 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001495 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001496 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001497
Matthias Braun08f47042016-08-17 02:52:01 +00001498 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1499 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001500 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001501 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001502 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001503 BBI.IsAnalyzed = false;
1504 CvtBBI->IsAnalyzed = false;
1505 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001506 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001507
Matthias Braun08f47042016-08-17 02:52:01 +00001508 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001509 // Conservatively abort if-conversion if BB's address is taken.
1510 return false;
1511
Evan Cheng3a51c852007-06-16 09:34:52 +00001512 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001513 if (TII->reverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001514 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001515
Evan Cheng3a51c852007-06-16 09:34:52 +00001516 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001517 if (reverseBranchCondition(*CvtBBI)) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001518 // BB has been changed, modify its predecessors (except for this
1519 // one) so they don't get ifcvt'ed based on bad intel.
Matthias Braun08f47042016-08-17 02:52:01 +00001520 for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001521 if (PBB == BBI.BB)
1522 continue;
1523 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1524 if (PBBI.IsEnqueued) {
1525 PBBI.IsAnalyzed = false;
1526 PBBI.IsEnqueued = false;
1527 }
Evan Chengadd97762007-06-14 23:34:09 +00001528 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001529 }
1530 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001531
Bob Wilson45814342010-06-19 05:33:57 +00001532 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001533 // predicated instructions.
Matthias Braun0c989a82016-12-08 00:15:51 +00001534 Redefs.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001535 if (MRI->tracksLiveness()) {
1536 Redefs.addLiveIns(CvtMBB);
1537 Redefs.addLiveIns(NextMBB);
1538 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001539
Craig Topperc0196b12014-04-14 00:51:57 +00001540 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001541 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001542
Manman Renb6819182014-01-29 23:18:47 +00001543 if (HasEarlyExit) {
Matthias Braun08f47042016-08-17 02:52:01 +00001544 // Get probabilities before modifying CvtMBB and BBI.BB.
1545 CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1546 CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1547 BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1548 BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
Manman Renb6819182014-01-29 23:18:47 +00001549 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001550
Mikael Holmen45bd32f2017-06-26 09:33:04 +00001551 // Remove the branches from the entry so we can add the contents of the true
1552 // block to it.
1553 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1554
Matthias Braun08f47042016-08-17 02:52:01 +00001555 if (CvtMBB.pred_size() > 1) {
Bob Wilson2371f4f2009-05-13 23:25:24 +00001556 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001557 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001558 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001559 } else {
1560 // Predicate the 'true' block after removing its branch.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001561 CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
Matthias Braun08f47042016-08-17 02:52:01 +00001562 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001563
Mikael Holmence3ec452017-05-12 06:28:58 +00001564 // Now merge the entry of the triangle with the true block.
Bob Wilson1e5da552010-06-29 00:55:23 +00001565 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001566 }
1567
Mikael Holmen8b106802017-08-11 06:57:08 +00001568 // Keep the CFG updated.
1569 BBI.BB->removeSuccessor(&CvtMBB, true);
1570
Evan Cheng312b7232007-06-04 06:47:22 +00001571 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001572 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001573 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1574 CvtBBI->BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001575 if (TII->reverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001576 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001577
Cong Houd97c1002015-12-01 05:29:22 +00001578 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
Matthias Braun08f47042016-08-17 02:52:01 +00001579 // NewNext = New_Prob(BBI.BB, NextMBB) =
1580 // Prob(BBI.BB, NextMBB) +
1581 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
Cong Houd97c1002015-12-01 05:29:22 +00001582 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
Matthias Braun08f47042016-08-17 02:52:01 +00001583 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1584 auto NewTrueBB = getNextBlock(*BBI.BB);
Cong Houd97c1002015-12-01 05:29:22 +00001585 auto NewNext = BBNext + BBCvt * CvtNext;
David Majnemer42531262016-08-12 03:55:06 +00001586 auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001587 if (NewTrueBBIter != BBI.BB->succ_end())
1588 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001589
1590 auto NewFalse = BBCvt * CvtFalse;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001591 TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
Cong Houd97c1002015-12-01 05:29:22 +00001592 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001593 }
Evan Cheng7783f822007-06-08 09:36:04 +00001594
1595 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001596 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001597 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001598 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001599 bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001600 if (!isFallThrough) {
1601 // Only merge them if the true block does not fallthrough to the false
1602 // block. By not merging them, we make it possible to iteratively
1603 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001604 if (!HasEarlyExit &&
Tobias Grosser8cf785f2017-05-29 06:12:18 +00001605 NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
Matthias Braun08f47042016-08-17 02:52:01 +00001606 !NextMBB.hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001607 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001608 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001609 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001610 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001611 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001612 }
Evan Cheng7783f822007-06-08 09:36:04 +00001613 // Mixed predicated and unpredicated code. This cannot be iteratively
1614 // predicated.
1615 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001616 }
Evan Chenge26c0912007-05-21 22:22:58 +00001617
Evan Chengd0e66912007-05-23 07:23:16 +00001618 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001619 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001620 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001621 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001622 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001623 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001624 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001625
1626 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001627 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001628}
1629
Kyle Butta8c73712016-08-24 21:34:27 +00001630/// Common code shared between diamond conversions.
1631/// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1632/// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1633/// and FalseBBI
1634/// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1635/// and \p FalseBBI
Kyle Butt092c4dd2016-08-29 18:27:12 +00001636/// \p RemoveBranch - Remove the common branch of the two blocks before
1637/// predicating. Only false for unanalyzable fallthrough
1638/// cases. The caller will replace the branch if necessary.
Kyle Butta8c73712016-08-24 21:34:27 +00001639/// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1640/// unanalyzable fallthrough
1641bool IfConverter::IfConvertDiamondCommon(
1642 BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1643 unsigned NumDups1, unsigned NumDups2,
1644 bool TClobbersPred, bool FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001645 bool RemoveBranch, bool MergeAddEdges) {
Evan Chenge26c0912007-05-21 22:22:58 +00001646
Evan Cheng51eb2c32007-06-18 08:37:25 +00001647 if (TrueBBI.IsDone || FalseBBI.IsDone ||
Kyle Butta8c73712016-08-24 21:34:27 +00001648 TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001649 // Something has changed. It's no longer safe to predicate these blocks.
1650 BBI.IsAnalyzed = false;
1651 TrueBBI.IsAnalyzed = false;
1652 FalseBBI.IsAnalyzed = false;
1653 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001654 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001655
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001656 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1657 // Conservatively abort if-conversion if either BB has its address taken.
1658 return false;
1659
Bob Wilson1e5da552010-06-29 00:55:23 +00001660 // Put the predicated instructions from the 'true' block before the
1661 // instructions from the 'false' block, unless the true block would clobber
1662 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001663 BBInfo *BBI1 = &TrueBBI;
1664 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001665 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001666 if (TII->reverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001667 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001668 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1669 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001670
Evan Cheng3a51c852007-06-16 09:34:52 +00001671 // Figure out the more profitable ordering.
1672 bool DoSwap = false;
Kyle Butt6262ca32016-08-24 21:34:24 +00001673 if (TClobbersPred && !FClobbersPred)
Evan Cheng3a51c852007-06-16 09:34:52 +00001674 DoSwap = true;
Kyle Butte31cc842016-09-02 18:29:28 +00001675 else if (!TClobbersPred && !FClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001676 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001677 DoSwap = true;
Kyle Butte31cc842016-09-02 18:29:28 +00001678 } else if (TClobbersPred && FClobbersPred)
1679 llvm_unreachable("Predicate info cannot be clobbered by both sides.");
Evan Cheng3a51c852007-06-16 09:34:52 +00001680 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001681 std::swap(BBI1, BBI2);
1682 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001683 }
Evan Cheng79484222007-06-05 23:46:14 +00001684
Evan Cheng51eb2c32007-06-18 08:37:25 +00001685 // Remove the conditional branch from entry to the blocks.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001686 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001687
Matthias Braun08f47042016-08-17 02:52:01 +00001688 MachineBasicBlock &MBB1 = *BBI1->BB;
1689 MachineBasicBlock &MBB2 = *BBI2->BB;
1690
Krzysztof Parzyszeka003b762016-08-11 18:42:06 +00001691 // Initialize the Redefs:
1692 // - BB2 live-in regs need implicit uses before being redefined by BB1
1693 // instructions.
1694 // - BB1 live-out regs need implicit uses before being redefined by BB2
1695 // instructions. We start with BB1 live-ins so we have the live-out regs
1696 // after tracking the BB1 instructions.
Matthias Braun0c989a82016-12-08 00:15:51 +00001697 Redefs.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001698 if (MRI->tracksLiveness()) {
1699 Redefs.addLiveIns(MBB1);
1700 Redefs.addLiveIns(MBB2);
1701 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001702
Evan Cheng51eb2c32007-06-18 08:37:25 +00001703 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001704 // Skip dbg_value instructions
Matthias Braun08f47042016-08-17 02:52:01 +00001705 MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1706 MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001707 BBI1->NonPredSize -= NumDups1;
1708 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001709
1710 // Skip past the dups on each side separately since there may be
1711 // differing dbg_value entries.
1712 for (unsigned i = 0; i < NumDups1; ++DI1) {
1713 if (!DI1->isDebugValue())
1714 ++i;
1715 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001716 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001717 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001718 if (!DI2->isDebugValue())
1719 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001720 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001721
Matthias Braun11723322017-01-05 20:01:19 +00001722 if (MRI->tracksLiveness()) {
Matthias Braun11723322017-01-05 20:01:19 +00001723 for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
1724 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Dummy;
1725 Redefs.stepForward(MI, Dummy);
1726 }
Matthias Braund616ccc2013-10-11 19:04:37 +00001727 }
Matthias Braun08f47042016-08-17 02:52:01 +00001728 BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1729 MBB2.erase(MBB2.begin(), DI2);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001730
Kyle Butt092c4dd2016-08-29 18:27:12 +00001731 // The branches have been checked to match, so it is safe to remove the branch
1732 // in BB1 and rely on the copy in BB2
1733#ifndef NDEBUG
1734 // Unanalyzable branches must match exactly. Check that now.
1735 if (!BBI1->IsBrAnalyzable)
1736 verifySameBranchInstructions(&MBB1, &MBB2);
1737#endif
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001738 BBI1->NonPredSize -= TII->removeBranch(*BBI1->BB);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001739 // Remove duplicated instructions.
Matthias Braun08f47042016-08-17 02:52:01 +00001740 DI1 = MBB1.end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001741 for (unsigned i = 0; i != NumDups2; ) {
1742 // NumDups2 only counted non-dbg_value instructions, so this won't
1743 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001744 assert(DI1 != MBB1.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001745 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001746 // skip dbg_value instructions
1747 if (!DI1->isDebugValue())
1748 ++i;
1749 }
Matthias Braun08f47042016-08-17 02:52:01 +00001750 MBB1.erase(DI1, MBB1.end());
Evan Cheng79484222007-06-05 23:46:14 +00001751
Kyle Butta8c73712016-08-24 21:34:27 +00001752 DI2 = BBI2->BB->end();
Kyle Butt092c4dd2016-08-29 18:27:12 +00001753 // The branches have been checked to match. Skip over the branch in the false
1754 // block so that we don't try to predicate it.
1755 if (RemoveBranch)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001756 BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
Kyle Butt092c4dd2016-08-29 18:27:12 +00001757 else {
1758 do {
1759 assert(DI2 != MBB2.begin());
1760 DI2--;
1761 } while (DI2->isBranch() || DI2->isDebugValue());
1762 DI2++;
1763 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001764 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001765 // NumDups2 only counted non-dbg_value instructions, so this won't
1766 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001767 assert(DI2 != MBB2.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001768 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001769 // skip dbg_value instructions
1770 if (!DI2->isDebugValue())
1771 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001772 }
Evan Cheng4266a792011-12-19 22:01:30 +00001773
1774 // Remember which registers would later be defined by the false block.
1775 // This allows us not to predicate instructions in the true block that would
1776 // later be re-defined. That is, rather than
1777 // subeq r0, r1, #1
1778 // addne r0, r1, #1
1779 // generate:
1780 // sub r0, r1, #1
1781 // addne r0, r1, #1
1782 SmallSet<unsigned, 4> RedefsByFalse;
1783 SmallSet<unsigned, 4> ExtUses;
Matthias Braun08f47042016-08-17 02:52:01 +00001784 if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1785 for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001786 if (FI.isDebugValue())
Evan Cheng4266a792011-12-19 22:01:30 +00001787 continue;
1788 SmallVector<unsigned, 4> Defs;
Matthias Braunb1e05582016-08-17 02:51:59 +00001789 for (const MachineOperand &MO : FI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001790 if (!MO.isReg())
1791 continue;
1792 unsigned Reg = MO.getReg();
1793 if (!Reg)
1794 continue;
1795 if (MO.isDef()) {
1796 Defs.push_back(Reg);
1797 } else if (!RedefsByFalse.count(Reg)) {
1798 // These are defined before ctrl flow reach the 'false' instructions.
1799 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001800 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1801 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001802 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001803 }
1804 }
1805
Matthias Braunb1e05582016-08-17 02:51:59 +00001806 for (unsigned Reg : Defs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001807 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001808 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1809 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001810 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001811 }
1812 }
1813 }
1814 }
1815
1816 // Predicate the 'true' block.
Matthias Braun08f47042016-08-17 02:52:01 +00001817 PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001818
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001819 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1820 // a non-predicated in BBI2, then we don't want to predicate the one from
1821 // BBI2. The reason is that if we merged these blocks, we would end up with
1822 // two predicated terminators in the same block.
Matthias Braun08f47042016-08-17 02:52:01 +00001823 if (!MBB2.empty() && (DI2 == MBB2.end())) {
1824 MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1825 MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1826 if (BBI1T != MBB1.end() && TII->isPredicated(*BBI1T) &&
1827 BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001828 --DI2;
1829 }
1830
Evan Cheng4266a792011-12-19 22:01:30 +00001831 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001832 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001833
Evan Cheng0598b2d2007-06-18 22:44:57 +00001834 // Merge the true block into the entry of the diamond.
Kyle Butta8c73712016-08-24 21:34:27 +00001835 MergeBlocks(BBI, *BBI1, MergeAddEdges);
1836 MergeBlocks(BBI, *BBI2, MergeAddEdges);
1837 return true;
1838}
1839
1840/// If convert an almost-diamond sub-CFG where the true
1841/// and false blocks share a common tail.
1842bool IfConverter::IfConvertForkedDiamond(
1843 BBInfo &BBI, IfcvtKind Kind,
1844 unsigned NumDups1, unsigned NumDups2,
1845 bool TClobbersPred, bool FClobbersPred) {
1846 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1847 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1848
1849 // Save the debug location for later.
1850 DebugLoc dl;
1851 MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1852 if (TIE != TrueBBI.BB->end())
1853 dl = TIE->getDebugLoc();
1854 // Removing branches from both blocks is safe, because we have already
1855 // determined that both blocks have the same branch instructions. The branch
1856 // will be added back at the end, unpredicated.
1857 if (!IfConvertDiamondCommon(
1858 BBI, TrueBBI, FalseBBI,
1859 NumDups1, NumDups2,
1860 TClobbersPred, FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001861 /* RemoveBranch */ true, /* MergeAddEdges */ true))
Kyle Butta8c73712016-08-24 21:34:27 +00001862 return false;
1863
1864 // Add back the branch.
1865 // Debug location saved above when removing the branch from BBI2
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001866 TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
Kyle Butta8c73712016-08-24 21:34:27 +00001867 TrueBBI.BrCond, dl);
1868
Kyle Butta8c73712016-08-24 21:34:27 +00001869 // Update block info.
1870 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1871 InvalidatePreds(*BBI.BB);
1872
1873 // FIXME: Must maintain LiveIns.
1874 return true;
1875}
1876
1877/// If convert a diamond sub-CFG.
1878bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1879 unsigned NumDups1, unsigned NumDups2,
1880 bool TClobbersPred, bool FClobbersPred) {
1881 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1882 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1883 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1884
1885 // True block must fall through or end with an unanalyzable terminator.
1886 if (!TailBB) {
1887 if (blockAlwaysFallThrough(TrueBBI))
1888 TailBB = FalseBBI.TrueBB;
1889 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1890 }
1891
1892 if (!IfConvertDiamondCommon(
1893 BBI, TrueBBI, FalseBBI,
1894 NumDups1, NumDups2,
Kyle Butt86999212016-09-02 18:29:26 +00001895 TClobbersPred, FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001896 /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
Kyle Butta8c73712016-08-24 21:34:27 +00001897 /* MergeAddEdges */ TailBB == nullptr))
1898 return false;
Evan Cheng30565992007-06-06 00:57:55 +00001899
Bob Wilson2371f4f2009-05-13 23:25:24 +00001900 // If the if-converted block falls through or unconditionally branches into
1901 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001902 // fold the tail block in as well. Otherwise, unless it falls through to the
1903 // tail, add a unconditional branch to it.
1904 if (TailBB) {
Mikael Holmen8b106802017-08-11 06:57:08 +00001905 // We need to remove the edges to the true and false blocks manually since
1906 // we didn't let IfConvertDiamondCommon update the CFG.
1907 BBI.BB->removeSuccessor(TrueBBI.BB);
1908 BBI.BB->removeSuccessor(FalseBBI.BB, true);
1909
Pete Cooper77c703f2011-11-04 23:49:14 +00001910 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001911 bool CanMergeTail = !TailBBI.HasFallThrough &&
1912 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001913 // The if-converted block can still have a predicated terminator
1914 // (e.g. a predicated return). If that is the case, we cannot merge
1915 // it with the tail block.
1916 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001917 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001918 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001919 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1920 // check if there are any other predecessors besides those.
1921 unsigned NumPreds = TailBB->pred_size();
1922 if (NumPreds > 1)
1923 CanMergeTail = false;
1924 else if (NumPreds == 1 && CanMergeTail) {
1925 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
Kyle Butta8c73712016-08-24 21:34:27 +00001926 if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
Bob Wilson1e5da552010-06-29 00:55:23 +00001927 CanMergeTail = false;
1928 }
1929 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001930 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001931 TailBBI.IsDone = true;
1932 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001933 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Matthias Braun08f47042016-08-17 02:52:01 +00001934 InsertUncondBranch(*BBI.BB, *TailBB, TII);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001935 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001936 }
Evan Chenge26c0912007-05-21 22:22:58 +00001937 }
1938
Evan Cheng79484222007-06-05 23:46:14 +00001939 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001940 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001941 InvalidatePreds(*BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001942
1943 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001944 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001945}
1946
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001947static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001948 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001949 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001950 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001951 return false;
1952
Matthias Braunb1e05582016-08-17 02:51:59 +00001953 for (const MachineOperand &MO : MI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001954 if (!MO.isReg())
1955 continue;
1956 unsigned Reg = MO.getReg();
1957 if (!Reg)
1958 continue;
1959 if (MO.isDef() && !LaterRedefs.count(Reg))
1960 return false;
1961 }
1962
1963 return true;
1964}
1965
Matthias Braun2c931792016-08-17 02:51:57 +00001966/// Predicate instructions from the start of the block to the specified end with
1967/// the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001968void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001969 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001970 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001971 SmallSet<unsigned, 4> *LaterRedefs) {
1972 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001973 bool MaySpec = LaterRedefs != nullptr;
Matthias Braunb1e05582016-08-17 02:51:59 +00001974 for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001975 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001976 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001977 // It may be possible not to predicate an instruction if it's the 'true'
1978 // side of a diamond and the 'false' side may re-define the instruction's
1979 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001980 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001981 AnyUnpred = true;
1982 continue;
1983 }
1984 // If any instruction is predicated, then every instruction after it must
1985 // be predicated.
1986 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001987 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001988#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001989 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001990#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001991 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001992 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001993
Bob Wilson45814342010-06-19 05:33:57 +00001994 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001995 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001996 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001997 }
Evan Chengd0e66912007-05-23 07:23:16 +00001998
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001999 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00002000
Evan Cheng92fb5452007-06-15 07:36:12 +00002001 BBI.IsAnalyzed = false;
2002 BBI.NonPredSize = 0;
2003
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002004 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00002005 if (AnyUnpred)
2006 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00002007}
2008
Matthias Braun2c931792016-08-17 02:51:57 +00002009/// Copy and predicate instructions from source BB to the destination block.
2010/// Skip end of block branches if IgnoreBr is true.
Evan Cheng92fb5452007-06-15 07:36:12 +00002011void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00002012 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00002013 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00002014 MachineFunction &MF = *ToBBI.BB->getParent();
2015
Matthias Braun08f47042016-08-17 02:52:01 +00002016 MachineBasicBlock &FromMBB = *FromBBI.BB;
2017 for (MachineInstr &I : FromMBB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00002018 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002019 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00002020 break;
2021
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002022 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00002023 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00002024 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002025 unsigned ExtraPredCost = TII->getPredicationCost(I);
2026 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00002027 if (NumCycles > 1)
2028 ToBBI.ExtraCost += NumCycles-1;
2029 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00002030
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00002031 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002032 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00002033#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002034 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00002035#endif
Craig Topperc0196b12014-04-14 00:51:57 +00002036 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00002037 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002038 }
2039
Bob Wilson45814342010-06-19 05:33:57 +00002040 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002041 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002042 UpdatePredRedefs(*MI, Redefs);
Evan Cheng92fb5452007-06-15 07:36:12 +00002043 }
2044
Bob Wilson1e5da552010-06-29 00:55:23 +00002045 if (!IgnoreBr) {
Matthias Braun08f47042016-08-17 02:52:01 +00002046 std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2047 FromMBB.succ_end());
2048 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00002049 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00002050
Matthias Braunb1e05582016-08-17 02:51:59 +00002051 for (MachineBasicBlock *Succ : Succs) {
Bob Wilson1e5da552010-06-29 00:55:23 +00002052 // Fallthrough edge can't be transferred.
2053 if (Succ == FallThrough)
2054 continue;
2055 ToBBI.BB->addSuccessor(Succ);
2056 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00002057 }
2058
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002059 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2060 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002061
2062 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2063 ToBBI.IsAnalyzed = false;
2064
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002065 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00002066}
2067
Matthias Braun2c931792016-08-17 02:51:57 +00002068/// Move all instructions from FromBB to the end of ToBB. This will leave
2069/// FromBB as an empty block, so remove all of its successor edges except for
2070/// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
Mikael Holmen8b106802017-08-11 06:57:08 +00002071/// being moved, add those successor edges to ToBBI and remove the old edge
2072/// from ToBBI to FromBBI.
Bob Wilson1e5da552010-06-29 00:55:23 +00002073void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Matthias Braun08f47042016-08-17 02:52:01 +00002074 MachineBasicBlock &FromMBB = *FromBBI.BB;
2075 assert(!FromMBB.hasAddressTaken() &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00002076 "Removing a BB whose address is taken!");
2077
Matthias Braun08f47042016-08-17 02:52:01 +00002078 // In case FromMBB contains terminators (e.g. return instruction),
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002079 // first move the non-terminator instructions, then the terminators.
Matthias Braun08f47042016-08-17 02:52:01 +00002080 MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002081 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
Matthias Braun08f47042016-08-17 02:52:01 +00002082 ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002083
2084 // If FromBB has non-predicated terminator we should copy it at the end.
Matthias Braun08f47042016-08-17 02:52:01 +00002085 if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002086 ToTI = ToBBI.BB->end();
Matthias Braun08f47042016-08-17 02:52:01 +00002087 ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
Evan Chengd0e66912007-05-23 07:23:16 +00002088
Cong Houb9e8d482015-12-17 01:29:08 +00002089 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2090 // unknown probabilities into known ones.
2091 // FIXME: This usage is too tricky and in the future we would like to
2092 // eliminate all unknown probabilities in MBB.
Krzysztof Parzyszek5b8fae52017-03-06 19:12:42 +00002093 if (ToBBI.IsBrAnalyzable)
2094 ToBBI.BB->normalizeSuccProbs();
Cong Houb9e8d482015-12-17 01:29:08 +00002095
Matthias Braun08f47042016-08-17 02:52:01 +00002096 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
2097 FromMBB.succ_end());
2098 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00002099 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Matthias Braun08f47042016-08-17 02:52:01 +00002100 // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2101 // AddEdges is true and FromMBB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00002102 auto To2FromProb = BranchProbability::getZero();
Matthias Braun08f47042016-08-17 02:52:01 +00002103 if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
Mikael Holmen8b106802017-08-11 06:57:08 +00002104 // Remove the old edge but remember the edge probability so we can calculate
2105 // the correct weights on the new edges being added further down.
Matthias Braun08f47042016-08-17 02:52:01 +00002106 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
Mikael Holmen8b106802017-08-11 06:57:08 +00002107 ToBBI.BB->removeSuccessor(&FromMBB);
Cong Houd97c1002015-12-01 05:29:22 +00002108 }
2109
Matthias Braunb1e05582016-08-17 02:51:59 +00002110 for (MachineBasicBlock *Succ : FromSuccs) {
Evan Cheng288f1542007-06-08 22:01:07 +00002111 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00002112 if (Succ == FallThrough)
2113 continue;
Cong Houd40105d2015-09-18 20:22:41 +00002114
Cong Houd97c1002015-12-01 05:29:22 +00002115 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00002116 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002117 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
Matthias Braun08f47042016-08-17 02:52:01 +00002118 // which is a portion of the edge probability from FromMBB to Succ. The
2119 // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
Cong Houd97c1002015-12-01 05:29:22 +00002120 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
Matthias Braun08f47042016-08-17 02:52:01 +00002121 NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002122
Matthias Braun08f47042016-08-17 02:52:01 +00002123 // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2124 // only happens when if-converting a diamond CFG and FromMBB is the
2125 // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
2126 // could just use the probabilities on FromMBB's out-edges when adding
Cong Houd97c1002015-12-01 05:29:22 +00002127 // new successors.
2128 if (!To2FromProb.isZero())
2129 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00002130 }
2131
Matthias Braun08f47042016-08-17 02:52:01 +00002132 FromMBB.removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002133
2134 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002135 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00002136 // probability of this edge by adding NewProb to it. An example is shown
Matthias Braun08f47042016-08-17 02:52:01 +00002137 // below, in which A is ToBBI.BB and B is FromMBB. In this case we
Cong Houd97c1002015-12-01 05:29:22 +00002138 // don't have to set C as A's successor as it already is. We only need to
2139 // update the edge probability on A->C. Note that B will not be
2140 // immediately removed from A's successors. It is possible that B->D is
2141 // not removed either if D is a fallthrough of B. Later the edge A->D
2142 // (generated here) and B->D will be combined into one edge. To maintain
2143 // correct edge probability of this combined edge, we need to set the edge
2144 // probability of A->B to zero, which is already done above. The edge
2145 // probability on A->D is calculated by scaling the original probability
2146 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00002147 //
2148 // Before ifcvt: After ifcvt (assume B->D is kept):
2149 //
2150 // A A
2151 // /| /|\
2152 // / B / B|
2153 // | /| | ||
2154 // |/ | | |/
2155 // C D C D
2156 //
2157 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00002158 ToBBI.BB->setSuccProbability(
David Majnemer42531262016-08-12 03:55:06 +00002159 find(ToBBI.BB->successors(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00002160 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002161 else
Cong Houd97c1002015-12-01 05:29:22 +00002162 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002163 }
Evan Chengbe9859e2007-06-07 02:12:15 +00002164 }
2165
Mikael Holmen8b106802017-08-11 06:57:08 +00002166 // Move the now empty FromMBB out of the way to the end of the function so
2167 // it doesn't interfere with fallthrough checks done by canFallThroughTo().
2168 MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
2169 if (Last != &FromMBB)
2170 FromMBB.moveAfter(Last);
Evan Cheng288f1542007-06-08 22:01:07 +00002171
Cong Houc1069892015-12-13 09:26:17 +00002172 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2173 // we've done above.
Krzysztof Parzyszek5b8fae52017-03-06 19:12:42 +00002174 if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
2175 ToBBI.BB->normalizeSuccProbs();
Cong Houc1069892015-12-13 09:26:17 +00002176
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002177 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002178 FromBBI.Predicate.clear();
2179
Evan Chengd0e66912007-05-23 07:23:16 +00002180 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002181 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00002182 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00002183 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002184 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00002185 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00002186
Evan Cheng4dd31a72007-06-11 22:26:22 +00002187 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00002188 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00002189 ToBBI.IsAnalyzed = false;
2190 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00002191}
Akira Hatanaka4a616192015-06-08 18:50:43 +00002192
2193FunctionPass *
Matthias Braun8b38ffa2016-10-24 23:23:02 +00002194llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00002195 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00002196}