blob: fc270a2c9972be343e3a90ee0605aa509193cf76 [file] [log] [blame]
Evan Chengf5e53a52007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
Justin Lebaracc47102016-04-01 01:09:03 +000010// This file implements the machine instruction level if-conversion pass, which
11// tries to convert conditional branches into predicated instructions.
Evan Chengf5e53a52007-05-16 02:00:57 +000012//
13//===----------------------------------------------------------------------===//
14
Evan Chengf5e53a52007-05-16 02:00:57 +000015#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "BranchFolding.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000020#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000021#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000022#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000027#include "llvm/CodeGen/TargetSchedule.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000028#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000029#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000030#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000035#include "llvm/Target/TargetSubtargetInfo.h"
Cong Houd97c1002015-12-01 05:29:22 +000036#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000037#include <utility>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000038
Evan Chengf5e53a52007-05-16 02:00:57 +000039using namespace llvm;
40
Chandler Carruth1b9dde02014-04-22 02:02:50 +000041#define DEBUG_TYPE "ifcvt"
42
Chris Lattner769c86b2008-01-07 05:40:58 +000043// Hidden options for help debugging.
44static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
45static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
46static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000047static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000048 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000049static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000050 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000051static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000052 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000053static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000054 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000055static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000056 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000057static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000058 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000059static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000060 cl::init(false), cl::Hidden);
Kyle Butt71cb44d2016-08-06 01:52:37 +000061static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
62 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000063static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
64 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000065
Evan Cheng2117d1f2007-06-09 01:03:43 +000066STATISTIC(NumSimple, "Number of simple if-conversions performed");
67STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
68STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000069STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000070STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
71STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
72STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
Kyle Butt71cb44d2016-08-06 01:52:37 +000073STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000074STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000075STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000076STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000077
78namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000079 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000080 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000081 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000082 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000083 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
84 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000085 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000086 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000087 ICTriangle, // BB is entry of a triangle sub-CFG.
Kyle Butt71cb44d2016-08-06 01:52:37 +000088 ICDiamond, // BB is entry of a diamond sub-CFG.
89 ICForkedDiamond // BB is entry of an almost diamond sub-CFG, with a
90 // common tail that can be shared.
Evan Chengf5e53a52007-05-16 02:00:57 +000091 };
92
93 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
94 /// if-conversion feasibility analysis. This includes results from
Jacques Pienaar71c30a12016-07-15 14:41:04 +000095 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000096 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000097 /// diamond shape), its size, whether it's predicable, and whether any
98 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000099 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +0000100 /// IsDone - True if BB is not to be considered for ifcvt.
101 /// IsBeingAnalyzed - True if BB is currently being analyzed.
102 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
103 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000104 /// IsBrAnalyzable - True if analyzeBranch() returns false.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000105 /// HasFallThrough - True if BB may fallthrough to the following BB.
106 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000107 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000108 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000109 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000110 /// ExtraCost - Extra cost for multi-cycle instructions.
111 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000112 /// BB - Corresponding MachineBasicBlock.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000113 /// TrueBB / FalseBB- See analyzeBranch().
Evan Chengd0e66912007-05-23 07:23:16 +0000114 /// BrCond - Conditions for end of block conditional branches.
115 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000116 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000117 bool IsDone : 1;
118 bool IsBeingAnalyzed : 1;
119 bool IsAnalyzed : 1;
120 bool IsEnqueued : 1;
121 bool IsBrAnalyzable : 1;
Kyle Butt71cb44d2016-08-06 01:52:37 +0000122 bool IsBrReversible : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000123 bool HasFallThrough : 1;
124 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000125 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000126 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000127 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000128 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000129 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000130 MachineBasicBlock *BB;
131 MachineBasicBlock *TrueBB;
132 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000133 SmallVector<MachineOperand, 4> BrCond;
134 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000135 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000136 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
Kyle Butt71cb44d2016-08-06 01:52:37 +0000137 IsBrReversible(false), HasFallThrough(false),
138 IsUnpredicable(false), CannotBeCopied(false),
139 ClobbersPred(false), NonPredSize(0), ExtraCost(0),
140 ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
Craig Topperc0196b12014-04-14 00:51:57 +0000141 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000142 };
143
Bob Wilson59475732010-06-15 18:19:27 +0000144 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000145 /// BBI - Corresponding BBInfo.
146 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000147 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000148 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000149 /// NumDups - Number of instructions that would be duplicated due
150 /// to this if-conversion. (For diamonds, the number of
151 /// identical instructions at the beginnings of both
152 /// paths).
153 /// NumDups2 - For diamonds, the number of identical instructions
154 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000155 struct IfcvtToken {
156 BBInfo &BBI;
157 IfcvtKind Kind;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000158 unsigned NumDups;
159 unsigned NumDups2;
Kyle Butt71cb44d2016-08-06 01:52:37 +0000160 bool NeedSubsumption : 1;
161 bool TClobbersPred : 1;
162 bool FClobbersPred : 1;
163 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
164 bool tc = false, bool fc = false)
165 : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
166 TClobbersPred(tc), FClobbersPred(fc) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000167 };
168
169 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
170 /// basic block number.
171 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000172 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000173
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000174 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000175 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000176 const TargetRegisterInfo *TRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000177 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000178 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000179
Juergen Ributzka310034e2013-12-14 06:52:56 +0000180 LivePhysRegs Redefs;
181 LivePhysRegs DontKill;
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;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000186 std::function<bool(const Function &)> PredicateFtor;
187
Evan Chengf5e53a52007-05-16 02:00:57 +0000188 public:
189 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000190 IfConverter(std::function<bool(const Function &)> 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(
205 MachineFunctionProperties::Property::AllVRegsAllocated);
206 }
207
Evan Chengf5e53a52007-05-16 02:00:57 +0000208 private:
Kyle Butt59f2a2a2016-07-27 20:19:31 +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;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000215 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
Kyle Butt71cb44d2016-08-06 01:52:37 +0000216 unsigned &Dups1, unsigned &Dups2,
217 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
218 bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
219 unsigned &Dups1, unsigned &Dups2,
220 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000221 void AnalyzeBranches(BBInfo &BBI);
222 void ScanInstructions(BBInfo &BBI,
223 MachineBasicBlock::iterator &Begin,
224 MachineBasicBlock::iterator &End) const;
Kyle Butt71cb44d2016-08-06 01:52:37 +0000225 bool RescanInstructions(
226 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
227 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
228 BBInfo &TrueBBI, BBInfo &FalseBBI) const;
Justin Lebar3a7bc572016-02-22 17:51:28 +0000229 void AnalyzeBlock(MachineBasicBlock *MBB,
230 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000231 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Kyle Butt71cb44d2016-08-06 01:52:37 +0000232 bool isTriangle = false, bool RevBranch = false,
233 bool hasCommonTail = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000234 void AnalyzeBlocks(MachineFunction &MF,
235 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000236 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000237 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000238 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
239 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Kyle Butt71cb44d2016-08-06 01:52:37 +0000240 bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
241 unsigned NumDups1, unsigned NumDups2,
242 bool TClobbersPred, bool FClobbersPred,
243 bool RemoveTrueBranch, bool RemoveFalseBranch,
244 bool MergeAddEdges);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000245 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
246 unsigned NumDups1, unsigned NumDups2);
Kyle Butt71cb44d2016-08-06 01:52:37 +0000247 bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
248 unsigned NumDups1, unsigned NumDups2,
249 bool TClobbers, bool FClobbers);
Evan Chengd0e66912007-05-23 07:23:16 +0000250 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000251 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000252 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000253 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000254 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000255 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000256 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000257 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000258
Evan Chengdebf9c52010-11-03 00:45:17 +0000259 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
260 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000261 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000262 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000263 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000264 }
265
Evan Chengdebf9c52010-11-03 00:45:17 +0000266 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
267 unsigned TCycle, unsigned TExtra,
268 MachineBasicBlock &FBB,
269 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000270 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000271 return TCycle > 0 && FCycle > 0 &&
272 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000273 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000274 }
275
Evan Chengbe9859e2007-06-07 02:12:15 +0000276 // blockAlwaysFallThrough - Block ends without a terminator.
277 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000278 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000279 }
280
Evan Cheng3a51c852007-06-16 09:34:52 +0000281 // IfcvtTokenCmp - Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000282 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
283 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000284 int Incr1 = (C1->Kind == ICDiamond)
285 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
286 int Incr2 = (C2->Kind == ICDiamond)
287 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
288 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000289 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000290 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000291 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000292 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000293 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000294 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000295 // Favors diamond over triangle, etc.
296 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
297 return true;
298 else if (C1->Kind == C2->Kind)
299 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
300 }
301 }
302 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000303 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000304 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000305
Evan Chengf5e53a52007-05-16 02:00:57 +0000306 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000307}
Evan Chengf5e53a52007-05-16 02:00:57 +0000308
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000309char &llvm::IfConverterID = IfConverter::ID;
310
Owen Anderson8ac477f2010-10-12 19:48:12 +0000311INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000312INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000313INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000314
Evan Chengf5e53a52007-05-16 02:00:57 +0000315bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000316 if (skipFunction(*MF.getFunction()) ||
317 (PredicateFtor && !PredicateFtor(*MF.getFunction())))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000318 return false;
319
Eric Christopher3d4276f2015-01-27 07:31:29 +0000320 const TargetSubtargetInfo &ST = MF.getSubtarget();
321 TLI = ST.getTargetLowering();
322 TII = ST.getInstrInfo();
323 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000324 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000325 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000326 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000327 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000328
Evan Chengf5e53a52007-05-16 02:00:57 +0000329 if (!TII) return false;
330
Evan Chengc5adcca2012-06-08 21:53:50 +0000331 PreRegAlloc = MRI->isSSA();
332
333 bool BFChange = false;
334 if (!PreRegAlloc) {
335 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000336 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000337 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000338 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000339 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000340
David Greene72e47cd2010-01-04 22:02:01 +0000341 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000342 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000343
344 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000345 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000346 return false;
347 }
David Greene72e47cd2010-01-04 22:02:01 +0000348 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000349
Evan Chengf5e53a52007-05-16 02:00:57 +0000350 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000351 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000352
Justin Lebar3a7bc572016-02-22 17:51:28 +0000353 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000354 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000355 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
356 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
357 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000358 // Do an initial analysis for each basic block and find all the potential
359 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000360 bool Change = false;
361 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000362 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000363 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000364 Tokens.pop_back();
365 BBInfo &BBI = Token->BBI;
366 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000367 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000368 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000369
Evan Cheng4dd31a72007-06-11 22:26:22 +0000370 // If the block has been evicted out of the queue or it has already been
371 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000372 if (BBI.IsDone)
373 BBI.IsEnqueued = false;
374 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000375 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000376
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000377 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000378
Evan Cheng312b7232007-06-04 06:47:22 +0000379 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000380 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000381 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000382 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000383 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000384 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000385 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000386 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
387 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000388 << "): BB#" << BBI.BB->getNumber() << " ("
389 << ((Kind == ICSimpleFalse)
390 ? BBI.FalseBB->getNumber()
391 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000392 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000393 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000394 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000395 if (isFalse) ++NumSimpleFalse;
396 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000397 }
Evan Cheng312b7232007-06-04 06:47:22 +0000398 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000399 }
Evan Chengd0e66912007-05-23 07:23:16 +0000400 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000401 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000402 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000403 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000404 bool isFalse = Kind == ICTriangleFalse;
405 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000406 if (DisableTriangle && !isFalse && !isRev) break;
407 if (DisableTriangleR && !isFalse && isRev) break;
408 if (DisableTriangleF && isFalse && !isRev) break;
409 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000410 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000411 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000412 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000413 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000414 DEBUG(dbgs() << " rev");
415 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000416 << BBI.TrueBB->getNumber() << ",F:"
417 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000418 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000419 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000420 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000421 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000422 if (isRev) ++NumTriangleFRev;
423 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000424 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000425 if (isRev) ++NumTriangleRev;
426 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000427 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000428 }
Evan Chengd0e66912007-05-23 07:23:16 +0000429 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000430 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000431 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000432 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000433 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000434 << BBI.TrueBB->getNumber() << ",F:"
435 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000436 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000437 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000438 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000439 break;
440 }
Kyle Butt71cb44d2016-08-06 01:52:37 +0000441 case ICForkedDiamond: {
442 if (DisableForkedDiamond) break;
443 DEBUG(dbgs() << "Ifcvt (Forked Diamond): BB#"
444 << BBI.BB->getNumber() << " (T:"
445 << BBI.TrueBB->getNumber() << ",F:"
446 << BBI.FalseBB->getNumber() << ") ");
447 RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
448 Token->TClobbersPred,
449 Token->FClobbersPred);
450 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
451 if (RetVal) ++NumForkedDiamonds;
452 break;
453 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000454 }
455
Evan Cheng312b7232007-06-04 06:47:22 +0000456 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000457
Evan Cheng92fb5452007-06-15 07:36:12 +0000458 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
459 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
460 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000461 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000462 }
Evan Chengd0e66912007-05-23 07:23:16 +0000463
Evan Chengd0e66912007-05-23 07:23:16 +0000464 if (!Change)
465 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000466 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000467 }
Evan Cheng478b8052007-05-18 01:55:58 +0000468
Evan Cheng3a51c852007-06-16 09:34:52 +0000469 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000470 BBAnalysis.clear();
471
Evan Chengcf9e8a92010-06-18 22:17:13 +0000472 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000473 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000474 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000475 getAnalysisIfAvailable<MachineModuleInfo>());
476 }
477
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000478 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000479 return MadeChange;
480}
481
Evan Cheng3a51c852007-06-16 09:34:52 +0000482/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
483/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000484static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000485 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000486 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
487 E = BB->succ_end(); SI != E; ++SI) {
488 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000489 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000490 return SuccBB;
491 }
Craig Topperc0196b12014-04-14 00:51:57 +0000492 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000493}
494
Evan Cheng3a51c852007-06-16 09:34:52 +0000495/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000496/// branch. Swap block's 'true' and 'false' successors.
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000497bool IfConverter::ReverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000498 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000499 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
500 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000501 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000502 std::swap(BBI.TrueBB, BBI.FalseBB);
503 return true;
504 }
505 return false;
506}
507
Evan Cheng2117d1f2007-06-09 01:03:43 +0000508/// getNextBlock - Returns the next block in the function blocks ordering. If
509/// it is the end, returns NULL.
510static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000511 MachineFunction::iterator I = BB->getIterator();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000512 MachineFunction::iterator E = BB->getParent()->end();
513 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000514 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000515 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000516}
517
Evan Cheng7783f822007-06-08 09:36:04 +0000518/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000519/// predecessor) forms a valid simple shape for ifcvt. It also returns the
520/// number of instructions that the ifcvt would need to duplicate if performed
521/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000522bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000523 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000524 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000525 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000526 return false;
527
Evan Chenga955c022007-06-19 21:45:13 +0000528 if (TrueBBI.IsBrAnalyzable)
529 return false;
530
Evan Cheng23402fc2007-06-15 21:18:05 +0000531 if (TrueBBI.BB->pred_size() > 1) {
532 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000533 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000534 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000535 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000536 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000537 }
538
Evan Chenga955c022007-06-19 21:45:13 +0000539 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000540}
541
Evan Cheng7783f822007-06-08 09:36:04 +0000542/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000543/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000544/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000545/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000546/// returns the number of instructions that the ifcvt would need to duplicate
547/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000548bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000549 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000550 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000551 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000552 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000553 return false;
554
Evan Cheng23402fc2007-06-15 21:18:05 +0000555 if (TrueBBI.BB->pred_size() > 1) {
556 if (TrueBBI.CannotBeCopied)
557 return false;
558
Evan Cheng92fb5452007-06-15 07:36:12 +0000559 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000560 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000561 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000562 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000563 --Size;
564 else {
565 MachineBasicBlock *FExit = FalseBranch
566 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
567 if (FExit)
568 // Require a conditional branch
569 ++Size;
570 }
571 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000572 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000573 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000574 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000575 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000576
Evan Cheng7783f822007-06-08 09:36:04 +0000577 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
578 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000579 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000580 if (++I == TrueBBI.BB->getParent()->end())
581 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000582 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000583 }
Evan Cheng7783f822007-06-08 09:36:04 +0000584 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000585}
586
Kyle Buttfe916822016-08-06 01:52:31 +0000587/// Increment It until it points to a non-debug instruction or to End.
588/// @param It Iterator to increment
589/// @param End Iterator that points to end. Will be compared to It
590/// @returns true if It == End, false otherwise.
591static inline bool skipDebugInstructionsForward(
592 MachineBasicBlock::iterator &It,
593 MachineBasicBlock::iterator &End) {
594 while (It != End && It->isDebugValue())
595 It++;
596 return It == End;
597}
598
599/// Decrement It until it points to a non-debug instruction or to Begin.
600/// @param It Iterator to decrement.
601/// @param End Iterator that points to beginning. Will be compared to It
602/// @returns true if It == Begin, false otherwise.
603static inline bool skipDebugInstructionsBackward(
604 MachineBasicBlock::iterator &It,
605 MachineBasicBlock::iterator &Begin) {
606 while (It != Begin && It->isDebugValue())
607 It--;
608 return It == Begin;
609}
610
Kyle Butt4f0e2872016-08-06 01:52:33 +0000611/// Count duplicated instructions and move the iterators to show where they
612/// are.
613/// @param TIB True Iterator Begin
614/// @param FIB False Iterator Begin
615/// These two iterators initially point to the first instruction of the two
616/// blocks, and finally point to the first non-shared instruction.
617/// @param TIE True Iterator End
618/// @param FIE False Iterator End
619/// These two iterators initially point to End() for the two blocks() and
620/// finally point to the first shared instruction in the tail.
621/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
622/// two blocks.
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000623static void countDuplicatedInstructions(
624 MachineBasicBlock::iterator &TIB,
625 MachineBasicBlock::iterator &FIB,
626 MachineBasicBlock::iterator &TIE,
627 MachineBasicBlock::iterator &FIE,
628 unsigned &Dups1, unsigned &Dups2,
629 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
630 bool SkipConditionalBranches) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000631
Bob Wilsone1961fe2010-10-26 00:02:24 +0000632 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000633 // Skip dbg_value instructions. These do not count.
Kyle Buttfe916822016-08-06 01:52:31 +0000634 if(skipDebugInstructionsForward(TIB, TIE))
635 break;
636 if(skipDebugInstructionsForward(FIB, FIE))
637 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000638 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000639 break;
640 ++Dups1;
641 ++TIB;
642 ++FIB;
643 }
644
645 // Now, in preparation for counting duplicate instructions at the ends of the
646 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000647 // If both blocks are returning don't skip the branches, since they will
648 // likely be both identical return instructions. In such cases the return
649 // can be left unpredicated.
650 // Check for already containing all of the block.
651 if (TIB == TIE || FIB == FIE)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000652 return;
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000653 --TIE;
654 --FIE;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000655 if (!TBB.succ_empty() || !FBB.succ_empty()) {
656 if (SkipConditionalBranches) {
657 while (TIE != TIB && TIE->isBranch())
658 --TIE;
659 while (FIE != FIB && FIE->isBranch())
660 --FIE;
661 } else {
662 while (TIE != TIB && TIE->isUnconditionalBranch())
663 --TIE;
664 while (FIE != FIB && FIE->isUnconditionalBranch())
665 --FIE;
666 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000667 }
668
669 // If Dups1 includes all of a block, then don't count duplicate
670 // instructions at the end of the blocks.
Kyle Butt71cb44d2016-08-06 01:52:37 +0000671 if (TIB == TIE || FIB == FIE) {
672 // Same reason as below. We need end to point just after the last non-shared
673 // instruction.
674 ++TIE; ++FIE;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000675 return;
Kyle Butt71cb44d2016-08-06 01:52:37 +0000676 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000677
678 // Count duplicate instructions at the ends of the blocks.
679 while (TIE != TIB && FIE != FIB) {
680 // Skip dbg_value instructions. These do not count.
Kyle Buttfe916822016-08-06 01:52:31 +0000681 if (skipDebugInstructionsBackward(TIE, TIB))
682 break;
683 if (skipDebugInstructionsBackward(FIE, FIB))
684 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000685 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000686 break;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000687 // If we are trying to make sure the conditional branches are the same, we
688 // still don't want to count them.
689 if (SkipConditionalBranches || !TIE->isBranch())
690 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000691 --TIE;
692 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000693 }
Kyle Butt71cb44d2016-08-06 01:52:37 +0000694 // TIE and FIE both now point at the last non-shared instruction, move them
695 // forward.
696 ++TIE; ++FIE;
697}
698
699/// RescanInstructions - Run ScanInstructions on a pair of blocks.
700/// @param TIB - True Iterator Begin, points to first non-shared instruction
701/// @param FIB - False Iterator Begin, points to first non-shared instruction
702/// @param TIE - True Iterator End, points past last non-shared instruction
703/// @param FIE - False Iterator End, points past last non-shared instruction
704/// @param TrueBBI - BBInfo to update for the true block.
705/// @param FalseBBI - BBInfo to update for the false block.
706/// @returns - false if either block cannot be predicated or if both blocks end
707/// with a predicate-clobbering instruction.
708bool IfConverter::RescanInstructions(
709 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
710 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
711 BBInfo &TrueBBI, BBInfo &FalseBBI) const {
712 ScanInstructions(TrueBBI, TIB, TIE);
713 if (TrueBBI.IsUnpredicable)
714 return false;
715 ScanInstructions(FalseBBI, FIB, FIE);
716 if (FalseBBI.IsUnpredicable)
717 return false;
718 if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
719 return false;
720 return true;
721}
722
723/// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
724/// with their common predecessor) form a diamond if a common tail block is
725/// extracted.
726/// While not strictly a diamond, this pattern would form a diamond if
727/// tail-merging had merged the shared tails.
728/// EBB
729/// _/ \_
730/// | |
731/// TBB FBB
732/// / \ / \
733/// FalseBB TrueBB FalseBB
734/// Currently only handles analyzable branches.
735/// Specifically excludes actual diamonds to avoid overlap.
736bool IfConverter::ValidForkedDiamond(
737 BBInfo &TrueBBI, BBInfo &FalseBBI,
738 unsigned &Dups1, unsigned &Dups2,
739 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
740 Dups1 = Dups2 = 0;
741 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
742 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
743 return false;
744
745 if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
746 return false;
747 // Don't IfConvert blocks that can't be folded into their predecessor.
748 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
749 return false;
750
751 // This function is specifically looking for conditional tails, as
752 // unconditional tails are already handled by the standard diamond case.
753 if (TrueBBI.BrCond.size() == 0 ||
754 FalseBBI.BrCond.size() == 0)
755 return false;
756
757 MachineBasicBlock *TT = TrueBBI.TrueBB;
758 MachineBasicBlock *TF = TrueBBI.FalseBB;
759 MachineBasicBlock *FT = FalseBBI.TrueBB;
760 MachineBasicBlock *FF = FalseBBI.FalseBB;
761
762 if (!TT)
763 TT = getNextBlock(TrueBBI.BB);
764 if (!TF)
765 TF = getNextBlock(TrueBBI.BB);
766 if (!FT)
767 FT = getNextBlock(FalseBBI.BB);
768 if (!FF)
769 FF = getNextBlock(FalseBBI.BB);
770
771 if (!TT || !TF)
772 return false;
773
774 // Check successors. If they don't match, bail.
775 if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
776 return false;
777
778 if (TF == FT && TT == FF) {
779 // If the branches are opposing, but we can't reverse, don't do it.
780 if (!FalseBBI.IsBrReversible)
781 return false;
782 ReverseBranchCondition(FalseBBI);
783 }
784
785 // Count duplicate instructions at the beginning of the true and false blocks.
786 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
787 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
788 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
789 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
790 countDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
791 *TrueBBI.BB, *FalseBBI.BB,
792 /* SkipConditionalBranches */ false);
793
794 TrueBBICalc.BB = TrueBBI.BB;
795 FalseBBICalc.BB = FalseBBI.BB;
796 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
797 return false;
798 // The size is used to decide whether to if-convert, and the shared portions
799 // are subtracted off. Because of the subtraction, we just use the size that
800 // was calculated by the original ScanInstructions, as it is correct.
801 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
802 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
803 return true;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000804}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000805
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000806/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
807/// with their common predecessor) forms a valid diamond shape for ifcvt.
Kyle Butt71cb44d2016-08-06 01:52:37 +0000808bool IfConverter::ValidDiamond(
809 BBInfo &TrueBBI, BBInfo &FalseBBI,
810 unsigned &Dups1, unsigned &Dups2,
811 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000812 Dups1 = Dups2 = 0;
813 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
814 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
815 return false;
816
817 MachineBasicBlock *TT = TrueBBI.TrueBB;
818 MachineBasicBlock *FT = FalseBBI.TrueBB;
819
820 if (!TT && blockAlwaysFallThrough(TrueBBI))
821 TT = getNextBlock(TrueBBI.BB);
822 if (!FT && blockAlwaysFallThrough(FalseBBI))
823 FT = getNextBlock(FalseBBI.BB);
824 if (TT != FT)
825 return false;
826 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
827 return false;
828 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
829 return false;
830
831 // FIXME: Allow true block to have an early exit?
Kyle Butt71cb44d2016-08-06 01:52:37 +0000832 if (TrueBBI.FalseBB || FalseBBI.FalseBB)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000833 return false;
834
835 // Count duplicate instructions at the beginning and end of the true and
836 // false blocks.
837 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
838 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
839 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
840 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
841 countDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
842 *TrueBBI.BB, *FalseBBI.BB,
843 /* SkipConditionalBranches */ true);
Kyle Butt71cb44d2016-08-06 01:52:37 +0000844
845 TrueBBICalc.BB = TrueBBI.BB;
846 FalseBBICalc.BB = FalseBBI.BB;
847 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
848 return false;
849 // The size is used to decide whether to if-convert, and the shared portions
850 // are subtracted off. Because of the subtraction, we just use the size that
851 // was calculated by the original ScanInstructions, as it is correct.
852 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
853 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000854 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000855}
856
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000857/// AnalyzeBranches - Look at the branches at the end of a block to determine if
858/// the block is predicable.
859void IfConverter::AnalyzeBranches(BBInfo &BBI) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000860 if (BBI.IsDone)
861 return;
862
Craig Topperc0196b12014-04-14 00:51:57 +0000863 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000864 BBI.BrCond.clear();
865 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000866 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Kyle Butt71cb44d2016-08-06 01:52:37 +0000867 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
868 BBI.IsBrReversible = (RevCond.size() == 0) ||
869 !TII->ReverseBranchCondition(RevCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000870 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000871
872 if (BBI.BrCond.size()) {
873 // No false branch. This BB must end with a conditional branch and a
874 // fallthrough.
875 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000876 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000877 if (!BBI.FalseBB) {
878 // Malformed bcc? True and false blocks are the same?
879 BBI.IsUnpredicable = true;
Evan Chengb9bff582009-06-15 21:24:34 +0000880 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000881 }
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000882}
Evan Cheng4dd31a72007-06-11 22:26:22 +0000883
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000884/// ScanInstructions - Scan all the instructions in the block to determine if
885/// the block is predicable. In most cases, that means all the instructions
886/// in the block are isPredicable(). Also checks if the block contains any
887/// instruction which can clobber a predicate (e.g. condition code register).
888/// If so, the block is not predicable unless it's the last instruction.
889void IfConverter::ScanInstructions(BBInfo &BBI,
890 MachineBasicBlock::iterator &Begin,
891 MachineBasicBlock::iterator &End) const {
892 if (BBI.IsDone || BBI.IsUnpredicable)
893 return;
894
895 bool AlreadyPredicated = !BBI.Predicate.empty();
896
Evan Cheng4dd31a72007-06-11 22:26:22 +0000897 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000898 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000899 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000900 BBI.ClobbersPred = false;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000901 for (; Begin != End; ++Begin) {
902 auto &MI = *Begin;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000903 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000904 continue;
905
Justin Lebar7dba2e02016-04-15 01:38:41 +0000906 // It's unsafe to duplicate convergent instructions in this context, so set
907 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
908 // following CFG, which is subject to our "simple" transformation.
909 //
910 // BB0 // if (c1) goto BB1; else goto BB2;
911 // / \
912 // BB1 |
913 // | BB2 // if (c2) goto TBB; else goto FBB;
914 // | / |
915 // | / |
916 // TBB |
917 // | |
918 // | FBB
919 // |
920 // exit
921 //
922 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
923 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
924 // TBB contains a convergent instruction. This is safe iff doing so does
925 // not add a control-flow dependency to the convergent instruction -- i.e.,
926 // it's safe iff the set of control flows that leads us to the convergent
927 // instruction does not get smaller after the transformation.
928 //
929 // Originally we executed TBB if c1 || c2. After the transformation, there
930 // are two copies of TBB's instructions. We get to the first if c1, and we
931 // get to the second if !c1 && c2.
932 //
933 // There are clearly fewer ways to satisfy the condition "c1" than
934 // "c1 || c2". Since we've shrunk the set of control flows which lead to
935 // our convergent instruction, the transformation is unsafe.
936 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000937 BBI.CannotBeCopied = true;
938
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000939 bool isPredicated = TII->isPredicated(MI);
940 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000941
Joey Goulya5153cb2013-09-09 14:21:49 +0000942 // A conditional branch is not predicable, but it may be eliminated.
943 if (isCondBr)
944 continue;
945
946 if (!isPredicated) {
947 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000948 unsigned ExtraPredCost = TII->getPredicationCost(MI);
949 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000950 if (NumCycles > 1)
951 BBI.ExtraCost += NumCycles-1;
952 BBI.ExtraCost2 += ExtraPredCost;
953 } else if (!AlreadyPredicated) {
954 // FIXME: This instruction is already predicated before the
955 // if-conversion pass. It's probably something like a conditional move.
956 // Mark this block unpredicable for now.
957 BBI.IsUnpredicable = true;
958 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000959 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000960
961 if (BBI.ClobbersPred && !isPredicated) {
962 // Predicate modification instruction should end the block (except for
963 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000964 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000965 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000966 BBI.IsUnpredicable = true;
967 return;
968 }
969
Evan Chengfbc73092007-07-10 17:50:43 +0000970 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
971 // still potentially predicable.
972 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000973 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000974 BBI.ClobbersPred = true;
975
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000976 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000977 BBI.IsUnpredicable = true;
978 return;
979 }
980 }
981}
982
983/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
984/// predicated by the specified predicate.
Kyle Butt71cb44d2016-08-06 01:52:37 +0000985/// @param BBI BBInfo for the block to check
986/// @param Pred Predicate array for the branch that leads to BBI
987/// @param isTriangle true if the Analysis is for a triangle
988/// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
989/// case
990/// @param hasCommonTail true if BBI shares a tail with a sibling block that
991/// contains any instruction that would make the block unpredicable.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000992bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000993 SmallVectorImpl<MachineOperand> &Pred,
Kyle Butt71cb44d2016-08-06 01:52:37 +0000994 bool isTriangle, bool RevBranch,
995 bool hasCommonTail) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000996 // If the block is dead or unpredicable, then it cannot be predicated.
Kyle Butt71cb44d2016-08-06 01:52:37 +0000997 // Two blocks may share a common unpredicable tail, but this doesn't prevent
998 // them from being if-converted. The non-shared portion is assumed to have
999 // been checked
1000 if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001001 return false;
1002
Ahmed Bougacha7173b662015-03-21 01:23:15 +00001003 // If it is already predicated but we couldn't analyze its terminator, the
1004 // latter might fallthrough, but we can't determine where to.
1005 // Conservatively avoid if-converting again.
1006 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1007 return false;
1008
Quentin Colombetbdab2272013-07-24 20:20:37 +00001009 // If it is already predicated, check if the new predicate subsumes
1010 // its predicate.
1011 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001012 return false;
1013
Kyle Butt71cb44d2016-08-06 01:52:37 +00001014 if (!hasCommonTail && BBI.BrCond.size()) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001015 if (!isTriangle)
1016 return false;
1017
Bob Wilson2371f4f2009-05-13 23:25:24 +00001018 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +00001019 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1020 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +00001021 if (RevBranch) {
1022 if (TII->ReverseBranchCondition(Cond))
1023 return false;
1024 }
1025 if (TII->ReverseBranchCondition(RevPred) ||
1026 !TII->SubsumesPredicate(Cond, RevPred))
1027 return false;
1028 }
1029
1030 return true;
1031}
1032
Evan Cheng7783f822007-06-08 09:36:04 +00001033/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +00001034/// the specified block. Record its successors and whether it looks like an
1035/// if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001036void IfConverter::AnalyzeBlock(
1037 MachineBasicBlock *MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001038 struct BBState {
1039 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
1040 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +00001041
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001042 /// This flag is true if MBB's successors have been analyzed.
1043 bool SuccsAnalyzed;
1044 };
Evan Cheng0f745da2007-05-18 00:20:58 +00001045
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001046 // Push MBB to the stack.
1047 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001048
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001049 while (!BBStack.empty()) {
1050 BBState &State = BBStack.back();
1051 MachineBasicBlock *BB = State.MBB;
1052 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +00001053
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001054 if (!State.SuccsAnalyzed) {
1055 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1056 BBStack.pop_back();
1057 continue;
1058 }
Evan Cheng9030b982007-06-06 10:16:17 +00001059
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001060 BBI.BB = BB;
1061 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +00001062
Kyle Butt54bf3ce2016-08-06 01:52:34 +00001063 AnalyzeBranches(BBI);
1064 MachineBasicBlock::iterator Begin = BBI.BB->begin();
1065 MachineBasicBlock::iterator End = BBI.BB->end();
1066 ScanInstructions(BBI, Begin, End);
Evan Chengb9bff582009-06-15 21:24:34 +00001067
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001068 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1069 // not considered for ifcvt anymore.
1070 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1071 BBI.IsBeingAnalyzed = false;
1072 BBI.IsAnalyzed = true;
1073 BBStack.pop_back();
1074 continue;
1075 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001076
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001077 // Do not ifcvt if either path is a back edge to the entry block.
1078 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1079 BBI.IsBeingAnalyzed = false;
1080 BBI.IsAnalyzed = true;
1081 BBStack.pop_back();
1082 continue;
1083 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001084
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001085 // Do not ifcvt if true and false fallthrough blocks are the same.
1086 if (!BBI.FalseBB) {
1087 BBI.IsBeingAnalyzed = false;
1088 BBI.IsAnalyzed = true;
1089 BBStack.pop_back();
1090 continue;
1091 }
Evan Cheng7783f822007-06-08 09:36:04 +00001092
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001093 // Push the False and True blocks to the stack.
1094 State.SuccsAnalyzed = true;
1095 BBStack.push_back(BBI.FalseBB);
1096 BBStack.push_back(BBI.TrueBB);
1097 continue;
1098 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +00001099
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001100 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1101 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +00001102
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001103 if (TrueBBI.IsDone && FalseBBI.IsDone) {
1104 BBI.IsBeingAnalyzed = false;
1105 BBI.IsAnalyzed = true;
1106 BBStack.pop_back();
1107 continue;
1108 }
1109
1110 SmallVector<MachineOperand, 4>
1111 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1112 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
1113
1114 unsigned Dups = 0;
1115 unsigned Dups2 = 0;
1116 bool TNeedSub = !TrueBBI.Predicate.empty();
1117 bool FNeedSub = !FalseBBI.Predicate.empty();
1118 bool Enqueued = false;
1119
1120 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1121
Kyle Butt71cb44d2016-08-06 01:52:37 +00001122 if (CanRevCond) {
1123 BBInfo TrueBBICalc, FalseBBICalc;
1124 auto feasibleDiamond = [&]() {
1125 return (
1126 MeetIfcvtSizeLimit(
1127 *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1128 TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1129 *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1130 FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1131 Prediction) &&
1132 FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1133 /* IsTriangle */ false, /* RevCond */ false,
1134 /* hasCommonTail */ true) &&
1135 FeasibilityAnalysis(FalseBBI, RevCond,
1136 /* IsTriangle */ false, /* RevCond */ false,
1137 /* hasCommonTail */ true));
1138 };
1139
1140 if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1141 TrueBBICalc, FalseBBICalc)) {
1142 if (feasibleDiamond()) {
1143 // Diamond:
1144 // EBB
1145 // / \_
1146 // | |
1147 // TBB FBB
1148 // \ /
1149 // TailBB
1150 // Note TailBB can be empty.
1151 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1152 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
1153 Enqueued = true;
1154 }
1155 } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1156 TrueBBICalc, FalseBBICalc)) {
1157 if (feasibleDiamond()) {
1158 // ForkedDiamond:
1159 // if TBB and FBB have a common tail that includes their conditional
1160 // branch instructions, then we can If Convert this pattern.
1161 // EBB
1162 // _/ \_
1163 // | |
1164 // TBB FBB
1165 // / \ / \
1166 // FalseBB TrueBB FalseBB
1167 //
1168 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1169 BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1170 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1171 Enqueued = true;
1172 }
1173 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001174 }
1175
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001176 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1177 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1178 TrueBBI.ExtraCost2, Prediction) &&
1179 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1180 // Triangle:
1181 // EBB
1182 // | \_
1183 // | |
1184 // | TBB
1185 // | /
1186 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001187 Tokens.push_back(
1188 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001189 Enqueued = true;
1190 }
1191
1192 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1193 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1194 TrueBBI.ExtraCost2, Prediction) &&
1195 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001196 Tokens.push_back(
1197 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001198 Enqueued = true;
1199 }
1200
1201 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1202 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1203 TrueBBI.ExtraCost2, Prediction) &&
1204 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1205 // Simple (split, no rejoin):
1206 // EBB
1207 // | \_
1208 // | |
1209 // | TBB---> exit
1210 // |
1211 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001212 Tokens.push_back(
1213 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001214 Enqueued = true;
1215 }
1216
1217 if (CanRevCond) {
1218 // Try the other path...
1219 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1220 Prediction.getCompl()) &&
1221 MeetIfcvtSizeLimit(*FalseBBI.BB,
1222 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1223 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1224 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001225 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1226 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001227 Enqueued = true;
1228 }
1229
1230 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1231 Prediction.getCompl()) &&
1232 MeetIfcvtSizeLimit(*FalseBBI.BB,
1233 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +00001234 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +00001235 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001236 Tokens.push_back(
1237 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001238 Enqueued = true;
1239 }
1240
1241 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1242 MeetIfcvtSizeLimit(*FalseBBI.BB,
1243 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1244 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1245 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001246 Tokens.push_back(
1247 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001248 Enqueued = true;
1249 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001250 }
1251
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001252 BBI.IsEnqueued = Enqueued;
1253 BBI.IsBeingAnalyzed = false;
1254 BBI.IsAnalyzed = true;
1255 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001256 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001257}
1258
Evan Cheng905a8f42007-05-30 19:49:19 +00001259/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +00001260/// candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001261void IfConverter::AnalyzeBlocks(
1262 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001263 for (auto &BB : MF)
1264 AnalyzeBlock(&BB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001265
Evan Cheng20e05992007-06-01 00:12:12 +00001266 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +00001267 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001268}
1269
Evan Cheng288f1542007-06-08 22:01:07 +00001270/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
1271/// that all the intervening blocks are empty (given BB can fall through to its
1272/// next block).
1273static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001274 MachineFunction::iterator PI = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001275 MachineFunction::iterator I = std::next(PI);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001276 MachineFunction::iterator TI = ToBB->getIterator();
Evan Cheng2c1acd62007-06-05 07:05:25 +00001277 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001278 while (I != TI) {
1279 // Check isSuccessor to avoid case where the next block is empty, but
1280 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001281 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001282 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001283 PI = I++;
1284 }
Evan Cheng312b7232007-06-04 06:47:22 +00001285 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001286}
1287
Evan Cheng51eb2c32007-06-18 08:37:25 +00001288/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
1289/// to determine if it can be if-converted. If predecessor is already enqueued,
1290/// dequeue it!
1291void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001292 for (const auto &Predecessor : BB->predecessors()) {
1293 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +00001294 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001295 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001296 PBBI.IsAnalyzed = false;
1297 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001298 }
1299}
1300
Evan Chengc2237ce2007-05-29 22:31:16 +00001301/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
1302///
1303static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
1304 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001305 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001306 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +00001307 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001308}
1309
Evan Cheng288f1542007-06-08 22:01:07 +00001310/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1311/// successors.
1312void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001313 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001314 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001315 if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
Evan Cheng0598b2d2007-06-18 22:44:57 +00001316 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001317}
1318
Matthias Braund616ccc2013-10-11 19:04:37 +00001319/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Jonas Paulsson196986c2016-08-03 05:46:35 +00001320/// values defined in MI which are also live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001321static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Jonas Paulsson196986c2016-08-03 05:46:35 +00001322 const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1323 ->getSubtarget().getRegisterInfo();
1324
1325 // Before stepping forward past MI, remember which regs were live
1326 // before MI. This is needed to set the Undef flag only when reg is
1327 // dead.
1328 SparseSet<unsigned> LiveBeforeMI;
1329 LiveBeforeMI.setUniverse(TRI->getNumRegs());
1330 for (auto &Reg : Redefs)
1331 LiveBeforeMI.insert(Reg);
1332
Pete Cooper7605e372015-05-05 20:14:22 +00001333 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001334 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001335
Pete Cooper7605e372015-05-05 20:14:22 +00001336 // Now add the implicit uses for each of the clobbered values.
1337 for (auto Reg : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001338 // FIXME: Const cast here is nasty, but better than making StepForward
1339 // take a mutable instruction instead of const.
Pete Cooper27483912015-05-06 22:51:04 +00001340 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1341 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001342 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001343 if (Op.isRegMask()) {
1344 // First handle regmasks. They clobber any entries in the mask which
1345 // means that we need a def for those registers.
Jonas Paulsson196986c2016-08-03 05:46:35 +00001346 if (LiveBeforeMI.count(Reg.first))
1347 MIB.addReg(Reg.first, RegState::Implicit);
Pete Cooperce9ad752015-05-05 22:09:41 +00001348
1349 // We also need to add an implicit def of this register for the later
1350 // use to read from.
1351 // For the register allocator to have allocated a register clobbered
1352 // by the call which is used later, it must be the case that
1353 // the call doesn't return.
1354 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1355 continue;
1356 }
1357 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001358 if (Op.isDead()) {
1359 // If we found a dead def, but it needs to be live, then remove the dead
1360 // flag.
1361 if (Redefs.contains(Op.getReg()))
1362 Op.setIsDead(false);
1363 }
Jonas Paulsson196986c2016-08-03 05:46:35 +00001364 if (LiveBeforeMI.count(Reg.first))
1365 MIB.addReg(Reg.first, RegState::Implicit);
Matthias Braund616ccc2013-10-11 19:04:37 +00001366 }
1367}
1368
1369/**
1370 * Remove kill flags from operands with a registers in the @p DontKill set.
1371 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001372static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001373 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001374 if (!O->isReg() || !O->isKill())
1375 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001376 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001377 O->setIsKill(false);
1378 }
1379}
1380
1381/**
1382 * Walks a range of machine instructions and removes kill flags for registers
1383 * in the @p DontKill set.
1384 */
1385static void RemoveKills(MachineBasicBlock::iterator I,
1386 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001387 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001388 const MCRegisterInfo &MCRI) {
1389 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001390 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001391}
1392
Evan Cheng312b7232007-06-04 06:47:22 +00001393/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001394///
Evan Cheng3a51c852007-06-16 09:34:52 +00001395bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001396 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1397 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1398 BBInfo *CvtBBI = &TrueBBI;
1399 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001400
Owen Anderson4f6bf042008-08-14 22:49:33 +00001401 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001402 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001403 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001404
Evan Cheng51eb2c32007-06-18 08:37:25 +00001405 if (CvtBBI->IsDone ||
1406 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001407 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001408 BBI.IsAnalyzed = false;
1409 CvtBBI->IsAnalyzed = false;
1410 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001411 }
Evan Chengd0e66912007-05-23 07:23:16 +00001412
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001413 if (CvtBBI->BB->hasAddressTaken())
1414 // Conservatively abort if-conversion if BB's address is taken.
1415 return false;
1416
Evan Cheng3a51c852007-06-16 09:34:52 +00001417 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001418 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001419 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001420
Bob Wilson45814342010-06-19 05:33:57 +00001421 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001422 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001423 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001424 Redefs.addLiveIns(*CvtBBI->BB);
1425 Redefs.addLiveIns(*NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001426
1427 // Compute a set of registers which must not be killed by instructions in
1428 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001429 DontKill.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001430 DontKill.addLiveIns(*NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001431
Evan Cheng92fb5452007-06-15 07:36:12 +00001432 if (CvtBBI->BB->pred_size() > 1) {
1433 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001434 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001435 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001436 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001437
1438 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1439 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001440 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001441 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001442 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001443 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001444
Evan Cheng92fb5452007-06-15 07:36:12 +00001445 // Merge converted block into entry block.
1446 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1447 MergeBlocks(BBI, *CvtBBI);
1448 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001449
Evan Chenge4ec9182007-06-06 02:08:52 +00001450 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001451 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001452 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001453 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001454 // Now ifcvt'd block will look like this:
1455 // BB:
1456 // ...
1457 // t, f = cmp
1458 // if t op
1459 // b BBf
1460 //
1461 // We cannot further ifcvt this block because the unconditional branch
1462 // will have to be predicated on the new condition, that will not be
1463 // available if cmp executes.
1464 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001465 }
Evan Chenge26c0912007-05-21 22:22:58 +00001466
Evan Cheng288f1542007-06-08 22:01:07 +00001467 RemoveExtraEdges(BBI);
1468
Evan Chengd0e66912007-05-23 07:23:16 +00001469 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001470 if (!IterIfcvt)
1471 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001472 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001473 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001474
1475 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001476 return true;
1477}
1478
Evan Chengaf716102007-05-16 21:54:37 +00001479/// IfConvertTriangle - If convert a triangle sub-CFG.
1480///
Evan Cheng3a51c852007-06-16 09:34:52 +00001481bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001482 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001483 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1484 BBInfo *CvtBBI = &TrueBBI;
1485 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001486 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001487
Owen Anderson4f6bf042008-08-14 22:49:33 +00001488 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001489 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001490 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001491
Evan Cheng51eb2c32007-06-18 08:37:25 +00001492 if (CvtBBI->IsDone ||
1493 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001494 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001495 BBI.IsAnalyzed = false;
1496 CvtBBI->IsAnalyzed = false;
1497 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001498 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001499
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001500 if (CvtBBI->BB->hasAddressTaken())
1501 // Conservatively abort if-conversion if BB's address is taken.
1502 return false;
1503
Evan Cheng3a51c852007-06-16 09:34:52 +00001504 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001505 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001506 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001507
Evan Cheng3a51c852007-06-16 09:34:52 +00001508 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001509 if (ReverseBranchCondition(*CvtBBI)) {
1510 // BB has been changed, modify its predecessors (except for this
1511 // one) so they don't get ifcvt'ed based on bad intel.
1512 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1513 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1514 MachineBasicBlock *PBB = *PI;
1515 if (PBB == BBI.BB)
1516 continue;
1517 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1518 if (PBBI.IsEnqueued) {
1519 PBBI.IsAnalyzed = false;
1520 PBBI.IsEnqueued = false;
1521 }
Evan Chengadd97762007-06-14 23:34:09 +00001522 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001523 }
1524 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001525
Bob Wilson45814342010-06-19 05:33:57 +00001526 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001527 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001528 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001529 Redefs.addLiveIns(*CvtBBI->BB);
1530 Redefs.addLiveIns(*NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001531
Andrew Trick276dd452013-10-14 20:45:17 +00001532 DontKill.clear();
1533
Craig Topperc0196b12014-04-14 00:51:57 +00001534 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001535 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001536
Manman Renb6819182014-01-29 23:18:47 +00001537 if (HasEarlyExit) {
Cong Houd97c1002015-12-01 05:29:22 +00001538 // Get probabilities before modifying CvtBBI->BB and BBI.BB.
1539 CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB);
1540 CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB);
1541 BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB);
1542 BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001543 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001544
Bob Wilson1e5da552010-06-29 00:55:23 +00001545 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001546 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001547 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001548 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001549 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001550
1551 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1552 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001553 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001554 } else {
1555 // Predicate the 'true' block after removing its branch.
1556 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001557 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001558
Evan Cheng0598b2d2007-06-18 22:44:57 +00001559 // Now merge the entry of the triangle with the true block.
1560 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001561 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001562 }
1563
Evan Cheng312b7232007-06-04 06:47:22 +00001564 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001565 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001566 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1567 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001568 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001569 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001570
Cong Houd97c1002015-12-01 05:29:22 +00001571 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1572 // NewNext = New_Prob(BBI.BB, NextBBI->BB) =
1573 // Prob(BBI.BB, NextBBI->BB) +
1574 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB)
1575 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1576 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB)
1577 auto NewTrueBB = getNextBlock(BBI.BB);
1578 auto NewNext = BBNext + BBCvt * CvtNext;
1579 auto NewTrueBBIter =
1580 std::find(BBI.BB->succ_begin(), BBI.BB->succ_end(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001581 if (NewTrueBBIter != BBI.BB->succ_end())
1582 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001583
1584 auto NewFalse = BBCvt * CvtFalse;
1585 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1586 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001587 }
Evan Cheng7783f822007-06-08 09:36:04 +00001588
1589 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001590 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001591 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001592 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001593 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001594 if (!isFallThrough) {
1595 // Only merge them if the true block does not fallthrough to the false
1596 // block. By not merging them, we make it possible to iteratively
1597 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001598 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001599 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1600 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001601 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001602 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001603 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001604 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1605 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001606 }
Evan Cheng7783f822007-06-08 09:36:04 +00001607 // Mixed predicated and unpredicated code. This cannot be iteratively
1608 // predicated.
1609 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001610 }
Evan Chenge26c0912007-05-21 22:22:58 +00001611
Evan Cheng288f1542007-06-08 22:01:07 +00001612 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001613
Evan Chengd0e66912007-05-23 07:23:16 +00001614 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001615 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001616 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001617 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001618 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001619 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001620 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001621
1622 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001623 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001624}
1625
Kyle Butt71cb44d2016-08-06 01:52:37 +00001626/// IfConvertDiamondCommon - Common code shared between diamond conversions.
1627/// BBI, TrueBBI, and FalseBBI form the diamond shape.
1628/// NumDups1 - number of shared instructions at the beginning of TrueBBI and
1629/// FalseBBI
1630/// NumDups2 - number of shared instructions at the end of TrueBBI and FalseBBI
1631/// RemoveTrueBranch - Remove the branch of the true block before predicating
1632/// Only false for unanalyzable fallthrough cases.
1633/// RemoveFalseBranch - Remove the branch of the false block before predicating
1634/// Only false for unanalyzable fallthrough cases.
1635/// MergeAddEdges - Add successor edges when merging blocks. Only false for
1636/// unanalyzable fallthrough
1637bool IfConverter::IfConvertDiamondCommon(
1638 BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1639 unsigned NumDups1, unsigned NumDups2,
1640 bool TClobbersPred, bool FClobbersPred,
1641 bool RemoveTrueBranch, bool RemoveFalseBranch,
1642 bool MergeAddEdges) {
Evan Chenge26c0912007-05-21 22:22:58 +00001643
Evan Cheng51eb2c32007-06-18 08:37:25 +00001644 if (TrueBBI.IsDone || FalseBBI.IsDone ||
Kyle Butt71cb44d2016-08-06 01:52:37 +00001645 TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001646 // Something has changed. It's no longer safe to predicate these blocks.
1647 BBI.IsAnalyzed = false;
1648 TrueBBI.IsAnalyzed = false;
1649 FalseBBI.IsAnalyzed = false;
1650 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001651 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001652
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001653 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1654 // Conservatively abort if-conversion if either BB has its address taken.
1655 return false;
1656
Bob Wilson1e5da552010-06-29 00:55:23 +00001657 // Put the predicated instructions from the 'true' block before the
1658 // instructions from the 'false' block, unless the true block would clobber
1659 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001660 BBInfo *BBI1 = &TrueBBI;
1661 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001662 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001663 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001664 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001665 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1666 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001667
Evan Cheng3a51c852007-06-16 09:34:52 +00001668 // Figure out the more profitable ordering.
1669 bool DoSwap = false;
Kyle Butt71cb44d2016-08-06 01:52:37 +00001670 if (TClobbersPred && !FClobbersPred)
Evan Cheng3a51c852007-06-16 09:34:52 +00001671 DoSwap = true;
Kyle Butt71cb44d2016-08-06 01:52:37 +00001672 else if (TClobbersPred == FClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001673 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001674 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001675 }
1676 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001677 std::swap(BBI1, BBI2);
1678 std::swap(Cond1, Cond2);
Kyle Butt71cb44d2016-08-06 01:52:37 +00001679 std::swap(RemoveTrueBranch, RemoveFalseBranch);
Evan Cheng30565992007-06-06 00:57:55 +00001680 }
Evan Cheng79484222007-06-05 23:46:14 +00001681
Evan Cheng51eb2c32007-06-18 08:37:25 +00001682 // Remove the conditional branch from entry to the blocks.
1683 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1684
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001685 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001686 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001687 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001688 Redefs.addLiveIns(*BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001689
Evan Cheng51eb2c32007-06-18 08:37:25 +00001690 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001691 // Skip dbg_value instructions
Benjamin Kramer6b568962015-06-23 14:47:29 +00001692 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1693 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001694 BBI1->NonPredSize -= NumDups1;
1695 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001696
1697 // Skip past the dups on each side separately since there may be
1698 // differing dbg_value entries.
1699 for (unsigned i = 0; i < NumDups1; ++DI1) {
1700 if (!DI1->isDebugValue())
1701 ++i;
1702 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001703 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001704 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001705 if (!DI2->isDebugValue())
1706 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001707 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001708
Matthias Braund616ccc2013-10-11 19:04:37 +00001709 // Compute a set of registers which must not be killed by instructions in BB1:
1710 // This is everything used+live in BB2 after the duplicated instructions. We
1711 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001712 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001713 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1714 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001715 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001716 }
1717
1718 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1719 ++I) {
Pete Cooper7605e372015-05-05 20:14:22 +00001720 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1721 Redefs.stepForward(*I, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001722 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001723 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1724 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1725
Kyle Butt71cb44d2016-08-06 01:52:37 +00001726 if (RemoveTrueBranch)
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001727 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1728 // Remove duplicated instructions.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001729 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001730 for (unsigned i = 0; i != NumDups2; ) {
1731 // NumDups2 only counted non-dbg_value instructions, so this won't
1732 // run off the head of the list.
1733 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001734 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001735 // skip dbg_value instructions
1736 if (!DI1->isDebugValue())
1737 ++i;
1738 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001739 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001740
Matthias Braund616ccc2013-10-11 19:04:37 +00001741 // Kill flags in the true block for registers living into the false block
1742 // must be removed.
1743 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1744
Kyle Butt71cb44d2016-08-06 01:52:37 +00001745 // Remove 'false' block branch, and find the last instruction to predicate.
1746 // Save the debug location.
1747 if (RemoveFalseBranch)
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001748 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001749 DI2 = BBI2->BB->end();
1750 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001751 // NumDups2 only counted non-dbg_value instructions, so this won't
1752 // run off the head of the list.
1753 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001754 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001755 // skip dbg_value instructions
1756 if (!DI2->isDebugValue())
1757 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001758 }
Evan Cheng4266a792011-12-19 22:01:30 +00001759
1760 // Remember which registers would later be defined by the false block.
1761 // This allows us not to predicate instructions in the true block that would
1762 // later be re-defined. That is, rather than
1763 // subeq r0, r1, #1
1764 // addne r0, r1, #1
1765 // generate:
1766 // sub r0, r1, #1
1767 // addne r0, r1, #1
1768 SmallSet<unsigned, 4> RedefsByFalse;
1769 SmallSet<unsigned, 4> ExtUses;
1770 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1771 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1772 if (FI->isDebugValue())
1773 continue;
1774 SmallVector<unsigned, 4> Defs;
1775 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1776 const MachineOperand &MO = FI->getOperand(i);
1777 if (!MO.isReg())
1778 continue;
1779 unsigned Reg = MO.getReg();
1780 if (!Reg)
1781 continue;
1782 if (MO.isDef()) {
1783 Defs.push_back(Reg);
1784 } else if (!RedefsByFalse.count(Reg)) {
1785 // These are defined before ctrl flow reach the 'false' instructions.
1786 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001787 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1788 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001789 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001790 }
1791 }
1792
1793 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1794 unsigned Reg = Defs[i];
1795 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001796 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1797 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001798 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001799 }
1800 }
1801 }
1802 }
1803
1804 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001805 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001806
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001807 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1808 // a non-predicated in BBI2, then we don't want to predicate the one from
1809 // BBI2. The reason is that if we merged these blocks, we would end up with
1810 // two predicated terminators in the same block.
1811 if (!BBI2->BB->empty() && (DI2 == BBI2->BB->end())) {
1812 MachineBasicBlock::iterator BBI1T = BBI1->BB->getFirstTerminator();
1813 MachineBasicBlock::iterator BBI2T = BBI2->BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001814 if (BBI1T != BBI1->BB->end() && TII->isPredicated(*BBI1T) &&
1815 BBI2T != BBI2->BB->end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001816 --DI2;
1817 }
1818
Evan Cheng4266a792011-12-19 22:01:30 +00001819 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001820 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001821
Evan Cheng0598b2d2007-06-18 22:44:57 +00001822 // Merge the true block into the entry of the diamond.
Kyle Butt71cb44d2016-08-06 01:52:37 +00001823 MergeBlocks(BBI, *BBI1, MergeAddEdges);
1824 MergeBlocks(BBI, *BBI2, MergeAddEdges);
1825 return true;
1826}
1827
1828/// IfConvertForkedDiamond - If convert an almost-diamond sub-CFG where the true
1829/// and false blocks share a common tail.
1830bool IfConverter::IfConvertForkedDiamond(
1831 BBInfo &BBI, IfcvtKind Kind,
1832 unsigned NumDups1, unsigned NumDups2,
1833 bool TClobbersPred, bool FClobbersPred) {
1834 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1835 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1836
1837 // Save the debug location for later.
1838 DebugLoc dl;
1839 MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1840 if (TIE != TrueBBI.BB->end())
1841 dl = TIE->getDebugLoc();
1842 // Removing branches from both blocks is safe, because we have already
1843 // determined that both blocks have the same branch instructions. The branch
1844 // will be added back at the end, unpredicated.
1845 if (!IfConvertDiamondCommon(
1846 BBI, TrueBBI, FalseBBI,
1847 NumDups1, NumDups2,
1848 TClobbersPred, FClobbersPred,
1849 /* RemoveTrueBranch */ true, /* RemoveFalseBranch */ true,
1850 /* MergeAddEdges */ true))
1851 return false;
1852
1853 // Add back the branch.
1854 // Debug location saved above when removing the branch from BBI2
1855 TII->InsertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
1856 TrueBBI.BrCond, dl);
1857
1858 RemoveExtraEdges(BBI);
1859
1860 // Update block info.
1861 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1862 InvalidatePreds(BBI.BB);
1863
1864 // FIXME: Must maintain LiveIns.
1865 return true;
1866}
1867
1868/// IfConvertDiamond - If convert a diamond sub-CFG.
1869///
1870bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1871 unsigned NumDups1, unsigned NumDups2) {
1872 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1873 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1874 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1875
1876 // True block must fall through or end with an unanalyzable terminator.
1877 if (!TailBB) {
1878 if (blockAlwaysFallThrough(TrueBBI))
1879 TailBB = FalseBBI.TrueBB;
1880 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1881 }
1882
1883 if (!IfConvertDiamondCommon(
1884 BBI, TrueBBI, FalseBBI,
1885 NumDups1, NumDups2,
1886 TrueBBI.ClobbersPred, FalseBBI.ClobbersPred,
1887 /* RemoveTrueBranch */ TrueBBI.IsBrAnalyzable,
1888 /* RemoveFalseBranch */ FalseBBI.IsBrAnalyzable,
1889 /* MergeAddEdges */ TailBB == nullptr))
1890 return false;
Evan Cheng30565992007-06-06 00:57:55 +00001891
Bob Wilson2371f4f2009-05-13 23:25:24 +00001892 // If the if-converted block falls through or unconditionally branches into
1893 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001894 // fold the tail block in as well. Otherwise, unless it falls through to the
1895 // tail, add a unconditional branch to it.
1896 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001897 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001898 bool CanMergeTail = !TailBBI.HasFallThrough &&
1899 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001900 // The if-converted block can still have a predicated terminator
1901 // (e.g. a predicated return). If that is the case, we cannot merge
1902 // it with the tail block.
1903 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001904 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001905 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001906 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1907 // check if there are any other predecessors besides those.
1908 unsigned NumPreds = TailBB->pred_size();
1909 if (NumPreds > 1)
1910 CanMergeTail = false;
1911 else if (NumPreds == 1 && CanMergeTail) {
1912 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
Kyle Butt71cb44d2016-08-06 01:52:37 +00001913 if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
Bob Wilson1e5da552010-06-29 00:55:23 +00001914 CanMergeTail = false;
1915 }
1916 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001917 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001918 TailBBI.IsDone = true;
1919 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001920 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Evan Cheng0598b2d2007-06-18 22:44:57 +00001921 InsertUncondBranch(BBI.BB, TailBB, TII);
1922 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001923 }
Evan Chenge26c0912007-05-21 22:22:58 +00001924 }
1925
Bob Wilson1e5da552010-06-29 00:55:23 +00001926 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1927 // which can happen here if TailBB is unanalyzable and is merged, so
1928 // explicitly remove BBI1 and BBI2 as successors.
Kyle Butt71cb44d2016-08-06 01:52:37 +00001929 BBI.BB->removeSuccessor(TrueBBI.BB);
1930 BBI.BB->removeSuccessor(FalseBBI.BB, /* NormalizeSuccessProbs */ true);
Evan Cheng288f1542007-06-08 22:01:07 +00001931 RemoveExtraEdges(BBI);
1932
Evan Cheng79484222007-06-05 23:46:14 +00001933 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001934 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001935 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001936
1937 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001938 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001939}
1940
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001941static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001942 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001943 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001944 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001945 return false;
1946
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001947 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1948 const MachineOperand &MO = MI.getOperand(i);
Evan Cheng4266a792011-12-19 22:01:30 +00001949 if (!MO.isReg())
1950 continue;
1951 unsigned Reg = MO.getReg();
1952 if (!Reg)
1953 continue;
1954 if (MO.isDef() && !LaterRedefs.count(Reg))
1955 return false;
1956 }
1957
1958 return true;
1959}
1960
Evan Cheng51eb2c32007-06-18 08:37:25 +00001961/// PredicateBlock - Predicate instructions from the start of the block to the
1962/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001963void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001964 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001965 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001966 SmallSet<unsigned, 4> *LaterRedefs) {
1967 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001968 bool MaySpec = LaterRedefs != nullptr;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001969 for (MachineInstr &I : llvm::make_range(BBI.BB->begin(), E)) {
1970 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001971 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001972 // It may be possible not to predicate an instruction if it's the 'true'
1973 // side of a diamond and the 'false' side may re-define the instruction's
1974 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001975 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001976 AnyUnpred = true;
1977 continue;
1978 }
1979 // If any instruction is predicated, then every instruction after it must
1980 // be predicated.
1981 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001982 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001983#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001984 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001985#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001986 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001987 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001988
Bob Wilson45814342010-06-19 05:33:57 +00001989 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001990 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001991 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001992 }
Evan Chengd0e66912007-05-23 07:23:16 +00001993
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001994 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001995
Evan Cheng92fb5452007-06-15 07:36:12 +00001996 BBI.IsAnalyzed = false;
1997 BBI.NonPredSize = 0;
1998
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001999 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00002000 if (AnyUnpred)
2001 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00002002}
2003
Evan Cheng92fb5452007-06-15 07:36:12 +00002004/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
2005/// the destination block. Skip end of block branches if IgnoreBr is true.
2006void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00002007 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00002008 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00002009 MachineFunction &MF = *ToBBI.BB->getParent();
2010
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002011 for (auto &I : *FromBBI.BB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00002012 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002013 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00002014 break;
2015
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002016 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00002017 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00002018 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002019 unsigned ExtraPredCost = TII->getPredicationCost(I);
2020 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00002021 if (NumCycles > 1)
2022 ToBBI.ExtraCost += NumCycles-1;
2023 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00002024
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00002025 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002026 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00002027#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002028 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00002029#endif
Craig Topperc0196b12014-04-14 00:51:57 +00002030 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00002031 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002032 }
2033
Bob Wilson45814342010-06-19 05:33:57 +00002034 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002035 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002036 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00002037
2038 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00002039 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00002040 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00002041 }
2042
Bob Wilson1e5da552010-06-29 00:55:23 +00002043 if (!IgnoreBr) {
2044 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
2045 FromBBI.BB->succ_end());
2046 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00002047 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00002048
Bob Wilson1e5da552010-06-29 00:55:23 +00002049 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
2050 MachineBasicBlock *Succ = Succs[i];
2051 // Fallthrough edge can't be transferred.
2052 if (Succ == FallThrough)
2053 continue;
2054 ToBBI.BB->addSuccessor(Succ);
2055 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00002056 }
2057
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002058 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2059 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002060
2061 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2062 ToBBI.IsAnalyzed = false;
2063
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002064 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00002065}
2066
Evan Cheng0f745da2007-05-18 00:20:58 +00002067/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00002068/// This will leave FromBB as an empty block, so remove all of its
2069/// successor edges except for the fall-through edge. If AddEdges is true,
2070/// i.e., when FromBBI's branch is being moved, add those successor edges to
2071/// ToBBI.
2072void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00002073 assert(!FromBBI.BB->hasAddressTaken() &&
2074 "Removing a BB whose address is taken!");
2075
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002076 // In case FromBBI.BB contains terminators (e.g. return instruction),
2077 // first move the non-terminator instructions, then the terminators.
2078 MachineBasicBlock::iterator FromTI = FromBBI.BB->getFirstTerminator();
2079 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
2080 ToBBI.BB->splice(ToTI, FromBBI.BB, FromBBI.BB->begin(), FromTI);
2081
2082 // If FromBB has non-predicated terminator we should copy it at the end.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002083 if (FromTI != FromBBI.BB->end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002084 ToTI = ToBBI.BB->end();
2085 ToBBI.BB->splice(ToTI, FromBBI.BB, FromTI, FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00002086
Cong Houb9e8d482015-12-17 01:29:08 +00002087 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2088 // unknown probabilities into known ones.
2089 // FIXME: This usage is too tricky and in the future we would like to
2090 // eliminate all unknown probabilities in MBB.
2091 ToBBI.BB->normalizeSuccProbs();
2092
Cong Houd40105d2015-09-18 20:22:41 +00002093 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
2094 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00002095 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00002096 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00002097 // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when
Hans Wennborg1dbaf672015-12-01 03:49:42 +00002098 // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00002099 auto To2FromProb = BranchProbability::getZero();
Cong Houfa1917c2015-12-01 00:02:51 +00002100 if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
Cong Houd97c1002015-12-01 05:29:22 +00002101 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB);
2102 // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the
2103 // edge probability being merged to other edges when this edge is removed
2104 // later.
2105 ToBBI.BB->setSuccProbability(
2106 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB),
2107 BranchProbability::getZero());
2108 }
2109
Cong Houd40105d2015-09-18 20:22:41 +00002110 for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
2111 MachineBasicBlock *Succ = FromSuccs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00002112 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00002113 if (Succ == FallThrough)
2114 continue;
Cong Houd40105d2015-09-18 20:22:41 +00002115
Cong Houd97c1002015-12-01 05:29:22 +00002116 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00002117 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002118 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
2119 // which is a portion of the edge probability from FromBBI.BB to Succ. The
2120 // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if
2121 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
2122 NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002123
Cong Houd97c1002015-12-01 05:29:22 +00002124 // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
Cong Houd40105d2015-09-18 20:22:41 +00002125 // only happens when if-converting a diamond CFG and FromBBI.BB is the
2126 // tail BB. In this case FromBBI.BB post-dominates ToBBI.BB and hence we
Cong Houd97c1002015-12-01 05:29:22 +00002127 // could just use the probabilities on FromBBI.BB's out-edges when adding
2128 // new successors.
2129 if (!To2FromProb.isZero())
2130 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00002131 }
2132
Evan Chengbe9859e2007-06-07 02:12:15 +00002133 FromBBI.BB->removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002134
2135 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002136 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00002137 // probability of this edge by adding NewProb to it. An example is shown
Cong Houd97c1002015-12-01 05:29:22 +00002138 // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we
2139 // don't have to set C as A's successor as it already is. We only need to
2140 // update the edge probability on A->C. Note that B will not be
2141 // immediately removed from A's successors. It is possible that B->D is
2142 // not removed either if D is a fallthrough of B. Later the edge A->D
2143 // (generated here) and B->D will be combined into one edge. To maintain
2144 // correct edge probability of this combined edge, we need to set the edge
2145 // probability of A->B to zero, which is already done above. The edge
2146 // probability on A->D is calculated by scaling the original probability
2147 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00002148 //
2149 // Before ifcvt: After ifcvt (assume B->D is kept):
2150 //
2151 // A A
2152 // /| /|\
2153 // / B / B|
2154 // | /| | ||
2155 // |/ | | |/
2156 // C D C D
2157 //
2158 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00002159 ToBBI.BB->setSuccProbability(
Cong Houd40105d2015-09-18 20:22:41 +00002160 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00002161 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002162 else
Cong Houd97c1002015-12-01 05:29:22 +00002163 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002164 }
Evan Chengbe9859e2007-06-07 02:12:15 +00002165 }
2166
Bob Wilson2371f4f2009-05-13 23:25:24 +00002167 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00002168 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00002169 FromBBI.BB->addSuccessor(NBB);
2170
Cong Houc1069892015-12-13 09:26:17 +00002171 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2172 // we've done above.
2173 ToBBI.BB->normalizeSuccProbs();
2174
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002175 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002176 FromBBI.Predicate.clear();
2177
Evan Chengd0e66912007-05-23 07:23:16 +00002178 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002179 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00002180 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00002181 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002182 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00002183 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00002184
Evan Cheng4dd31a72007-06-11 22:26:22 +00002185 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00002186 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00002187 ToBBI.IsAnalyzed = false;
2188 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00002189}
Akira Hatanaka4a616192015-06-08 18:50:43 +00002190
2191FunctionPass *
2192llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00002193 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00002194}