blob: 22fe5288d8df6edefd892fb5679dbff594057600 [file] [log] [blame]
Evan Chengf5e53a52007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
Justin Lebaracc47102016-04-01 01:09:03 +000010// This file implements the machine instruction level if-conversion pass, which
11// tries to convert conditional branches into predicated instructions.
Evan Chengf5e53a52007-05-16 02:00:57 +000012//
13//===----------------------------------------------------------------------===//
14
Evan Chengf5e53a52007-05-16 02:00:57 +000015#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "BranchFolding.h"
17#include "llvm/ADT/STLExtras.h"
Kyle Butte1c931b2016-08-10 20:45:56 +000018#include "llvm/ADT/ScopeExit.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000021#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000022#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000023#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000024#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000025#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000028#include "llvm/CodeGen/TargetSchedule.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000029#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000030#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000031#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000036#include "llvm/Target/TargetSubtargetInfo.h"
Cong Houd97c1002015-12-01 05:29:22 +000037#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000038#include <utility>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000039
Evan Chengf5e53a52007-05-16 02:00:57 +000040using namespace llvm;
41
Chandler Carruth1b9dde02014-04-22 02:02:50 +000042#define DEBUG_TYPE "ifcvt"
43
Chris Lattner769c86b2008-01-07 05:40:58 +000044// Hidden options for help debugging.
45static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
46static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
47static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000048static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000049 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000050static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000051 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000052static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000053 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000054static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000055 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000056static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000057 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000058static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000059 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000060static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000061 cl::init(false), cl::Hidden);
Kyle Butte1c931b2016-08-10 20:45:56 +000062static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
63 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000064static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
65 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000066
Evan Cheng2117d1f2007-06-09 01:03:43 +000067STATISTIC(NumSimple, "Number of simple if-conversions performed");
68STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
69STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000070STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000071STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
72STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
73STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
Kyle Butte1c931b2016-08-10 20:45:56 +000074STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000075STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000076STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000077STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000078
79namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000080 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000081 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000082 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000083 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000084 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
85 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000086 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000087 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000088 ICTriangle, // BB is entry of a triangle sub-CFG.
Kyle Butte1c931b2016-08-10 20:45:56 +000089 ICDiamond, // BB is entry of a diamond sub-CFG.
90 ICForkedDiamond // BB is entry of an almost diamond sub-CFG, with a
91 // common tail that can be shared.
Evan Chengf5e53a52007-05-16 02:00:57 +000092 };
93
94 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
95 /// if-conversion feasibility analysis. This includes results from
Jacques Pienaar71c30a12016-07-15 14:41:04 +000096 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000097 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000098 /// diamond shape), its size, whether it's predicable, and whether any
99 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +0000100 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +0000101 /// IsDone - True if BB is not to be considered for ifcvt.
102 /// IsBeingAnalyzed - True if BB is currently being analyzed.
103 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
104 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000105 /// IsBrAnalyzable - True if analyzeBranch() returns false.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000106 /// HasFallThrough - True if BB may fallthrough to the following BB.
107 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000108 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000109 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000110 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000111 /// ExtraCost - Extra cost for multi-cycle instructions.
112 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000113 /// BB - Corresponding MachineBasicBlock.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000114 /// TrueBB / FalseBB- See analyzeBranch().
Evan Chengd0e66912007-05-23 07:23:16 +0000115 /// BrCond - Conditions for end of block conditional branches.
116 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000117 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000118 bool IsDone : 1;
119 bool IsBeingAnalyzed : 1;
120 bool IsAnalyzed : 1;
121 bool IsEnqueued : 1;
122 bool IsBrAnalyzable : 1;
Kyle Butte1c931b2016-08-10 20:45:56 +0000123 bool IsBrReversible : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000124 bool HasFallThrough : 1;
125 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000126 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000127 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000128 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000129 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000130 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000131 MachineBasicBlock *BB;
132 MachineBasicBlock *TrueBB;
133 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000134 SmallVector<MachineOperand, 4> BrCond;
135 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000136 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000137 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
Kyle Butte1c931b2016-08-10 20:45:56 +0000138 IsBrReversible(false), HasFallThrough(false),
139 IsUnpredicable(false), CannotBeCopied(false),
140 ClobbersPred(false), NonPredSize(0), ExtraCost(0),
141 ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
Craig Topperc0196b12014-04-14 00:51:57 +0000142 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000143 };
144
Bob Wilson59475732010-06-15 18:19:27 +0000145 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000146 /// BBI - Corresponding BBInfo.
147 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000148 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000149 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000150 /// NumDups - Number of instructions that would be duplicated due
151 /// to this if-conversion. (For diamonds, the number of
152 /// identical instructions at the beginnings of both
153 /// paths).
154 /// NumDups2 - For diamonds, the number of identical instructions
155 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000156 struct IfcvtToken {
157 BBInfo &BBI;
158 IfcvtKind Kind;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000159 unsigned NumDups;
160 unsigned NumDups2;
Kyle Butte1c931b2016-08-10 20:45:56 +0000161 bool NeedSubsumption : 1;
162 bool TClobbersPred : 1;
163 bool FClobbersPred : 1;
164 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
165 bool tc = false, bool fc = false)
166 : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
167 TClobbersPred(tc), FClobbersPred(fc) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000168 };
169
170 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
171 /// basic block number.
172 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000173 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000174
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000175 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000176 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000177 const TargetRegisterInfo *TRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000178 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000179 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000180
Juergen Ributzka310034e2013-12-14 06:52:56 +0000181 LivePhysRegs Redefs;
182 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000183
Evan Chengc5adcca2012-06-08 21:53:50 +0000184 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000185 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000186 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000187 std::function<bool(const Function &)> PredicateFtor;
188
Evan Chengf5e53a52007-05-16 02:00:57 +0000189 public:
190 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000191 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000192 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000193 initializeIfConverterPass(*PassRegistry::getPassRegistry());
194 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000195
Craig Topper4584cd52014-03-07 09:26:03 +0000196 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000197 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000198 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000199 MachineFunctionPass::getAnalysisUsage(AU);
200 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000201
Craig Topper4584cd52014-03-07 09:26:03 +0000202 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000203
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000204 MachineFunctionProperties getRequiredProperties() const override {
205 return MachineFunctionProperties().set(
206 MachineFunctionProperties::Property::AllVRegsAllocated);
207 }
208
Evan Chengf5e53a52007-05-16 02:00:57 +0000209 private:
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000210 bool ReverseBranchCondition(BBInfo &BBI) const;
Owen Andersonf31f33e2010-10-01 22:45:50 +0000211 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000212 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000213 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000214 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000215 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000216 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
Kyle Butte1c931b2016-08-10 20:45:56 +0000217 unsigned &Dups1, unsigned &Dups2,
218 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
219 bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
220 unsigned &Dups1, unsigned &Dups2,
221 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000222 void AnalyzeBranches(BBInfo &BBI);
223 void ScanInstructions(BBInfo &BBI,
224 MachineBasicBlock::iterator &Begin,
225 MachineBasicBlock::iterator &End) const;
Kyle Butte1c931b2016-08-10 20:45:56 +0000226 bool RescanInstructions(
227 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
228 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
229 BBInfo &TrueBBI, BBInfo &FalseBBI) const;
Justin Lebar3a7bc572016-02-22 17:51:28 +0000230 void AnalyzeBlock(MachineBasicBlock *MBB,
231 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000232 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Kyle Butte1c931b2016-08-10 20:45:56 +0000233 bool isTriangle = false, bool RevBranch = false,
234 bool hasCommonTail = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000235 void AnalyzeBlocks(MachineFunction &MF,
236 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000237 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000238 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000239 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
240 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Kyle Butte1c931b2016-08-10 20:45:56 +0000241 bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
242 unsigned NumDups1, unsigned NumDups2,
243 bool TClobbersPred, bool FClobbersPred,
244 bool RemoveTrueBranch, bool RemoveFalseBranch,
245 bool MergeAddEdges);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000246 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
247 unsigned NumDups1, unsigned NumDups2);
Kyle Butte1c931b2016-08-10 20:45:56 +0000248 bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
249 unsigned NumDups1, unsigned NumDups2,
250 bool TClobbers, bool FClobbers);
Evan Chengd0e66912007-05-23 07:23:16 +0000251 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000252 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000253 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000254 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000255 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000256 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000257 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000258 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000259
Evan Chengdebf9c52010-11-03 00:45:17 +0000260 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
261 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000262 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000263 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000264 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000265 }
266
Evan Chengdebf9c52010-11-03 00:45:17 +0000267 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
268 unsigned TCycle, unsigned TExtra,
269 MachineBasicBlock &FBB,
270 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000271 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000272 return TCycle > 0 && FCycle > 0 &&
273 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000274 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000275 }
276
Evan Chengbe9859e2007-06-07 02:12:15 +0000277 // blockAlwaysFallThrough - Block ends without a terminator.
278 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000279 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000280 }
281
Evan Cheng3a51c852007-06-16 09:34:52 +0000282 // IfcvtTokenCmp - Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000283 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
284 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000285 int Incr1 = (C1->Kind == ICDiamond)
286 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
287 int Incr2 = (C2->Kind == ICDiamond)
288 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
289 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000290 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000291 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000292 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000293 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000294 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000295 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000296 // Favors diamond over triangle, etc.
297 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
298 return true;
299 else if (C1->Kind == C2->Kind)
300 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
301 }
302 }
303 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000304 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000305 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000306
Evan Chengf5e53a52007-05-16 02:00:57 +0000307 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000308}
Evan Chengf5e53a52007-05-16 02:00:57 +0000309
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000310char &llvm::IfConverterID = IfConverter::ID;
311
Owen Anderson8ac477f2010-10-12 19:48:12 +0000312INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000313INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000314INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000315
Evan Chengf5e53a52007-05-16 02:00:57 +0000316bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000317 if (skipFunction(*MF.getFunction()) ||
318 (PredicateFtor && !PredicateFtor(*MF.getFunction())))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000319 return false;
320
Eric Christopher3d4276f2015-01-27 07:31:29 +0000321 const TargetSubtargetInfo &ST = MF.getSubtarget();
322 TLI = ST.getTargetLowering();
323 TII = ST.getInstrInfo();
324 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000325 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000326 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000327 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000328 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000329
Evan Chengf5e53a52007-05-16 02:00:57 +0000330 if (!TII) return false;
331
Evan Chengc5adcca2012-06-08 21:53:50 +0000332 PreRegAlloc = MRI->isSSA();
333
334 bool BFChange = false;
335 if (!PreRegAlloc) {
336 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000337 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000338 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000339 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000340 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000341
David Greene72e47cd2010-01-04 22:02:01 +0000342 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000343 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000344
345 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000346 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000347 return false;
348 }
David Greene72e47cd2010-01-04 22:02:01 +0000349 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000350
Evan Chengf5e53a52007-05-16 02:00:57 +0000351 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000352 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000353
Justin Lebar3a7bc572016-02-22 17:51:28 +0000354 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000355 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000356 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
357 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
358 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000359 // Do an initial analysis for each basic block and find all the potential
360 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000361 bool Change = false;
362 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000363 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000364 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000365 Tokens.pop_back();
366 BBInfo &BBI = Token->BBI;
367 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000368 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000369 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000370
Evan Cheng4dd31a72007-06-11 22:26:22 +0000371 // If the block has been evicted out of the queue or it has already been
372 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000373 if (BBI.IsDone)
374 BBI.IsEnqueued = false;
375 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000376 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000377
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000378 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000379
Evan Cheng312b7232007-06-04 06:47:22 +0000380 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000381 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000382 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000383 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000384 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000385 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000386 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000387 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
388 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000389 << "): BB#" << BBI.BB->getNumber() << " ("
390 << ((Kind == ICSimpleFalse)
391 ? BBI.FalseBB->getNumber()
392 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000393 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000394 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000395 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000396 if (isFalse) ++NumSimpleFalse;
397 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000398 }
Evan Cheng312b7232007-06-04 06:47:22 +0000399 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000400 }
Evan Chengd0e66912007-05-23 07:23:16 +0000401 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000402 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000403 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000404 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000405 bool isFalse = Kind == ICTriangleFalse;
406 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000407 if (DisableTriangle && !isFalse && !isRev) break;
408 if (DisableTriangleR && !isFalse && isRev) break;
409 if (DisableTriangleF && isFalse && !isRev) break;
410 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000411 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000412 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000413 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000414 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000415 DEBUG(dbgs() << " rev");
416 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000417 << BBI.TrueBB->getNumber() << ",F:"
418 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000419 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000420 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000421 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000422 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000423 if (isRev) ++NumTriangleFRev;
424 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000425 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000426 if (isRev) ++NumTriangleRev;
427 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000428 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000429 }
Evan Chengd0e66912007-05-23 07:23:16 +0000430 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000431 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000432 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000433 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000434 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000435 << BBI.TrueBB->getNumber() << ",F:"
436 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000437 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000438 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000439 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000440 break;
441 }
Kyle Butte1c931b2016-08-10 20:45:56 +0000442 case ICForkedDiamond: {
443 if (DisableForkedDiamond) break;
444 DEBUG(dbgs() << "Ifcvt (Forked Diamond): BB#"
445 << BBI.BB->getNumber() << " (T:"
446 << BBI.TrueBB->getNumber() << ",F:"
447 << BBI.FalseBB->getNumber() << ") ");
448 RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
449 Token->TClobbersPred,
450 Token->FClobbersPred);
451 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
452 if (RetVal) ++NumForkedDiamonds;
453 break;
454 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000455 }
456
Evan Cheng312b7232007-06-04 06:47:22 +0000457 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000458
Evan Cheng92fb5452007-06-15 07:36:12 +0000459 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
460 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
461 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000462 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000463 }
Evan Chengd0e66912007-05-23 07:23:16 +0000464
Evan Chengd0e66912007-05-23 07:23:16 +0000465 if (!Change)
466 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000467 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000468 }
Evan Cheng478b8052007-05-18 01:55:58 +0000469
Evan Cheng3a51c852007-06-16 09:34:52 +0000470 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000471 BBAnalysis.clear();
472
Evan Chengcf9e8a92010-06-18 22:17:13 +0000473 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000474 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000475 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000476 getAnalysisIfAvailable<MachineModuleInfo>());
477 }
478
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000479 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000480 return MadeChange;
481}
482
Evan Cheng3a51c852007-06-16 09:34:52 +0000483/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
484/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000485static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000486 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000487 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
488 E = BB->succ_end(); SI != E; ++SI) {
489 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000490 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000491 return SuccBB;
492 }
Craig Topperc0196b12014-04-14 00:51:57 +0000493 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000494}
495
Evan Cheng3a51c852007-06-16 09:34:52 +0000496/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000497/// branch. Swap block's 'true' and 'false' successors.
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000498bool IfConverter::ReverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000499 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000500 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
501 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000502 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000503 std::swap(BBI.TrueBB, BBI.FalseBB);
504 return true;
505 }
506 return false;
507}
508
Evan Cheng2117d1f2007-06-09 01:03:43 +0000509/// getNextBlock - Returns the next block in the function blocks ordering. If
510/// it is the end, returns NULL.
511static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000512 MachineFunction::iterator I = BB->getIterator();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000513 MachineFunction::iterator E = BB->getParent()->end();
514 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000515 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000516 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000517}
518
Evan Cheng7783f822007-06-08 09:36:04 +0000519/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000520/// predecessor) forms a valid simple shape for ifcvt. It also returns the
521/// number of instructions that the ifcvt would need to duplicate if performed
522/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000523bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000524 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000525 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000526 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000527 return false;
528
Evan Chenga955c022007-06-19 21:45:13 +0000529 if (TrueBBI.IsBrAnalyzable)
530 return false;
531
Evan Cheng23402fc2007-06-15 21:18:05 +0000532 if (TrueBBI.BB->pred_size() > 1) {
533 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000534 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000535 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000536 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000537 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000538 }
539
Evan Chenga955c022007-06-19 21:45:13 +0000540 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000541}
542
Evan Cheng7783f822007-06-08 09:36:04 +0000543/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000544/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000545/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000546/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000547/// returns the number of instructions that the ifcvt would need to duplicate
548/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000549bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000550 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000551 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000552 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000553 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000554 return false;
555
Evan Cheng23402fc2007-06-15 21:18:05 +0000556 if (TrueBBI.BB->pred_size() > 1) {
557 if (TrueBBI.CannotBeCopied)
558 return false;
559
Evan Cheng92fb5452007-06-15 07:36:12 +0000560 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000561 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000562 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000563 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000564 --Size;
565 else {
566 MachineBasicBlock *FExit = FalseBranch
567 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
568 if (FExit)
569 // Require a conditional branch
570 ++Size;
571 }
572 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000573 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000574 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000575 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000576 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000577
Evan Cheng7783f822007-06-08 09:36:04 +0000578 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
579 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000580 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000581 if (++I == TrueBBI.BB->getParent()->end())
582 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000583 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000584 }
Evan Cheng7783f822007-06-08 09:36:04 +0000585 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000586}
587
Kyle Buttfe916822016-08-06 01:52:31 +0000588/// Increment It until it points to a non-debug instruction or to End.
589/// @param It Iterator to increment
590/// @param End Iterator that points to end. Will be compared to It
591/// @returns true if It == End, false otherwise.
592static inline bool skipDebugInstructionsForward(
593 MachineBasicBlock::iterator &It,
594 MachineBasicBlock::iterator &End) {
595 while (It != End && It->isDebugValue())
596 It++;
597 return It == End;
598}
599
600/// Decrement It until it points to a non-debug instruction or to Begin.
601/// @param It Iterator to decrement.
David Majnemer70c93fa2016-08-06 08:37:12 +0000602/// @param Begin Iterator that points to beginning. Will be compared to It
Kyle Buttfe916822016-08-06 01:52:31 +0000603/// @returns true if It == Begin, false otherwise.
604static inline bool skipDebugInstructionsBackward(
605 MachineBasicBlock::iterator &It,
606 MachineBasicBlock::iterator &Begin) {
607 while (It != Begin && It->isDebugValue())
608 It--;
609 return It == Begin;
610}
611
Kyle Butt4f0e2872016-08-06 01:52:33 +0000612/// Count duplicated instructions and move the iterators to show where they
613/// are.
614/// @param TIB True Iterator Begin
615/// @param FIB False Iterator Begin
616/// These two iterators initially point to the first instruction of the two
617/// blocks, and finally point to the first non-shared instruction.
618/// @param TIE True Iterator End
619/// @param FIE False Iterator End
620/// These two iterators initially point to End() for the two blocks() and
621/// finally point to the first shared instruction in the tail.
622/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
623/// two blocks.
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000624static void countDuplicatedInstructions(
625 MachineBasicBlock::iterator &TIB,
626 MachineBasicBlock::iterator &FIB,
627 MachineBasicBlock::iterator &TIE,
628 MachineBasicBlock::iterator &FIE,
629 unsigned &Dups1, unsigned &Dups2,
630 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
631 bool SkipConditionalBranches) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000632
Bob Wilsone1961fe2010-10-26 00:02:24 +0000633 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000634 // Skip dbg_value instructions. These do not count.
Kyle Buttfe916822016-08-06 01:52:31 +0000635 if(skipDebugInstructionsForward(TIB, TIE))
636 break;
637 if(skipDebugInstructionsForward(FIB, FIE))
638 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000639 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000640 break;
641 ++Dups1;
642 ++TIB;
643 ++FIB;
644 }
645
646 // Now, in preparation for counting duplicate instructions at the ends of the
647 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000648 // If both blocks are returning don't skip the branches, since they will
649 // likely be both identical return instructions. In such cases the return
650 // can be left unpredicated.
651 // Check for already containing all of the block.
652 if (TIB == TIE || FIB == FIE)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000653 return;
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000654 --TIE;
655 --FIE;
Kyle Butte1c931b2016-08-10 20:45:56 +0000656 // Upon exit TIE and FIE will both point at the last non-shared instruction,
657 // they need to be moved forward to point past the last non-shared
658 // instruction.
659 auto IncrementEndIteratorsOnExit = make_scope_exit([&]() {
660 ++TIE; ++FIE;
661 });
662
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000663 if (!TBB.succ_empty() || !FBB.succ_empty()) {
664 if (SkipConditionalBranches) {
665 while (TIE != TIB && TIE->isBranch())
666 --TIE;
667 while (FIE != FIB && FIE->isBranch())
668 --FIE;
669 } else {
670 while (TIE != TIB && TIE->isUnconditionalBranch())
671 --TIE;
672 while (FIE != FIB && FIE->isUnconditionalBranch())
673 --FIE;
674 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000675 }
676
677 // If Dups1 includes all of a block, then don't count duplicate
678 // instructions at the end of the blocks.
Nico Weber99ceee82016-08-07 20:18:04 +0000679 if (TIB == TIE || FIB == FIE)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000680 return;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000681
682 // Count duplicate instructions at the ends of the blocks.
683 while (TIE != TIB && FIE != FIB) {
684 // Skip dbg_value instructions. These do not count.
Kyle Buttfe916822016-08-06 01:52:31 +0000685 if (skipDebugInstructionsBackward(TIE, TIB))
686 break;
687 if (skipDebugInstructionsBackward(FIE, FIB))
688 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000689 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000690 break;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000691 // If we are trying to make sure the conditional branches are the same, we
692 // still don't want to count them.
693 if (SkipConditionalBranches || !TIE->isBranch())
694 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000695 --TIE;
696 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000697 }
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000698}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000699
Kyle Butte1c931b2016-08-10 20:45:56 +0000700/// RescanInstructions - Run ScanInstructions on a pair of blocks.
701/// @param TIB - True Iterator Begin, points to first non-shared instruction
702/// @param FIB - False Iterator Begin, points to first non-shared instruction
703/// @param TIE - True Iterator End, points past last non-shared instruction
704/// @param FIE - False Iterator End, points past last non-shared instruction
705/// @param TrueBBI - BBInfo to update for the true block.
706/// @param FalseBBI - BBInfo to update for the false block.
707/// @returns - false if either block cannot be predicated or if both blocks end
708/// with a predicate-clobbering instruction.
709bool IfConverter::RescanInstructions(
710 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
711 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
712 BBInfo &TrueBBI, BBInfo &FalseBBI) const {
713 ScanInstructions(TrueBBI, TIB, TIE);
714 if (TrueBBI.IsUnpredicable)
715 return false;
716 ScanInstructions(FalseBBI, FIB, FIE);
717 if (FalseBBI.IsUnpredicable)
718 return false;
719 if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
720 return false;
721 return true;
722}
723
724/// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
725/// with their common predecessor) form a diamond if a common tail block is
726/// extracted.
727/// While not strictly a diamond, this pattern would form a diamond if
728/// tail-merging had merged the shared tails.
729/// EBB
730/// _/ \_
731/// | |
732/// TBB FBB
733/// / \ / \
734/// FalseBB TrueBB FalseBB
735/// Currently only handles analyzable branches.
736/// Specifically excludes actual diamonds to avoid overlap.
737bool IfConverter::ValidForkedDiamond(
738 BBInfo &TrueBBI, BBInfo &FalseBBI,
739 unsigned &Dups1, unsigned &Dups2,
740 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
741 Dups1 = Dups2 = 0;
742 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
743 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
744 return false;
745
746 if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
747 return false;
748 // Don't IfConvert blocks that can't be folded into their predecessor.
749 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
750 return false;
751
752 // This function is specifically looking for conditional tails, as
753 // unconditional tails are already handled by the standard diamond case.
754 if (TrueBBI.BrCond.size() == 0 ||
755 FalseBBI.BrCond.size() == 0)
756 return false;
757
758 MachineBasicBlock *TT = TrueBBI.TrueBB;
759 MachineBasicBlock *TF = TrueBBI.FalseBB;
760 MachineBasicBlock *FT = FalseBBI.TrueBB;
761 MachineBasicBlock *FF = FalseBBI.FalseBB;
762
763 if (!TT)
764 TT = getNextBlock(TrueBBI.BB);
765 if (!TF)
766 TF = getNextBlock(TrueBBI.BB);
767 if (!FT)
768 FT = getNextBlock(FalseBBI.BB);
769 if (!FF)
770 FF = getNextBlock(FalseBBI.BB);
771
772 if (!TT || !TF)
773 return false;
774
775 // Check successors. If they don't match, bail.
776 if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
777 return false;
778
779 bool FalseReversed = false;
780 if (TF == FT && TT == FF) {
781 // If the branches are opposing, but we can't reverse, don't do it.
782 if (!FalseBBI.IsBrReversible)
783 return false;
784 FalseReversed = true;
785 ReverseBranchCondition(FalseBBI);
786 }
787 auto UnReverseOnExit = make_scope_exit([&]() {
788 if (FalseReversed)
789 ReverseBranchCondition(FalseBBI);
790 });
791
792 // Count duplicate instructions at the beginning of the true and false blocks.
793 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
794 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
795 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
796 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
797 countDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
798 *TrueBBI.BB, *FalseBBI.BB,
799 /* SkipConditionalBranches */ false);
800
801 TrueBBICalc.BB = TrueBBI.BB;
802 FalseBBICalc.BB = FalseBBI.BB;
803 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
804 return false;
805 // The size is used to decide whether to if-convert, and the shared portions
806 // are subtracted off. Because of the subtraction, we just use the size that
807 // was calculated by the original ScanInstructions, as it is correct.
808 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
809 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
810 return true;
811}
812
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000813/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
814/// with their common predecessor) forms a valid diamond shape for ifcvt.
Kyle Butte1c931b2016-08-10 20:45:56 +0000815bool IfConverter::ValidDiamond(
816 BBInfo &TrueBBI, BBInfo &FalseBBI,
817 unsigned &Dups1, unsigned &Dups2,
818 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000819 Dups1 = Dups2 = 0;
820 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
821 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
822 return false;
823
824 MachineBasicBlock *TT = TrueBBI.TrueBB;
825 MachineBasicBlock *FT = FalseBBI.TrueBB;
826
827 if (!TT && blockAlwaysFallThrough(TrueBBI))
828 TT = getNextBlock(TrueBBI.BB);
829 if (!FT && blockAlwaysFallThrough(FalseBBI))
830 FT = getNextBlock(FalseBBI.BB);
831 if (TT != FT)
832 return false;
833 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
834 return false;
835 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
836 return false;
837
838 // FIXME: Allow true block to have an early exit?
Kyle Butte1c931b2016-08-10 20:45:56 +0000839 if (TrueBBI.FalseBB || FalseBBI.FalseBB)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000840 return false;
841
842 // Count duplicate instructions at the beginning and end of the true and
843 // false blocks.
844 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
845 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
846 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
847 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
848 countDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
849 *TrueBBI.BB, *FalseBBI.BB,
850 /* SkipConditionalBranches */ true);
Kyle Butte1c931b2016-08-10 20:45:56 +0000851
852 TrueBBICalc.BB = TrueBBI.BB;
853 FalseBBICalc.BB = FalseBBI.BB;
854 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
855 return false;
856 // The size is used to decide whether to if-convert, and the shared portions
857 // are subtracted off. Because of the subtraction, we just use the size that
858 // was calculated by the original ScanInstructions, as it is correct.
859 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
860 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000861 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000862}
863
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000864/// AnalyzeBranches - Look at the branches at the end of a block to determine if
865/// the block is predicable.
866void IfConverter::AnalyzeBranches(BBInfo &BBI) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000867 if (BBI.IsDone)
868 return;
869
Craig Topperc0196b12014-04-14 00:51:57 +0000870 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000871 BBI.BrCond.clear();
872 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000873 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Kyle Butte1c931b2016-08-10 20:45:56 +0000874 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
875 BBI.IsBrReversible = (RevCond.size() == 0) ||
876 !TII->ReverseBranchCondition(RevCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000877 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000878
879 if (BBI.BrCond.size()) {
880 // No false branch. This BB must end with a conditional branch and a
881 // fallthrough.
882 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000883 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000884 if (!BBI.FalseBB) {
885 // Malformed bcc? True and false blocks are the same?
886 BBI.IsUnpredicable = true;
Evan Chengb9bff582009-06-15 21:24:34 +0000887 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000888 }
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000889}
Evan Cheng4dd31a72007-06-11 22:26:22 +0000890
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000891/// ScanInstructions - Scan all the instructions in the block to determine if
892/// the block is predicable. In most cases, that means all the instructions
893/// in the block are isPredicable(). Also checks if the block contains any
894/// instruction which can clobber a predicate (e.g. condition code register).
895/// If so, the block is not predicable unless it's the last instruction.
896void IfConverter::ScanInstructions(BBInfo &BBI,
897 MachineBasicBlock::iterator &Begin,
898 MachineBasicBlock::iterator &End) const {
899 if (BBI.IsDone || BBI.IsUnpredicable)
900 return;
901
902 bool AlreadyPredicated = !BBI.Predicate.empty();
903
Evan Cheng4dd31a72007-06-11 22:26:22 +0000904 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000905 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000906 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000907 BBI.ClobbersPred = false;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000908 for (; Begin != End; ++Begin) {
909 auto &MI = *Begin;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000910 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000911 continue;
912
Justin Lebar7dba2e02016-04-15 01:38:41 +0000913 // It's unsafe to duplicate convergent instructions in this context, so set
914 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
915 // following CFG, which is subject to our "simple" transformation.
916 //
917 // BB0 // if (c1) goto BB1; else goto BB2;
918 // / \
919 // BB1 |
920 // | BB2 // if (c2) goto TBB; else goto FBB;
921 // | / |
922 // | / |
923 // TBB |
924 // | |
925 // | FBB
926 // |
927 // exit
928 //
929 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
930 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
931 // TBB contains a convergent instruction. This is safe iff doing so does
932 // not add a control-flow dependency to the convergent instruction -- i.e.,
933 // it's safe iff the set of control flows that leads us to the convergent
934 // instruction does not get smaller after the transformation.
935 //
936 // Originally we executed TBB if c1 || c2. After the transformation, there
937 // are two copies of TBB's instructions. We get to the first if c1, and we
938 // get to the second if !c1 && c2.
939 //
940 // There are clearly fewer ways to satisfy the condition "c1" than
941 // "c1 || c2". Since we've shrunk the set of control flows which lead to
942 // our convergent instruction, the transformation is unsafe.
943 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000944 BBI.CannotBeCopied = true;
945
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000946 bool isPredicated = TII->isPredicated(MI);
947 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000948
Joey Goulya5153cb2013-09-09 14:21:49 +0000949 // A conditional branch is not predicable, but it may be eliminated.
950 if (isCondBr)
951 continue;
952
953 if (!isPredicated) {
954 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000955 unsigned ExtraPredCost = TII->getPredicationCost(MI);
956 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000957 if (NumCycles > 1)
958 BBI.ExtraCost += NumCycles-1;
959 BBI.ExtraCost2 += ExtraPredCost;
960 } else if (!AlreadyPredicated) {
961 // FIXME: This instruction is already predicated before the
962 // if-conversion pass. It's probably something like a conditional move.
963 // Mark this block unpredicable for now.
964 BBI.IsUnpredicable = true;
965 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000966 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000967
968 if (BBI.ClobbersPred && !isPredicated) {
969 // Predicate modification instruction should end the block (except for
970 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000971 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000972 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000973 BBI.IsUnpredicable = true;
974 return;
975 }
976
Evan Chengfbc73092007-07-10 17:50:43 +0000977 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
978 // still potentially predicable.
979 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000980 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000981 BBI.ClobbersPred = true;
982
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000983 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000984 BBI.IsUnpredicable = true;
985 return;
986 }
987 }
988}
989
990/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
991/// predicated by the specified predicate.
Kyle Butte1c931b2016-08-10 20:45:56 +0000992/// @param BBI BBInfo for the block to check
993/// @param Pred Predicate array for the branch that leads to BBI
994/// @param isTriangle true if the Analysis is for a triangle
995/// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
996/// case
997/// @param hasCommonTail true if BBI shares a tail with a sibling block that
998/// contains any instruction that would make the block unpredicable.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000999bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001000 SmallVectorImpl<MachineOperand> &Pred,
Kyle Butte1c931b2016-08-10 20:45:56 +00001001 bool isTriangle, bool RevBranch,
1002 bool hasCommonTail) {
Evan Cheng3a51c852007-06-16 09:34:52 +00001003 // If the block is dead or unpredicable, then it cannot be predicated.
Kyle Butte1c931b2016-08-10 20:45:56 +00001004 // Two blocks may share a common unpredicable tail, but this doesn't prevent
1005 // them from being if-converted. The non-shared portion is assumed to have
1006 // been checked
1007 if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001008 return false;
1009
Ahmed Bougacha7173b662015-03-21 01:23:15 +00001010 // If it is already predicated but we couldn't analyze its terminator, the
1011 // latter might fallthrough, but we can't determine where to.
1012 // Conservatively avoid if-converting again.
1013 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1014 return false;
1015
Quentin Colombetbdab2272013-07-24 20:20:37 +00001016 // If it is already predicated, check if the new predicate subsumes
1017 // its predicate.
1018 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001019 return false;
1020
Kyle Butte1c931b2016-08-10 20:45:56 +00001021 if (!hasCommonTail && BBI.BrCond.size()) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001022 if (!isTriangle)
1023 return false;
1024
Bob Wilson2371f4f2009-05-13 23:25:24 +00001025 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +00001026 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1027 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +00001028 if (RevBranch) {
1029 if (TII->ReverseBranchCondition(Cond))
1030 return false;
1031 }
1032 if (TII->ReverseBranchCondition(RevPred) ||
1033 !TII->SubsumesPredicate(Cond, RevPred))
1034 return false;
1035 }
1036
1037 return true;
1038}
1039
Evan Cheng7783f822007-06-08 09:36:04 +00001040/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +00001041/// the specified block. Record its successors and whether it looks like an
1042/// if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001043void IfConverter::AnalyzeBlock(
1044 MachineBasicBlock *MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001045 struct BBState {
1046 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
1047 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +00001048
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001049 /// This flag is true if MBB's successors have been analyzed.
1050 bool SuccsAnalyzed;
1051 };
Evan Cheng0f745da2007-05-18 00:20:58 +00001052
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001053 // Push MBB to the stack.
1054 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001055
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001056 while (!BBStack.empty()) {
1057 BBState &State = BBStack.back();
1058 MachineBasicBlock *BB = State.MBB;
1059 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +00001060
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001061 if (!State.SuccsAnalyzed) {
1062 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1063 BBStack.pop_back();
1064 continue;
1065 }
Evan Cheng9030b982007-06-06 10:16:17 +00001066
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001067 BBI.BB = BB;
1068 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +00001069
Kyle Butt54bf3ce2016-08-06 01:52:34 +00001070 AnalyzeBranches(BBI);
1071 MachineBasicBlock::iterator Begin = BBI.BB->begin();
1072 MachineBasicBlock::iterator End = BBI.BB->end();
1073 ScanInstructions(BBI, Begin, End);
Evan Chengb9bff582009-06-15 21:24:34 +00001074
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001075 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1076 // not considered for ifcvt anymore.
1077 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1078 BBI.IsBeingAnalyzed = false;
1079 BBI.IsAnalyzed = true;
1080 BBStack.pop_back();
1081 continue;
1082 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001083
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001084 // Do not ifcvt if either path is a back edge to the entry block.
1085 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1086 BBI.IsBeingAnalyzed = false;
1087 BBI.IsAnalyzed = true;
1088 BBStack.pop_back();
1089 continue;
1090 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001091
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001092 // Do not ifcvt if true and false fallthrough blocks are the same.
1093 if (!BBI.FalseBB) {
1094 BBI.IsBeingAnalyzed = false;
1095 BBI.IsAnalyzed = true;
1096 BBStack.pop_back();
1097 continue;
1098 }
Evan Cheng7783f822007-06-08 09:36:04 +00001099
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001100 // Push the False and True blocks to the stack.
1101 State.SuccsAnalyzed = true;
1102 BBStack.push_back(BBI.FalseBB);
1103 BBStack.push_back(BBI.TrueBB);
1104 continue;
1105 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +00001106
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001107 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1108 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +00001109
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001110 if (TrueBBI.IsDone && FalseBBI.IsDone) {
1111 BBI.IsBeingAnalyzed = false;
1112 BBI.IsAnalyzed = true;
1113 BBStack.pop_back();
1114 continue;
1115 }
1116
1117 SmallVector<MachineOperand, 4>
1118 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1119 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
1120
1121 unsigned Dups = 0;
1122 unsigned Dups2 = 0;
1123 bool TNeedSub = !TrueBBI.Predicate.empty();
1124 bool FNeedSub = !FalseBBI.Predicate.empty();
1125 bool Enqueued = false;
1126
1127 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1128
Kyle Butte1c931b2016-08-10 20:45:56 +00001129 if (CanRevCond) {
1130 BBInfo TrueBBICalc, FalseBBICalc;
1131 auto feasibleDiamond = [&]() {
1132 return (
1133 MeetIfcvtSizeLimit(
1134 *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1135 TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1136 *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1137 FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1138 Prediction) &&
1139 FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1140 /* IsTriangle */ false, /* RevCond */ false,
1141 /* hasCommonTail */ true) &&
1142 FeasibilityAnalysis(FalseBBI, RevCond,
1143 /* IsTriangle */ false, /* RevCond */ false,
1144 /* hasCommonTail */ true));
1145 };
1146
1147 if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1148 TrueBBICalc, FalseBBICalc)) {
1149 if (feasibleDiamond()) {
1150 // Diamond:
1151 // EBB
1152 // / \_
1153 // | |
1154 // TBB FBB
1155 // \ /
1156 // TailBB
1157 // Note TailBB can be empty.
1158 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1159 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
1160 Enqueued = true;
1161 }
1162 } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1163 TrueBBICalc, FalseBBICalc)) {
1164 if (feasibleDiamond()) {
1165 // ForkedDiamond:
1166 // if TBB and FBB have a common tail that includes their conditional
1167 // branch instructions, then we can If Convert this pattern.
1168 // EBB
1169 // _/ \_
1170 // | |
1171 // TBB FBB
1172 // / \ / \
1173 // FalseBB TrueBB FalseBB
1174 //
1175 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1176 BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1177 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1178 Enqueued = true;
1179 }
1180 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001181 }
1182
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001183 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1184 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1185 TrueBBI.ExtraCost2, Prediction) &&
1186 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1187 // Triangle:
1188 // EBB
1189 // | \_
1190 // | |
1191 // | TBB
1192 // | /
1193 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001194 Tokens.push_back(
1195 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001196 Enqueued = true;
1197 }
1198
1199 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1200 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1201 TrueBBI.ExtraCost2, Prediction) &&
1202 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001203 Tokens.push_back(
1204 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001205 Enqueued = true;
1206 }
1207
1208 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1209 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1210 TrueBBI.ExtraCost2, Prediction) &&
1211 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1212 // Simple (split, no rejoin):
1213 // EBB
1214 // | \_
1215 // | |
1216 // | TBB---> exit
1217 // |
1218 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001219 Tokens.push_back(
1220 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001221 Enqueued = true;
1222 }
1223
1224 if (CanRevCond) {
1225 // Try the other path...
1226 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1227 Prediction.getCompl()) &&
1228 MeetIfcvtSizeLimit(*FalseBBI.BB,
1229 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1230 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1231 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001232 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1233 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001234 Enqueued = true;
1235 }
1236
1237 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1238 Prediction.getCompl()) &&
1239 MeetIfcvtSizeLimit(*FalseBBI.BB,
1240 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +00001241 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +00001242 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001243 Tokens.push_back(
1244 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001245 Enqueued = true;
1246 }
1247
1248 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1249 MeetIfcvtSizeLimit(*FalseBBI.BB,
1250 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1251 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1252 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001253 Tokens.push_back(
1254 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001255 Enqueued = true;
1256 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001257 }
1258
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001259 BBI.IsEnqueued = Enqueued;
1260 BBI.IsBeingAnalyzed = false;
1261 BBI.IsAnalyzed = true;
1262 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001263 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001264}
1265
Evan Cheng905a8f42007-05-30 19:49:19 +00001266/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +00001267/// candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001268void IfConverter::AnalyzeBlocks(
1269 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001270 for (auto &BB : MF)
1271 AnalyzeBlock(&BB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001272
Evan Cheng20e05992007-06-01 00:12:12 +00001273 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +00001274 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001275}
1276
Evan Cheng288f1542007-06-08 22:01:07 +00001277/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
1278/// that all the intervening blocks are empty (given BB can fall through to its
1279/// next block).
1280static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001281 MachineFunction::iterator PI = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001282 MachineFunction::iterator I = std::next(PI);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001283 MachineFunction::iterator TI = ToBB->getIterator();
Evan Cheng2c1acd62007-06-05 07:05:25 +00001284 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001285 while (I != TI) {
1286 // Check isSuccessor to avoid case where the next block is empty, but
1287 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001288 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001289 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001290 PI = I++;
1291 }
Evan Cheng312b7232007-06-04 06:47:22 +00001292 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001293}
1294
Evan Cheng51eb2c32007-06-18 08:37:25 +00001295/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
1296/// to determine if it can be if-converted. If predecessor is already enqueued,
1297/// dequeue it!
1298void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001299 for (const auto &Predecessor : BB->predecessors()) {
1300 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +00001301 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001302 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001303 PBBI.IsAnalyzed = false;
1304 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001305 }
1306}
1307
Evan Chengc2237ce2007-05-29 22:31:16 +00001308/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
1309///
1310static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
1311 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001312 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001313 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +00001314 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001315}
1316
Evan Cheng288f1542007-06-08 22:01:07 +00001317/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1318/// successors.
1319void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001320 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001321 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001322 if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
Evan Cheng0598b2d2007-06-18 22:44:57 +00001323 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001324}
1325
Matthias Braund616ccc2013-10-11 19:04:37 +00001326/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Jonas Paulsson196986c2016-08-03 05:46:35 +00001327/// values defined in MI which are also live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001328static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Jonas Paulsson196986c2016-08-03 05:46:35 +00001329 const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1330 ->getSubtarget().getRegisterInfo();
1331
1332 // Before stepping forward past MI, remember which regs were live
1333 // before MI. This is needed to set the Undef flag only when reg is
1334 // dead.
1335 SparseSet<unsigned> LiveBeforeMI;
1336 LiveBeforeMI.setUniverse(TRI->getNumRegs());
1337 for (auto &Reg : Redefs)
1338 LiveBeforeMI.insert(Reg);
1339
Pete Cooper7605e372015-05-05 20:14:22 +00001340 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001341 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001342
Pete Cooper7605e372015-05-05 20:14:22 +00001343 // Now add the implicit uses for each of the clobbered values.
1344 for (auto Reg : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001345 // FIXME: Const cast here is nasty, but better than making StepForward
1346 // take a mutable instruction instead of const.
Pete Cooper27483912015-05-06 22:51:04 +00001347 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1348 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001349 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001350 if (Op.isRegMask()) {
1351 // First handle regmasks. They clobber any entries in the mask which
1352 // means that we need a def for those registers.
Jonas Paulsson196986c2016-08-03 05:46:35 +00001353 if (LiveBeforeMI.count(Reg.first))
1354 MIB.addReg(Reg.first, RegState::Implicit);
Pete Cooperce9ad752015-05-05 22:09:41 +00001355
1356 // We also need to add an implicit def of this register for the later
1357 // use to read from.
1358 // For the register allocator to have allocated a register clobbered
1359 // by the call which is used later, it must be the case that
1360 // the call doesn't return.
1361 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1362 continue;
1363 }
1364 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001365 if (Op.isDead()) {
1366 // If we found a dead def, but it needs to be live, then remove the dead
1367 // flag.
1368 if (Redefs.contains(Op.getReg()))
1369 Op.setIsDead(false);
1370 }
Jonas Paulsson196986c2016-08-03 05:46:35 +00001371 if (LiveBeforeMI.count(Reg.first))
1372 MIB.addReg(Reg.first, RegState::Implicit);
Matthias Braund616ccc2013-10-11 19:04:37 +00001373 }
1374}
1375
1376/**
1377 * Remove kill flags from operands with a registers in the @p DontKill set.
1378 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001379static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001380 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001381 if (!O->isReg() || !O->isKill())
1382 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001383 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001384 O->setIsKill(false);
1385 }
1386}
1387
1388/**
1389 * Walks a range of machine instructions and removes kill flags for registers
1390 * in the @p DontKill set.
1391 */
1392static void RemoveKills(MachineBasicBlock::iterator I,
1393 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001394 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001395 const MCRegisterInfo &MCRI) {
1396 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001397 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001398}
1399
Evan Cheng312b7232007-06-04 06:47:22 +00001400/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001401///
Evan Cheng3a51c852007-06-16 09:34:52 +00001402bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001403 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1404 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1405 BBInfo *CvtBBI = &TrueBBI;
1406 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001407
Owen Anderson4f6bf042008-08-14 22:49:33 +00001408 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001409 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001410 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001411
Evan Cheng51eb2c32007-06-18 08:37:25 +00001412 if (CvtBBI->IsDone ||
1413 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001414 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001415 BBI.IsAnalyzed = false;
1416 CvtBBI->IsAnalyzed = false;
1417 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001418 }
Evan Chengd0e66912007-05-23 07:23:16 +00001419
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001420 if (CvtBBI->BB->hasAddressTaken())
1421 // Conservatively abort if-conversion if BB's address is taken.
1422 return false;
1423
Evan Cheng3a51c852007-06-16 09:34:52 +00001424 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001425 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001426 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001427
Bob Wilson45814342010-06-19 05:33:57 +00001428 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001429 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001430 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001431 Redefs.addLiveIns(*CvtBBI->BB);
1432 Redefs.addLiveIns(*NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001433
1434 // Compute a set of registers which must not be killed by instructions in
1435 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001436 DontKill.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001437 DontKill.addLiveIns(*NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001438
Evan Cheng92fb5452007-06-15 07:36:12 +00001439 if (CvtBBI->BB->pred_size() > 1) {
1440 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001441 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001442 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001443 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001444
1445 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1446 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001447 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001448 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001449 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001450 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001451
Evan Cheng92fb5452007-06-15 07:36:12 +00001452 // Merge converted block into entry block.
1453 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1454 MergeBlocks(BBI, *CvtBBI);
1455 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001456
Evan Chenge4ec9182007-06-06 02:08:52 +00001457 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001458 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001459 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001460 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001461 // Now ifcvt'd block will look like this:
1462 // BB:
1463 // ...
1464 // t, f = cmp
1465 // if t op
1466 // b BBf
1467 //
1468 // We cannot further ifcvt this block because the unconditional branch
1469 // will have to be predicated on the new condition, that will not be
1470 // available if cmp executes.
1471 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001472 }
Evan Chenge26c0912007-05-21 22:22:58 +00001473
Evan Cheng288f1542007-06-08 22:01:07 +00001474 RemoveExtraEdges(BBI);
1475
Evan Chengd0e66912007-05-23 07:23:16 +00001476 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001477 if (!IterIfcvt)
1478 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001479 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001480 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001481
1482 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001483 return true;
1484}
1485
Evan Chengaf716102007-05-16 21:54:37 +00001486/// IfConvertTriangle - If convert a triangle sub-CFG.
1487///
Evan Cheng3a51c852007-06-16 09:34:52 +00001488bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001489 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001490 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1491 BBInfo *CvtBBI = &TrueBBI;
1492 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001493 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001494
Owen Anderson4f6bf042008-08-14 22:49:33 +00001495 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001496 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001497 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001498
Evan Cheng51eb2c32007-06-18 08:37:25 +00001499 if (CvtBBI->IsDone ||
1500 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001501 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001502 BBI.IsAnalyzed = false;
1503 CvtBBI->IsAnalyzed = false;
1504 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001505 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001506
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001507 if (CvtBBI->BB->hasAddressTaken())
1508 // Conservatively abort if-conversion if BB's address is taken.
1509 return false;
1510
Evan Cheng3a51c852007-06-16 09:34:52 +00001511 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001512 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001513 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001514
Evan Cheng3a51c852007-06-16 09:34:52 +00001515 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001516 if (ReverseBranchCondition(*CvtBBI)) {
1517 // BB has been changed, modify its predecessors (except for this
1518 // one) so they don't get ifcvt'ed based on bad intel.
1519 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1520 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1521 MachineBasicBlock *PBB = *PI;
1522 if (PBB == BBI.BB)
1523 continue;
1524 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1525 if (PBBI.IsEnqueued) {
1526 PBBI.IsAnalyzed = false;
1527 PBBI.IsEnqueued = false;
1528 }
Evan Chengadd97762007-06-14 23:34:09 +00001529 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001530 }
1531 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001532
Bob Wilson45814342010-06-19 05:33:57 +00001533 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001534 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001535 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001536 Redefs.addLiveIns(*CvtBBI->BB);
1537 Redefs.addLiveIns(*NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001538
Andrew Trick276dd452013-10-14 20:45:17 +00001539 DontKill.clear();
1540
Craig Topperc0196b12014-04-14 00:51:57 +00001541 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001542 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001543
Manman Renb6819182014-01-29 23:18:47 +00001544 if (HasEarlyExit) {
Cong Houd97c1002015-12-01 05:29:22 +00001545 // Get probabilities before modifying CvtBBI->BB and BBI.BB.
1546 CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB);
1547 CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB);
1548 BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB);
1549 BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001550 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001551
Bob Wilson1e5da552010-06-29 00:55:23 +00001552 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001553 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001554 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001555 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001556 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001557
1558 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1559 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001560 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001561 } else {
1562 // Predicate the 'true' block after removing its branch.
1563 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001564 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001565
Evan Cheng0598b2d2007-06-18 22:44:57 +00001566 // Now merge the entry of the triangle with the true block.
1567 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001568 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001569 }
1570
Evan Cheng312b7232007-06-04 06:47:22 +00001571 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001572 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001573 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1574 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001575 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001576 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001577
Cong Houd97c1002015-12-01 05:29:22 +00001578 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1579 // NewNext = New_Prob(BBI.BB, NextBBI->BB) =
1580 // Prob(BBI.BB, NextBBI->BB) +
1581 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB)
1582 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1583 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB)
1584 auto NewTrueBB = getNextBlock(BBI.BB);
1585 auto NewNext = BBNext + BBCvt * CvtNext;
1586 auto NewTrueBBIter =
1587 std::find(BBI.BB->succ_begin(), BBI.BB->succ_end(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001588 if (NewTrueBBIter != BBI.BB->succ_end())
1589 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001590
1591 auto NewFalse = BBCvt * CvtFalse;
1592 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1593 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001594 }
Evan Cheng7783f822007-06-08 09:36:04 +00001595
1596 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001597 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001598 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001599 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001600 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001601 if (!isFallThrough) {
1602 // Only merge them if the true block does not fallthrough to the false
1603 // block. By not merging them, we make it possible to iteratively
1604 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001605 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001606 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1607 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001608 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001609 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001610 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001611 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1612 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001613 }
Evan Cheng7783f822007-06-08 09:36:04 +00001614 // Mixed predicated and unpredicated code. This cannot be iteratively
1615 // predicated.
1616 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001617 }
Evan Chenge26c0912007-05-21 22:22:58 +00001618
Evan Cheng288f1542007-06-08 22:01:07 +00001619 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001620
Evan Chengd0e66912007-05-23 07:23:16 +00001621 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001622 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001623 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001624 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001625 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001626 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001627 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001628
1629 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001630 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001631}
1632
Kyle Butte1c931b2016-08-10 20:45:56 +00001633/// IfConvertDiamondCommon - Common code shared between diamond conversions.
1634/// BBI, TrueBBI, and FalseBBI form the diamond shape.
1635/// NumDups1 - number of shared instructions at the beginning of TrueBBI and
1636/// FalseBBI
1637/// NumDups2 - number of shared instructions at the end of TrueBBI and FalseBBI
1638/// RemoveTrueBranch - Remove the branch of the true block before predicating
1639/// Only false for unanalyzable fallthrough cases.
1640/// RemoveFalseBranch - Remove the branch of the false block before predicating
1641/// Only false for unanalyzable fallthrough cases.
1642/// MergeAddEdges - Add successor edges when merging blocks. Only false for
1643/// unanalyzable fallthrough
1644bool IfConverter::IfConvertDiamondCommon(
1645 BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1646 unsigned NumDups1, unsigned NumDups2,
1647 bool TClobbersPred, bool FClobbersPred,
1648 bool RemoveTrueBranch, bool RemoveFalseBranch,
1649 bool MergeAddEdges) {
Evan Chenge26c0912007-05-21 22:22:58 +00001650
Evan Cheng51eb2c32007-06-18 08:37:25 +00001651 if (TrueBBI.IsDone || FalseBBI.IsDone ||
Kyle Butte1c931b2016-08-10 20:45:56 +00001652 TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001653 // Something has changed. It's no longer safe to predicate these blocks.
1654 BBI.IsAnalyzed = false;
1655 TrueBBI.IsAnalyzed = false;
1656 FalseBBI.IsAnalyzed = false;
1657 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001658 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001659
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001660 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1661 // Conservatively abort if-conversion if either BB has its address taken.
1662 return false;
1663
Bob Wilson1e5da552010-06-29 00:55:23 +00001664 // Put the predicated instructions from the 'true' block before the
1665 // instructions from the 'false' block, unless the true block would clobber
1666 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001667 BBInfo *BBI1 = &TrueBBI;
1668 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001669 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001670 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001671 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001672 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1673 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001674
Evan Cheng3a51c852007-06-16 09:34:52 +00001675 // Figure out the more profitable ordering.
1676 bool DoSwap = false;
Kyle Butte1c931b2016-08-10 20:45:56 +00001677 if (TClobbersPred && !FClobbersPred)
Evan Cheng3a51c852007-06-16 09:34:52 +00001678 DoSwap = true;
Kyle Butte1c931b2016-08-10 20:45:56 +00001679 else if (TClobbersPred == FClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001680 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001681 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001682 }
1683 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001684 std::swap(BBI1, BBI2);
1685 std::swap(Cond1, Cond2);
Kyle Butte1c931b2016-08-10 20:45:56 +00001686 std::swap(RemoveTrueBranch, RemoveFalseBranch);
Evan Cheng30565992007-06-06 00:57:55 +00001687 }
Evan Cheng79484222007-06-05 23:46:14 +00001688
Evan Cheng51eb2c32007-06-18 08:37:25 +00001689 // Remove the conditional branch from entry to the blocks.
1690 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1691
Krzysztof Parzyszeka003b762016-08-11 18:42:06 +00001692 // Initialize the Redefs:
1693 // - BB2 live-in regs need implicit uses before being redefined by BB1
1694 // instructions.
1695 // - BB1 live-out regs need implicit uses before being redefined by BB2
1696 // instructions. We start with BB1 live-ins so we have the live-out regs
1697 // after tracking the BB1 instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001698 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001699 Redefs.addLiveIns(*BBI1->BB);
Krzysztof Parzyszeka003b762016-08-11 18:42:06 +00001700 Redefs.addLiveIns(*BBI2->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001701
Evan Cheng51eb2c32007-06-18 08:37:25 +00001702 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001703 // Skip dbg_value instructions
Benjamin Kramer6b568962015-06-23 14:47:29 +00001704 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1705 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001706 BBI1->NonPredSize -= NumDups1;
1707 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001708
1709 // Skip past the dups on each side separately since there may be
1710 // differing dbg_value entries.
1711 for (unsigned i = 0; i < NumDups1; ++DI1) {
1712 if (!DI1->isDebugValue())
1713 ++i;
1714 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001715 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001716 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001717 if (!DI2->isDebugValue())
1718 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001719 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001720
Matthias Braund616ccc2013-10-11 19:04:37 +00001721 // Compute a set of registers which must not be killed by instructions in BB1:
1722 // This is everything used+live in BB2 after the duplicated instructions. We
1723 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001724 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001725 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1726 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001727 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001728 }
1729
1730 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1731 ++I) {
Pete Cooper7605e372015-05-05 20:14:22 +00001732 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1733 Redefs.stepForward(*I, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001734 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001735 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1736 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1737
Kyle Butte1c931b2016-08-10 20:45:56 +00001738 if (RemoveTrueBranch)
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001739 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1740 // Remove duplicated instructions.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001741 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001742 for (unsigned i = 0; i != NumDups2; ) {
1743 // NumDups2 only counted non-dbg_value instructions, so this won't
1744 // run off the head of the list.
1745 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001746 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001747 // skip dbg_value instructions
1748 if (!DI1->isDebugValue())
1749 ++i;
1750 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001751 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001752
Matthias Braund616ccc2013-10-11 19:04:37 +00001753 // Kill flags in the true block for registers living into the false block
1754 // must be removed.
1755 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1756
Kyle Butte1c931b2016-08-10 20:45:56 +00001757 // Remove 'false' block branch, and find the last instruction to predicate.
1758 // Save the debug location.
1759 if (RemoveFalseBranch)
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001760 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001761 DI2 = BBI2->BB->end();
1762 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001763 // NumDups2 only counted non-dbg_value instructions, so this won't
1764 // run off the head of the list.
1765 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001766 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001767 // skip dbg_value instructions
1768 if (!DI2->isDebugValue())
1769 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001770 }
Evan Cheng4266a792011-12-19 22:01:30 +00001771
1772 // Remember which registers would later be defined by the false block.
1773 // This allows us not to predicate instructions in the true block that would
1774 // later be re-defined. That is, rather than
1775 // subeq r0, r1, #1
1776 // addne r0, r1, #1
1777 // generate:
1778 // sub r0, r1, #1
1779 // addne r0, r1, #1
1780 SmallSet<unsigned, 4> RedefsByFalse;
1781 SmallSet<unsigned, 4> ExtUses;
1782 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1783 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1784 if (FI->isDebugValue())
1785 continue;
1786 SmallVector<unsigned, 4> Defs;
1787 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1788 const MachineOperand &MO = FI->getOperand(i);
1789 if (!MO.isReg())
1790 continue;
1791 unsigned Reg = MO.getReg();
1792 if (!Reg)
1793 continue;
1794 if (MO.isDef()) {
1795 Defs.push_back(Reg);
1796 } else if (!RedefsByFalse.count(Reg)) {
1797 // These are defined before ctrl flow reach the 'false' instructions.
1798 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001799 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1800 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001801 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001802 }
1803 }
1804
1805 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1806 unsigned Reg = Defs[i];
1807 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001808 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1809 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001810 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001811 }
1812 }
1813 }
1814 }
1815
1816 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001817 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001818
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001819 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1820 // a non-predicated in BBI2, then we don't want to predicate the one from
1821 // BBI2. The reason is that if we merged these blocks, we would end up with
1822 // two predicated terminators in the same block.
1823 if (!BBI2->BB->empty() && (DI2 == BBI2->BB->end())) {
1824 MachineBasicBlock::iterator BBI1T = BBI1->BB->getFirstTerminator();
1825 MachineBasicBlock::iterator BBI2T = BBI2->BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001826 if (BBI1T != BBI1->BB->end() && TII->isPredicated(*BBI1T) &&
1827 BBI2T != BBI2->BB->end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001828 --DI2;
1829 }
1830
Evan Cheng4266a792011-12-19 22:01:30 +00001831 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001832 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001833
Evan Cheng0598b2d2007-06-18 22:44:57 +00001834 // Merge the true block into the entry of the diamond.
Kyle Butte1c931b2016-08-10 20:45:56 +00001835 MergeBlocks(BBI, *BBI1, MergeAddEdges);
1836 MergeBlocks(BBI, *BBI2, MergeAddEdges);
1837 return true;
1838}
1839
1840/// IfConvertForkedDiamond - If convert an almost-diamond sub-CFG where the true
1841/// and false blocks share a common tail.
1842bool IfConverter::IfConvertForkedDiamond(
1843 BBInfo &BBI, IfcvtKind Kind,
1844 unsigned NumDups1, unsigned NumDups2,
1845 bool TClobbersPred, bool FClobbersPred) {
1846 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1847 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1848
1849 // Save the debug location for later.
1850 DebugLoc dl;
1851 MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1852 if (TIE != TrueBBI.BB->end())
1853 dl = TIE->getDebugLoc();
1854 // Removing branches from both blocks is safe, because we have already
1855 // determined that both blocks have the same branch instructions. The branch
1856 // will be added back at the end, unpredicated.
1857 if (!IfConvertDiamondCommon(
1858 BBI, TrueBBI, FalseBBI,
1859 NumDups1, NumDups2,
1860 TClobbersPred, FClobbersPred,
1861 /* RemoveTrueBranch */ true, /* RemoveFalseBranch */ true,
1862 /* MergeAddEdges */ true))
1863 return false;
1864
1865 // Add back the branch.
1866 // Debug location saved above when removing the branch from BBI2
1867 TII->InsertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
1868 TrueBBI.BrCond, dl);
1869
1870 RemoveExtraEdges(BBI);
1871
1872 // Update block info.
1873 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1874 InvalidatePreds(BBI.BB);
1875
1876 // FIXME: Must maintain LiveIns.
1877 return true;
1878}
1879
1880/// IfConvertDiamond - If convert a diamond sub-CFG.
1881///
1882bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1883 unsigned NumDups1, unsigned NumDups2) {
1884 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1885 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1886 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1887
1888 // True block must fall through or end with an unanalyzable terminator.
1889 if (!TailBB) {
1890 if (blockAlwaysFallThrough(TrueBBI))
1891 TailBB = FalseBBI.TrueBB;
1892 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1893 }
1894
1895 if (!IfConvertDiamondCommon(
1896 BBI, TrueBBI, FalseBBI,
1897 NumDups1, NumDups2,
1898 TrueBBI.ClobbersPred, FalseBBI.ClobbersPred,
1899 /* RemoveTrueBranch */ TrueBBI.IsBrAnalyzable,
1900 /* RemoveFalseBranch */ FalseBBI.IsBrAnalyzable,
1901 /* MergeAddEdges */ TailBB == nullptr))
1902 return false;
Evan Cheng30565992007-06-06 00:57:55 +00001903
Bob Wilson2371f4f2009-05-13 23:25:24 +00001904 // If the if-converted block falls through or unconditionally branches into
1905 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001906 // fold the tail block in as well. Otherwise, unless it falls through to the
1907 // tail, add a unconditional branch to it.
1908 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001909 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001910 bool CanMergeTail = !TailBBI.HasFallThrough &&
1911 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001912 // The if-converted block can still have a predicated terminator
1913 // (e.g. a predicated return). If that is the case, we cannot merge
1914 // it with the tail block.
1915 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001916 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001917 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001918 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1919 // check if there are any other predecessors besides those.
1920 unsigned NumPreds = TailBB->pred_size();
1921 if (NumPreds > 1)
1922 CanMergeTail = false;
1923 else if (NumPreds == 1 && CanMergeTail) {
1924 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
Kyle Butte1c931b2016-08-10 20:45:56 +00001925 if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
Bob Wilson1e5da552010-06-29 00:55:23 +00001926 CanMergeTail = false;
1927 }
1928 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001929 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001930 TailBBI.IsDone = true;
1931 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001932 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Evan Cheng0598b2d2007-06-18 22:44:57 +00001933 InsertUncondBranch(BBI.BB, TailBB, TII);
1934 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001935 }
Evan Chenge26c0912007-05-21 22:22:58 +00001936 }
1937
Bob Wilson1e5da552010-06-29 00:55:23 +00001938 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1939 // which can happen here if TailBB is unanalyzable and is merged, so
1940 // explicitly remove BBI1 and BBI2 as successors.
Kyle Butte1c931b2016-08-10 20:45:56 +00001941 BBI.BB->removeSuccessor(TrueBBI.BB);
1942 BBI.BB->removeSuccessor(FalseBBI.BB, /* NormalizeSuccessProbs */ true);
Evan Cheng288f1542007-06-08 22:01:07 +00001943 RemoveExtraEdges(BBI);
1944
Evan Cheng79484222007-06-05 23:46:14 +00001945 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001946 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001947 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001948
1949 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001950 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001951}
1952
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001953static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001954 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001955 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001956 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001957 return false;
1958
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001959 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1960 const MachineOperand &MO = MI.getOperand(i);
Evan Cheng4266a792011-12-19 22:01:30 +00001961 if (!MO.isReg())
1962 continue;
1963 unsigned Reg = MO.getReg();
1964 if (!Reg)
1965 continue;
1966 if (MO.isDef() && !LaterRedefs.count(Reg))
1967 return false;
1968 }
1969
1970 return true;
1971}
1972
Evan Cheng51eb2c32007-06-18 08:37:25 +00001973/// PredicateBlock - Predicate instructions from the start of the block to the
1974/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001975void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001976 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001977 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001978 SmallSet<unsigned, 4> *LaterRedefs) {
1979 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001980 bool MaySpec = LaterRedefs != nullptr;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001981 for (MachineInstr &I : llvm::make_range(BBI.BB->begin(), E)) {
1982 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001983 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001984 // It may be possible not to predicate an instruction if it's the 'true'
1985 // side of a diamond and the 'false' side may re-define the instruction's
1986 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001987 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001988 AnyUnpred = true;
1989 continue;
1990 }
1991 // If any instruction is predicated, then every instruction after it must
1992 // be predicated.
1993 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001994 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001995#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001996 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001997#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001998 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001999 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002000
Bob Wilson45814342010-06-19 05:33:57 +00002001 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002002 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002003 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00002004 }
Evan Chengd0e66912007-05-23 07:23:16 +00002005
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002006 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00002007
Evan Cheng92fb5452007-06-15 07:36:12 +00002008 BBI.IsAnalyzed = false;
2009 BBI.NonPredSize = 0;
2010
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002011 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00002012 if (AnyUnpred)
2013 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00002014}
2015
Evan Cheng92fb5452007-06-15 07:36:12 +00002016/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
2017/// the destination block. Skip end of block branches if IgnoreBr is true.
2018void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00002019 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00002020 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00002021 MachineFunction &MF = *ToBBI.BB->getParent();
2022
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002023 for (auto &I : *FromBBI.BB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00002024 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002025 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00002026 break;
2027
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002028 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00002029 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00002030 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002031 unsigned ExtraPredCost = TII->getPredicationCost(I);
2032 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00002033 if (NumCycles > 1)
2034 ToBBI.ExtraCost += NumCycles-1;
2035 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00002036
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00002037 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002038 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00002039#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002040 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00002041#endif
Craig Topperc0196b12014-04-14 00:51:57 +00002042 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00002043 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002044 }
2045
Bob Wilson45814342010-06-19 05:33:57 +00002046 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002047 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002048 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00002049
2050 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00002051 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00002052 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00002053 }
2054
Bob Wilson1e5da552010-06-29 00:55:23 +00002055 if (!IgnoreBr) {
2056 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
2057 FromBBI.BB->succ_end());
2058 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00002059 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00002060
Bob Wilson1e5da552010-06-29 00:55:23 +00002061 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
2062 MachineBasicBlock *Succ = Succs[i];
2063 // Fallthrough edge can't be transferred.
2064 if (Succ == FallThrough)
2065 continue;
2066 ToBBI.BB->addSuccessor(Succ);
2067 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00002068 }
2069
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002070 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2071 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002072
2073 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2074 ToBBI.IsAnalyzed = false;
2075
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002076 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00002077}
2078
Evan Cheng0f745da2007-05-18 00:20:58 +00002079/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00002080/// This will leave FromBB as an empty block, so remove all of its
2081/// successor edges except for the fall-through edge. If AddEdges is true,
2082/// i.e., when FromBBI's branch is being moved, add those successor edges to
2083/// ToBBI.
2084void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00002085 assert(!FromBBI.BB->hasAddressTaken() &&
2086 "Removing a BB whose address is taken!");
2087
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002088 // In case FromBBI.BB contains terminators (e.g. return instruction),
2089 // first move the non-terminator instructions, then the terminators.
2090 MachineBasicBlock::iterator FromTI = FromBBI.BB->getFirstTerminator();
2091 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
2092 ToBBI.BB->splice(ToTI, FromBBI.BB, FromBBI.BB->begin(), FromTI);
2093
2094 // If FromBB has non-predicated terminator we should copy it at the end.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002095 if (FromTI != FromBBI.BB->end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002096 ToTI = ToBBI.BB->end();
2097 ToBBI.BB->splice(ToTI, FromBBI.BB, FromTI, FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00002098
Cong Houb9e8d482015-12-17 01:29:08 +00002099 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2100 // unknown probabilities into known ones.
2101 // FIXME: This usage is too tricky and in the future we would like to
2102 // eliminate all unknown probabilities in MBB.
2103 ToBBI.BB->normalizeSuccProbs();
2104
Cong Houd40105d2015-09-18 20:22:41 +00002105 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
2106 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00002107 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00002108 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00002109 // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when
Hans Wennborg1dbaf672015-12-01 03:49:42 +00002110 // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00002111 auto To2FromProb = BranchProbability::getZero();
Cong Houfa1917c2015-12-01 00:02:51 +00002112 if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
Cong Houd97c1002015-12-01 05:29:22 +00002113 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB);
2114 // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the
2115 // edge probability being merged to other edges when this edge is removed
2116 // later.
2117 ToBBI.BB->setSuccProbability(
2118 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB),
2119 BranchProbability::getZero());
2120 }
2121
Cong Houd40105d2015-09-18 20:22:41 +00002122 for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
2123 MachineBasicBlock *Succ = FromSuccs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00002124 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00002125 if (Succ == FallThrough)
2126 continue;
Cong Houd40105d2015-09-18 20:22:41 +00002127
Cong Houd97c1002015-12-01 05:29:22 +00002128 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00002129 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002130 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
2131 // which is a portion of the edge probability from FromBBI.BB to Succ. The
2132 // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if
2133 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
2134 NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002135
Cong Houd97c1002015-12-01 05:29:22 +00002136 // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
Cong Houd40105d2015-09-18 20:22:41 +00002137 // only happens when if-converting a diamond CFG and FromBBI.BB is the
2138 // tail BB. In this case FromBBI.BB post-dominates ToBBI.BB and hence we
Cong Houd97c1002015-12-01 05:29:22 +00002139 // could just use the probabilities on FromBBI.BB's out-edges when adding
2140 // new successors.
2141 if (!To2FromProb.isZero())
2142 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00002143 }
2144
Evan Chengbe9859e2007-06-07 02:12:15 +00002145 FromBBI.BB->removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002146
2147 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002148 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00002149 // probability of this edge by adding NewProb to it. An example is shown
Cong Houd97c1002015-12-01 05:29:22 +00002150 // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we
2151 // don't have to set C as A's successor as it already is. We only need to
2152 // update the edge probability on A->C. Note that B will not be
2153 // immediately removed from A's successors. It is possible that B->D is
2154 // not removed either if D is a fallthrough of B. Later the edge A->D
2155 // (generated here) and B->D will be combined into one edge. To maintain
2156 // correct edge probability of this combined edge, we need to set the edge
2157 // probability of A->B to zero, which is already done above. The edge
2158 // probability on A->D is calculated by scaling the original probability
2159 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00002160 //
2161 // Before ifcvt: After ifcvt (assume B->D is kept):
2162 //
2163 // A A
2164 // /| /|\
2165 // / B / B|
2166 // | /| | ||
2167 // |/ | | |/
2168 // C D C D
2169 //
2170 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00002171 ToBBI.BB->setSuccProbability(
Cong Houd40105d2015-09-18 20:22:41 +00002172 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00002173 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002174 else
Cong Houd97c1002015-12-01 05:29:22 +00002175 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002176 }
Evan Chengbe9859e2007-06-07 02:12:15 +00002177 }
2178
Bob Wilson2371f4f2009-05-13 23:25:24 +00002179 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00002180 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00002181 FromBBI.BB->addSuccessor(NBB);
2182
Cong Houc1069892015-12-13 09:26:17 +00002183 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2184 // we've done above.
2185 ToBBI.BB->normalizeSuccProbs();
2186
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002187 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002188 FromBBI.Predicate.clear();
2189
Evan Chengd0e66912007-05-23 07:23:16 +00002190 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002191 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00002192 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00002193 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002194 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00002195 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00002196
Evan Cheng4dd31a72007-06-11 22:26:22 +00002197 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00002198 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00002199 ToBBI.IsAnalyzed = false;
2200 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00002201}
Akira Hatanaka4a616192015-06-08 18:50:43 +00002202
2203FunctionPass *
2204llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00002205 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00002206}