blob: cecc61700e1be39dd029b79cd473b080065d35f8 [file] [log] [blame]
Evan Chengf5e53a52007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
Justin Lebaracc47102016-04-01 01:09:03 +000010// This file implements the machine instruction level if-conversion pass, which
11// tries to convert conditional branches into predicated instructions.
Evan Chengf5e53a52007-05-16 02:00:57 +000012//
13//===----------------------------------------------------------------------===//
14
Evan Chengf5e53a52007-05-16 02:00:57 +000015#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "BranchFolding.h"
17#include "llvm/ADT/STLExtras.h"
Kyle Buttd76755e2016-08-18 22:09:23 +000018#include "llvm/ADT/ScopeExit.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000021#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000022#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000023#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000024#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000025#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000028#include "llvm/CodeGen/TargetSchedule.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000029#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000030#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000031#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000036#include "llvm/Target/TargetSubtargetInfo.h"
Cong Houd97c1002015-12-01 05:29:22 +000037#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000038#include <utility>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000039
Evan Chengf5e53a52007-05-16 02:00:57 +000040using namespace llvm;
41
Chandler Carruth1b9dde02014-04-22 02:02:50 +000042#define DEBUG_TYPE "ifcvt"
43
Chris Lattner769c86b2008-01-07 05:40:58 +000044// Hidden options for help debugging.
45static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
46static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
47static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000048static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000049 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000050static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000051 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000052static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000053 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000054static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000055 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000056static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000057 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000058static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000059 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000060static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000061 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000062static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
63 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000064
Evan Cheng2117d1f2007-06-09 01:03:43 +000065STATISTIC(NumSimple, "Number of simple if-conversions performed");
66STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
67STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000068STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000069STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
70STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
71STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
72STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000073STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000074STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000075
76namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000077 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000078 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000079 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000080 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000081 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
82 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000083 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000084 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000085 ICTriangle, // BB is entry of a triangle sub-CFG.
Kyle Buttce0196d2016-08-19 18:17:04 +000086 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Chengf5e53a52007-05-16 02:00:57 +000087 };
88
Matthias Braun2c931792016-08-17 02:51:57 +000089 /// One per MachineBasicBlock, this is used to cache the result
Evan Chengf5e53a52007-05-16 02:00:57 +000090 /// if-conversion feasibility analysis. This includes results from
Jacques Pienaar71c30a12016-07-15 14:41:04 +000091 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000092 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000093 /// diamond shape), its size, whether it's predicable, and whether any
94 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000095 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +000096 /// IsDone - True if BB is not to be considered for ifcvt.
97 /// IsBeingAnalyzed - True if BB is currently being analyzed.
98 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
99 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000100 /// IsBrAnalyzable - True if analyzeBranch() returns false.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000101 /// HasFallThrough - True if BB may fallthrough to the following BB.
102 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000103 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000104 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000105 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000106 /// ExtraCost - Extra cost for multi-cycle instructions.
107 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000108 /// BB - Corresponding MachineBasicBlock.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000109 /// TrueBB / FalseBB- See analyzeBranch().
Evan Chengd0e66912007-05-23 07:23:16 +0000110 /// BrCond - Conditions for end of block conditional branches.
111 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000112 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000113 bool IsDone : 1;
114 bool IsBeingAnalyzed : 1;
115 bool IsAnalyzed : 1;
116 bool IsEnqueued : 1;
117 bool IsBrAnalyzable : 1;
118 bool HasFallThrough : 1;
119 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000120 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000121 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000122 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000123 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000124 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000125 MachineBasicBlock *BB;
126 MachineBasicBlock *TrueBB;
127 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000128 SmallVector<MachineOperand, 4> BrCond;
129 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000130 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000131 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
Kyle Buttce0196d2016-08-19 18:17:04 +0000132 HasFallThrough(false), IsUnpredicable(false),
133 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
134 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
Craig Topperc0196b12014-04-14 00:51:57 +0000135 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000136 };
137
Matthias Braun2c931792016-08-17 02:51:57 +0000138 /// Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000139 /// BBI - Corresponding BBInfo.
140 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000141 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000142 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000143 /// NumDups - Number of instructions that would be duplicated due
144 /// to this if-conversion. (For diamonds, the number of
145 /// identical instructions at the beginnings of both
146 /// paths).
147 /// NumDups2 - For diamonds, the number of identical instructions
148 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000149 struct IfcvtToken {
150 BBInfo &BBI;
151 IfcvtKind Kind;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000152 unsigned NumDups;
153 unsigned NumDups2;
Kyle Butt491afad2016-08-18 22:09:25 +0000154 bool NeedSubsumption : 1;
155 bool TClobbersPred : 1;
156 bool FClobbersPred : 1;
157 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
158 bool tc = false, bool fc = false)
159 : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
160 TClobbersPred(tc), FClobbersPred(fc) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000161 };
162
Matthias Braun2c931792016-08-17 02:51:57 +0000163 /// Results of if-conversion feasibility analysis indexed by basic block
164 /// number.
Evan Chengf5e53a52007-05-16 02:00:57 +0000165 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000166 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000167
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000168 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000169 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000170 const TargetRegisterInfo *TRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000171 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000172 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000173
Juergen Ributzka310034e2013-12-14 06:52:56 +0000174 LivePhysRegs Redefs;
175 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000176
Evan Chengc5adcca2012-06-08 21:53:50 +0000177 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000178 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000179 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000180 std::function<bool(const Function &)> PredicateFtor;
181
Evan Chengf5e53a52007-05-16 02:00:57 +0000182 public:
183 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000184 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000185 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000186 initializeIfConverterPass(*PassRegistry::getPassRegistry());
187 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000188
Craig Topper4584cd52014-03-07 09:26:03 +0000189 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000190 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000191 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000192 MachineFunctionPass::getAnalysisUsage(AU);
193 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000194
Craig Topper4584cd52014-03-07 09:26:03 +0000195 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000196
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000197 MachineFunctionProperties getRequiredProperties() const override {
198 return MachineFunctionProperties().set(
199 MachineFunctionProperties::Property::AllVRegsAllocated);
200 }
201
Evan Chengf5e53a52007-05-16 02:00:57 +0000202 private:
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000203 bool ReverseBranchCondition(BBInfo &BBI) const;
Owen Andersonf31f33e2010-10-01 22:45:50 +0000204 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000205 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000206 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000207 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000208 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000209 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
Kyle Butt491afad2016-08-18 22:09:25 +0000210 unsigned &Dups1, unsigned &Dups2,
211 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000212 void AnalyzeBranches(BBInfo &BBI);
213 void ScanInstructions(BBInfo &BBI,
214 MachineBasicBlock::iterator &Begin,
Kyle Buttce0196d2016-08-19 18:17:04 +0000215 MachineBasicBlock::iterator &End) const;
Kyle Butt491afad2016-08-18 22:09:25 +0000216 bool RescanInstructions(
217 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
218 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
219 BBInfo &TrueBBI, BBInfo &FalseBBI) const;
Matthias Braun08f47042016-08-17 02:52:01 +0000220 void AnalyzeBlock(MachineBasicBlock &MBB,
Justin Lebar3a7bc572016-02-22 17:51:28 +0000221 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000222 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Kyle Butt491afad2016-08-18 22:09:25 +0000223 bool isTriangle = false, bool RevBranch = false,
224 bool hasCommonTail = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000225 void AnalyzeBlocks(MachineFunction &MF,
226 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Matthias Braun08f47042016-08-17 02:52:01 +0000227 void InvalidatePreds(MachineBasicBlock &MBB);
Evan Cheng288f1542007-06-08 22:01:07 +0000228 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000229 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
230 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000231 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
Kyle Butt491afad2016-08-18 22:09:25 +0000232 unsigned NumDups1, unsigned NumDups2,
233 bool TClobbers, bool FClobbers);
Evan Chengd0e66912007-05-23 07:23:16 +0000234 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000235 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000236 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000237 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000238 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000239 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000240 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000241 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000242
Evan Chengdebf9c52010-11-03 00:45:17 +0000243 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
244 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000245 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000246 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000247 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000248 }
249
Evan Chengdebf9c52010-11-03 00:45:17 +0000250 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
251 unsigned TCycle, unsigned TExtra,
252 MachineBasicBlock &FBB,
253 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000254 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000255 return TCycle > 0 && FCycle > 0 &&
256 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000257 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000258 }
259
Matthias Braun2c931792016-08-17 02:51:57 +0000260 /// Returns true if Block ends without a terminator.
Evan Chengbe9859e2007-06-07 02:12:15 +0000261 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000262 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000263 }
264
Matthias Braun2c931792016-08-17 02:51:57 +0000265 /// Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000266 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
267 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000268 int Incr1 = (C1->Kind == ICDiamond)
269 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
270 int Incr2 = (C2->Kind == ICDiamond)
271 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
272 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000273 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000274 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000275 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000276 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000277 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000278 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000279 // Favors diamond over triangle, etc.
280 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
281 return true;
282 else if (C1->Kind == C2->Kind)
283 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
284 }
285 }
286 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000287 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000288 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000289
Evan Chengf5e53a52007-05-16 02:00:57 +0000290 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000291}
Evan Chengf5e53a52007-05-16 02:00:57 +0000292
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000293char &llvm::IfConverterID = IfConverter::ID;
294
Owen Anderson8ac477f2010-10-12 19:48:12 +0000295INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000296INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000297INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000298
Evan Chengf5e53a52007-05-16 02:00:57 +0000299bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000300 if (skipFunction(*MF.getFunction()) ||
301 (PredicateFtor && !PredicateFtor(*MF.getFunction())))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000302 return false;
303
Eric Christopher3d4276f2015-01-27 07:31:29 +0000304 const TargetSubtargetInfo &ST = MF.getSubtarget();
305 TLI = ST.getTargetLowering();
306 TII = ST.getInstrInfo();
307 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000308 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000309 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000310 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000311 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000312
Evan Chengf5e53a52007-05-16 02:00:57 +0000313 if (!TII) return false;
314
Evan Chengc5adcca2012-06-08 21:53:50 +0000315 PreRegAlloc = MRI->isSSA();
316
317 bool BFChange = false;
318 if (!PreRegAlloc) {
319 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000320 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000321 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000322 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000323 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000324
David Greene72e47cd2010-01-04 22:02:01 +0000325 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000326 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000327
328 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000329 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000330 return false;
331 }
David Greene72e47cd2010-01-04 22:02:01 +0000332 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000333
Evan Chengf5e53a52007-05-16 02:00:57 +0000334 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000335 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000336
Justin Lebar3a7bc572016-02-22 17:51:28 +0000337 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000338 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000339 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
340 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
341 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000342 // Do an initial analysis for each basic block and find all the potential
343 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000344 bool Change = false;
345 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000346 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000347 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000348 Tokens.pop_back();
349 BBInfo &BBI = Token->BBI;
350 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000351 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000352 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000353
Evan Cheng4dd31a72007-06-11 22:26:22 +0000354 // If the block has been evicted out of the queue or it has already been
355 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000356 if (BBI.IsDone)
357 BBI.IsEnqueued = false;
358 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000359 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000360
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000361 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000362
Evan Cheng312b7232007-06-04 06:47:22 +0000363 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000364 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000365 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000366 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000367 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000368 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000369 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000370 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
371 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000372 << "): BB#" << BBI.BB->getNumber() << " ("
373 << ((Kind == ICSimpleFalse)
374 ? BBI.FalseBB->getNumber()
375 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000376 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000377 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000378 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000379 if (isFalse) ++NumSimpleFalse;
380 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000381 }
Evan Cheng312b7232007-06-04 06:47:22 +0000382 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000383 }
Evan Chengd0e66912007-05-23 07:23:16 +0000384 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000385 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000386 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000387 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000388 bool isFalse = Kind == ICTriangleFalse;
389 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000390 if (DisableTriangle && !isFalse && !isRev) break;
391 if (DisableTriangleR && !isFalse && isRev) break;
392 if (DisableTriangleF && isFalse && !isRev) break;
393 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000394 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000395 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000396 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000397 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000398 DEBUG(dbgs() << " rev");
399 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000400 << BBI.TrueBB->getNumber() << ",F:"
401 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000402 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000403 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000404 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000405 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000406 if (isRev) ++NumTriangleFRev;
407 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000408 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000409 if (isRev) ++NumTriangleRev;
410 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000411 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000412 }
Evan Chengd0e66912007-05-23 07:23:16 +0000413 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000414 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000415 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000416 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000417 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000418 << BBI.TrueBB->getNumber() << ",F:"
419 << BBI.FalseBB->getNumber() << ") ");
Kyle Butt491afad2016-08-18 22:09:25 +0000420 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
421 Token->TClobbersPred,
422 Token->FClobbersPred);
David Greene72e47cd2010-01-04 22:02:01 +0000423 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000424 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000425 break;
426 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000427 }
428
Evan Cheng312b7232007-06-04 06:47:22 +0000429 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000430
Evan Cheng92fb5452007-06-15 07:36:12 +0000431 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
432 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
433 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000434 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000435 }
Evan Chengd0e66912007-05-23 07:23:16 +0000436
Evan Chengd0e66912007-05-23 07:23:16 +0000437 if (!Change)
438 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000439 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000440 }
Evan Cheng478b8052007-05-18 01:55:58 +0000441
Evan Cheng3a51c852007-06-16 09:34:52 +0000442 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000443 BBAnalysis.clear();
444
Evan Chengcf9e8a92010-06-18 22:17:13 +0000445 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000446 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000447 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000448 getAnalysisIfAvailable<MachineModuleInfo>());
449 }
450
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000451 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000452 return MadeChange;
453}
454
Matthias Braun2c931792016-08-17 02:51:57 +0000455/// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000456static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000457 MachineBasicBlock *TrueBB) {
Matthias Braunb1e05582016-08-17 02:51:59 +0000458 for (MachineBasicBlock *SuccBB : BB->successors()) {
Evan Cheng0f745da2007-05-18 00:20:58 +0000459 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000460 return SuccBB;
461 }
Craig Topperc0196b12014-04-14 00:51:57 +0000462 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000463}
464
Matthias Braun2c931792016-08-17 02:51:57 +0000465/// Reverse the condition of the end of the block branch. Swap block's 'true'
466/// and 'false' successors.
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000467bool IfConverter::ReverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000468 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000469 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
470 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000471 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000472 std::swap(BBI.TrueBB, BBI.FalseBB);
473 return true;
474 }
475 return false;
476}
477
Matthias Braun2c931792016-08-17 02:51:57 +0000478/// Returns the next block in the function blocks ordering. If it is the end,
479/// returns NULL.
Matthias Braun08f47042016-08-17 02:52:01 +0000480static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
481 MachineFunction::iterator I = MBB.getIterator();
482 MachineFunction::iterator E = MBB.getParent()->end();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000483 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000484 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000485 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000486}
487
Matthias Braun2c931792016-08-17 02:51:57 +0000488/// Returns true if the 'true' block (along with its predecessor) forms a valid
489/// simple shape for ifcvt. It also returns the number of instructions that the
490/// ifcvt would need to duplicate if performed in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000491bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000492 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000493 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000494 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000495 return false;
496
Evan Chenga955c022007-06-19 21:45:13 +0000497 if (TrueBBI.IsBrAnalyzable)
498 return false;
499
Evan Cheng23402fc2007-06-15 21:18:05 +0000500 if (TrueBBI.BB->pred_size() > 1) {
501 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000502 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000503 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000504 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000505 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000506 }
507
Evan Chenga955c022007-06-19 21:45:13 +0000508 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000509}
510
Matthias Braun2c931792016-08-17 02:51:57 +0000511/// Returns true if the 'true' and 'false' blocks (along with their common
512/// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
513/// true, it checks if 'true' block's false branch branches to the 'false' block
514/// rather than the other way around. It also returns the number of instructions
515/// that the ifcvt would need to duplicate if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000516bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000517 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000518 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000519 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000520 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000521 return false;
522
Evan Cheng23402fc2007-06-15 21:18:05 +0000523 if (TrueBBI.BB->pred_size() > 1) {
524 if (TrueBBI.CannotBeCopied)
525 return false;
526
Evan Cheng92fb5452007-06-15 07:36:12 +0000527 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000528 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000529 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000530 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000531 --Size;
532 else {
533 MachineBasicBlock *FExit = FalseBranch
534 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
535 if (FExit)
536 // Require a conditional branch
537 ++Size;
538 }
539 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000540 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000541 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000542 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000543 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000544
Evan Cheng7783f822007-06-08 09:36:04 +0000545 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
546 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000547 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000548 if (++I == TrueBBI.BB->getParent()->end())
549 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000550 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000551 }
Evan Cheng7783f822007-06-08 09:36:04 +0000552 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000553}
554
Matthias Braun2c931792016-08-17 02:51:57 +0000555/// Increment \p It until it points to a non-debug instruction or to \p End.
Kyle Buttfe916822016-08-06 01:52:31 +0000556/// @param It Iterator to increment
557/// @param End Iterator that points to end. Will be compared to It
558/// @returns true if It == End, false otherwise.
559static inline bool skipDebugInstructionsForward(
560 MachineBasicBlock::iterator &It,
561 MachineBasicBlock::iterator &End) {
562 while (It != End && It->isDebugValue())
563 It++;
564 return It == End;
565}
566
Kyle Buttd76755e2016-08-18 22:09:23 +0000567/// Shrink the provided inclusive range by one instruction.
568/// If the range was one instruction (\p It == \p Begin), It is not modified,
569/// but \p Empty is set to true.
570static inline void shrinkInclusiveRange(
571 MachineBasicBlock::iterator &Begin,
572 MachineBasicBlock::iterator &It,
573 bool &Empty) {
574 if (It == Begin)
575 Empty = true;
576 else
577 It--;
578}
579
580/// Decrement \p It until it points to a non-debug instruction or the range is
581/// empty.
Kyle Buttfe916822016-08-06 01:52:31 +0000582/// @param It Iterator to decrement.
David Majnemer70c93fa2016-08-06 08:37:12 +0000583/// @param Begin Iterator that points to beginning. Will be compared to It
Kyle Buttd76755e2016-08-18 22:09:23 +0000584/// @param Empty Set to true if the resulting range is Empty
585/// @returns the value of Empty as a convenience.
Kyle Buttfe916822016-08-06 01:52:31 +0000586static inline bool skipDebugInstructionsBackward(
Kyle Buttd76755e2016-08-18 22:09:23 +0000587 MachineBasicBlock::iterator &Begin,
Kyle Buttfe916822016-08-06 01:52:31 +0000588 MachineBasicBlock::iterator &It,
Kyle Buttd76755e2016-08-18 22:09:23 +0000589 bool &Empty) {
590 while (!Empty && It->isDebugValue())
591 shrinkInclusiveRange(Begin, It, Empty);
592 return Empty;
Kyle Buttfe916822016-08-06 01:52:31 +0000593}
594
Kyle Butt4f0e2872016-08-06 01:52:33 +0000595/// Count duplicated instructions and move the iterators to show where they
596/// are.
597/// @param TIB True Iterator Begin
598/// @param FIB False Iterator Begin
599/// These two iterators initially point to the first instruction of the two
600/// blocks, and finally point to the first non-shared instruction.
601/// @param TIE True Iterator End
602/// @param FIE False Iterator End
603/// These two iterators initially point to End() for the two blocks() and
604/// finally point to the first shared instruction in the tail.
605/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
606/// two blocks.
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000607static void countDuplicatedInstructions(
608 MachineBasicBlock::iterator &TIB,
609 MachineBasicBlock::iterator &FIB,
610 MachineBasicBlock::iterator &TIE,
611 MachineBasicBlock::iterator &FIE,
612 unsigned &Dups1, unsigned &Dups2,
613 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
614 bool SkipConditionalBranches) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000615
Bob Wilsone1961fe2010-10-26 00:02:24 +0000616 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000617 // Skip dbg_value instructions. These do not count.
Kyle Buttfe916822016-08-06 01:52:31 +0000618 if(skipDebugInstructionsForward(TIB, TIE))
619 break;
620 if(skipDebugInstructionsForward(FIB, FIE))
621 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000622 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000623 break;
624 ++Dups1;
625 ++TIB;
626 ++FIB;
627 }
628
Kyle Buttce0196d2016-08-19 18:17:04 +0000629 // If both blocks are returning don't skip the branches, since they will
630 // likely be both identical return instructions. In such cases the return
631 // can be left unpredicated.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000632 // Check for already containing all of the block.
633 if (TIB == TIE || FIB == FIE)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000634 return;
Kyle Buttd76755e2016-08-18 22:09:23 +0000635 // Now, in preparation for counting duplicate instructions at the ends of the
636 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000637 --TIE;
638 --FIE;
Kyle Buttd76755e2016-08-18 22:09:23 +0000639
640 // After this point TIB and TIE define an inclusive range, which means that
641 // TIB == TIE is true when there is one more instruction to consider, not at
642 // the end. Because we may not be able to go before TIB, we need a flag to
643 // indicate a completely empty range.
644 bool TEmpty = false, FEmpty = false;
645
646 // Upon exit TIE and FIE will both point at the last non-shared instruction.
647 // They need to be moved forward to point past the last non-shared
648 // instruction if the range they delimit is non-empty.
649 auto IncrementEndIteratorsOnExit = make_scope_exit([&]() {
650 if (!TEmpty)
651 ++TIE;
652 if (!FEmpty)
653 ++FIE;
654 });
655
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000656 if (!TBB.succ_empty() || !FBB.succ_empty()) {
657 if (SkipConditionalBranches) {
Kyle Buttd76755e2016-08-18 22:09:23 +0000658 while (!TEmpty && TIE->isBranch())
659 shrinkInclusiveRange(TIB, TIE, TEmpty);
660 while (!FEmpty && FIE->isBranch())
661 shrinkInclusiveRange(FIB, FIE, FEmpty);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000662 } else {
Kyle Buttd76755e2016-08-18 22:09:23 +0000663 while (!TEmpty && TIE->isUnconditionalBranch())
664 shrinkInclusiveRange(TIB, TIE, TEmpty);
665 while (!FEmpty && FIE->isUnconditionalBranch())
666 shrinkInclusiveRange(FIB, FIE, FEmpty);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000667 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000668 }
669
670 // If Dups1 includes all of a block, then don't count duplicate
671 // instructions at the end of the blocks.
Kyle Buttd76755e2016-08-18 22:09:23 +0000672 if (TEmpty || FEmpty)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000673 return;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000674
675 // Count duplicate instructions at the ends of the blocks.
Kyle Buttd76755e2016-08-18 22:09:23 +0000676 while (!TEmpty && !FEmpty) {
Bob Wilsone1961fe2010-10-26 00:02:24 +0000677 // Skip dbg_value instructions. These do not count.
Kyle Buttd76755e2016-08-18 22:09:23 +0000678 if (skipDebugInstructionsBackward(TIB, TIE, TEmpty))
Kyle Buttfe916822016-08-06 01:52:31 +0000679 break;
Kyle Buttd76755e2016-08-18 22:09:23 +0000680 if (skipDebugInstructionsBackward(FIB, FIE, FEmpty))
Kyle Buttfe916822016-08-06 01:52:31 +0000681 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000682 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000683 break;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000684 // If we are trying to make sure the conditional branches are the same, we
685 // still don't want to count them.
686 if (SkipConditionalBranches || !TIE->isBranch())
687 ++Dups2;
Kyle Buttd76755e2016-08-18 22:09:23 +0000688 shrinkInclusiveRange(TIB, TIE, TEmpty);
689 shrinkInclusiveRange(FIB, FIE, FEmpty);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000690 }
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000691}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000692
Kyle Butt491afad2016-08-18 22:09:25 +0000693/// RescanInstructions - Run ScanInstructions on a pair of blocks.
694/// @param TIB - True Iterator Begin, points to first non-shared instruction
695/// @param FIB - False Iterator Begin, points to first non-shared instruction
696/// @param TIE - True Iterator End, points past last non-shared instruction
697/// @param FIE - False Iterator End, points past last non-shared instruction
698/// @param TrueBBI - BBInfo to update for the true block.
699/// @param FalseBBI - BBInfo to update for the false block.
700/// @returns - false if either block cannot be predicated or if both blocks end
701/// with a predicate-clobbering instruction.
702bool IfConverter::RescanInstructions(
703 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
704 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
705 BBInfo &TrueBBI, BBInfo &FalseBBI) const {
Kyle Buttce0196d2016-08-19 18:17:04 +0000706 ScanInstructions(TrueBBI, TIB, TIE);
Kyle Butt491afad2016-08-18 22:09:25 +0000707 if (TrueBBI.IsUnpredicable)
708 return false;
Kyle Buttce0196d2016-08-19 18:17:04 +0000709 ScanInstructions(FalseBBI, FIB, FIE);
Kyle Butt491afad2016-08-18 22:09:25 +0000710 if (FalseBBI.IsUnpredicable)
711 return false;
712 if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
713 return false;
714 return true;
715}
716
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000717/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
718/// with their common predecessor) forms a valid diamond shape for ifcvt.
Kyle Butt491afad2016-08-18 22:09:25 +0000719bool IfConverter::ValidDiamond(
720 BBInfo &TrueBBI, BBInfo &FalseBBI,
721 unsigned &Dups1, unsigned &Dups2,
722 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000723 Dups1 = Dups2 = 0;
724 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
725 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
726 return false;
727
728 MachineBasicBlock *TT = TrueBBI.TrueBB;
729 MachineBasicBlock *FT = FalseBBI.TrueBB;
730
731 if (!TT && blockAlwaysFallThrough(TrueBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000732 TT = getNextBlock(*TrueBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000733 if (!FT && blockAlwaysFallThrough(FalseBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000734 FT = getNextBlock(*FalseBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000735 if (TT != FT)
736 return false;
737 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
738 return false;
739 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
740 return false;
741
742 // FIXME: Allow true block to have an early exit?
Kyle Butt491afad2016-08-18 22:09:25 +0000743 if (TrueBBI.FalseBB || FalseBBI.FalseBB)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000744 return false;
745
746 // Count duplicate instructions at the beginning and end of the true and
747 // false blocks.
748 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
749 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
750 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
751 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
752 countDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
753 *TrueBBI.BB, *FalseBBI.BB,
754 /* SkipConditionalBranches */ true);
Kyle Butt491afad2016-08-18 22:09:25 +0000755
756 TrueBBICalc.BB = TrueBBI.BB;
757 FalseBBICalc.BB = FalseBBI.BB;
758 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
759 return false;
760 // The size is used to decide whether to if-convert, and the shared portions
761 // are subtracted off. Because of the subtraction, we just use the size that
762 // was calculated by the original ScanInstructions, as it is correct.
763 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
764 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000765 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000766}
767
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000768/// AnalyzeBranches - Look at the branches at the end of a block to determine if
769/// the block is predicable.
770void IfConverter::AnalyzeBranches(BBInfo &BBI) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000771 if (BBI.IsDone)
772 return;
773
Craig Topperc0196b12014-04-14 00:51:57 +0000774 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000775 BBI.BrCond.clear();
776 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000777 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000778 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000779
780 if (BBI.BrCond.size()) {
781 // No false branch. This BB must end with a conditional branch and a
782 // fallthrough.
783 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000784 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000785 if (!BBI.FalseBB) {
786 // Malformed bcc? True and false blocks are the same?
787 BBI.IsUnpredicable = true;
Evan Chengb9bff582009-06-15 21:24:34 +0000788 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000789 }
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000790}
Evan Cheng4dd31a72007-06-11 22:26:22 +0000791
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000792/// ScanInstructions - Scan all the instructions in the block to determine if
793/// the block is predicable. In most cases, that means all the instructions
794/// in the block are isPredicable(). Also checks if the block contains any
795/// instruction which can clobber a predicate (e.g. condition code register).
796/// If so, the block is not predicable unless it's the last instruction.
797void IfConverter::ScanInstructions(BBInfo &BBI,
798 MachineBasicBlock::iterator &Begin,
Kyle Buttce0196d2016-08-19 18:17:04 +0000799 MachineBasicBlock::iterator &End) const {
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000800 if (BBI.IsDone || BBI.IsUnpredicable)
801 return;
802
803 bool AlreadyPredicated = !BBI.Predicate.empty();
804
Evan Cheng4dd31a72007-06-11 22:26:22 +0000805 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000806 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000807 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000808 BBI.ClobbersPred = false;
Matthias Braunb1e05582016-08-17 02:51:59 +0000809 for (MachineInstr &MI : make_range(Begin, End)) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000810 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000811 continue;
812
Justin Lebar7dba2e02016-04-15 01:38:41 +0000813 // It's unsafe to duplicate convergent instructions in this context, so set
814 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
815 // following CFG, which is subject to our "simple" transformation.
816 //
817 // BB0 // if (c1) goto BB1; else goto BB2;
818 // / \
819 // BB1 |
820 // | BB2 // if (c2) goto TBB; else goto FBB;
821 // | / |
822 // | / |
823 // TBB |
824 // | |
825 // | FBB
826 // |
827 // exit
828 //
829 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
830 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
831 // TBB contains a convergent instruction. This is safe iff doing so does
832 // not add a control-flow dependency to the convergent instruction -- i.e.,
833 // it's safe iff the set of control flows that leads us to the convergent
834 // instruction does not get smaller after the transformation.
835 //
836 // Originally we executed TBB if c1 || c2. After the transformation, there
837 // are two copies of TBB's instructions. We get to the first if c1, and we
838 // get to the second if !c1 && c2.
839 //
840 // There are clearly fewer ways to satisfy the condition "c1" than
841 // "c1 || c2". Since we've shrunk the set of control flows which lead to
842 // our convergent instruction, the transformation is unsafe.
843 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000844 BBI.CannotBeCopied = true;
845
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000846 bool isPredicated = TII->isPredicated(MI);
847 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000848
Joey Goulya5153cb2013-09-09 14:21:49 +0000849 // A conditional branch is not predicable, but it may be eliminated.
850 if (isCondBr)
851 continue;
852
853 if (!isPredicated) {
854 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000855 unsigned ExtraPredCost = TII->getPredicationCost(MI);
856 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000857 if (NumCycles > 1)
858 BBI.ExtraCost += NumCycles-1;
859 BBI.ExtraCost2 += ExtraPredCost;
860 } else if (!AlreadyPredicated) {
861 // FIXME: This instruction is already predicated before the
862 // if-conversion pass. It's probably something like a conditional move.
863 // Mark this block unpredicable for now.
864 BBI.IsUnpredicable = true;
865 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000866 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000867
868 if (BBI.ClobbersPred && !isPredicated) {
869 // Predicate modification instruction should end the block (except for
870 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000871 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000872 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000873 BBI.IsUnpredicable = true;
874 return;
875 }
876
Evan Chengfbc73092007-07-10 17:50:43 +0000877 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
878 // still potentially predicable.
879 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000880 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000881 BBI.ClobbersPred = true;
882
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000883 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000884 BBI.IsUnpredicable = true;
885 return;
886 }
887 }
888}
889
Matthias Braun2c931792016-08-17 02:51:57 +0000890/// Determine if the block is a suitable candidate to be predicated by the
891/// specified predicate.
Kyle Butt491afad2016-08-18 22:09:25 +0000892/// @param BBI BBInfo for the block to check
893/// @param Pred Predicate array for the branch that leads to BBI
894/// @param isTriangle true if the Analysis is for a triangle
895/// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
896/// case
897/// @param hasCommonTail true if BBI shares a tail with a sibling block that
898/// contains any instruction that would make the block unpredicable.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000899bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000900 SmallVectorImpl<MachineOperand> &Pred,
Kyle Butt491afad2016-08-18 22:09:25 +0000901 bool isTriangle, bool RevBranch,
902 bool hasCommonTail) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000903 // If the block is dead or unpredicable, then it cannot be predicated.
Kyle Butt491afad2016-08-18 22:09:25 +0000904 // Two blocks may share a common unpredicable tail, but this doesn't prevent
905 // them from being if-converted. The non-shared portion is assumed to have
906 // been checked
907 if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000908 return false;
909
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000910 // If it is already predicated but we couldn't analyze its terminator, the
911 // latter might fallthrough, but we can't determine where to.
912 // Conservatively avoid if-converting again.
913 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
914 return false;
915
Quentin Colombetbdab2272013-07-24 20:20:37 +0000916 // If it is already predicated, check if the new predicate subsumes
917 // its predicate.
918 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000919 return false;
920
Kyle Butt491afad2016-08-18 22:09:25 +0000921 if (!hasCommonTail && BBI.BrCond.size()) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000922 if (!isTriangle)
923 return false;
924
Bob Wilson2371f4f2009-05-13 23:25:24 +0000925 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000926 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
927 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000928 if (RevBranch) {
929 if (TII->ReverseBranchCondition(Cond))
930 return false;
931 }
932 if (TII->ReverseBranchCondition(RevPred) ||
933 !TII->SubsumesPredicate(Cond, RevPred))
934 return false;
935 }
936
937 return true;
938}
939
Matthias Braun2c931792016-08-17 02:51:57 +0000940/// Analyze the structure of the sub-CFG starting from the specified block.
941/// Record its successors and whether it looks like an if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000942void IfConverter::AnalyzeBlock(
Matthias Braun08f47042016-08-17 02:52:01 +0000943 MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000944 struct BBState {
Matthias Braun08f47042016-08-17 02:52:01 +0000945 BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000946 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000947
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000948 /// This flag is true if MBB's successors have been analyzed.
949 bool SuccsAnalyzed;
950 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000951
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000952 // Push MBB to the stack.
953 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000954
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000955 while (!BBStack.empty()) {
956 BBState &State = BBStack.back();
957 MachineBasicBlock *BB = State.MBB;
958 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000959
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000960 if (!State.SuccsAnalyzed) {
961 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
962 BBStack.pop_back();
963 continue;
964 }
Evan Cheng9030b982007-06-06 10:16:17 +0000965
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000966 BBI.BB = BB;
967 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000968
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000969 AnalyzeBranches(BBI);
970 MachineBasicBlock::iterator Begin = BBI.BB->begin();
971 MachineBasicBlock::iterator End = BBI.BB->end();
972 ScanInstructions(BBI, Begin, End);
Evan Chengb9bff582009-06-15 21:24:34 +0000973
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000974 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
975 // not considered for ifcvt anymore.
976 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
977 BBI.IsBeingAnalyzed = false;
978 BBI.IsAnalyzed = true;
979 BBStack.pop_back();
980 continue;
981 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000982
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000983 // Do not ifcvt if either path is a back edge to the entry block.
984 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
985 BBI.IsBeingAnalyzed = false;
986 BBI.IsAnalyzed = true;
987 BBStack.pop_back();
988 continue;
989 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000990
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000991 // Do not ifcvt if true and false fallthrough blocks are the same.
992 if (!BBI.FalseBB) {
993 BBI.IsBeingAnalyzed = false;
994 BBI.IsAnalyzed = true;
995 BBStack.pop_back();
996 continue;
997 }
Evan Cheng7783f822007-06-08 09:36:04 +0000998
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000999 // Push the False and True blocks to the stack.
1000 State.SuccsAnalyzed = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001001 BBStack.push_back(*BBI.FalseBB);
1002 BBStack.push_back(*BBI.TrueBB);
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001003 continue;
1004 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +00001005
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001006 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1007 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +00001008
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001009 if (TrueBBI.IsDone && FalseBBI.IsDone) {
1010 BBI.IsBeingAnalyzed = false;
1011 BBI.IsAnalyzed = true;
1012 BBStack.pop_back();
1013 continue;
1014 }
1015
1016 SmallVector<MachineOperand, 4>
1017 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1018 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
1019
1020 unsigned Dups = 0;
1021 unsigned Dups2 = 0;
1022 bool TNeedSub = !TrueBBI.Predicate.empty();
1023 bool FNeedSub = !FalseBBI.Predicate.empty();
1024 bool Enqueued = false;
1025
1026 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1027
Kyle Butt491afad2016-08-18 22:09:25 +00001028 if (CanRevCond) {
1029 BBInfo TrueBBICalc, FalseBBICalc;
1030 if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
Kyle Buttce0196d2016-08-19 18:17:04 +00001031 TrueBBICalc, FalseBBICalc) &&
1032 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
1033 TrueBBICalc.ExtraCost),
1034 TrueBBICalc.ExtraCost2,
1035 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
1036 FalseBBICalc.ExtraCost),
1037 FalseBBICalc.ExtraCost2,
1038 Prediction) &&
1039 FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1040 /* IsTriangle */ false, /* RevCond */ false,
1041 /* hasCommonTail */ true) &&
1042 FeasibilityAnalysis(FalseBBI, RevCond,
1043 /* IsTriangle */ false, /* RevCond */ false,
1044 /* hasCommonTail */ true)) {
1045 // Diamond:
1046 // EBB
1047 // / \_
1048 // | |
1049 // TBB FBB
1050 // \ /
1051 // TailBB
1052 // Note TailBB can be empty.
1053 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1054 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1055 (bool) TrueBBICalc.ClobbersPred,
1056 (bool) FalseBBICalc.ClobbersPred));
1057 Enqueued = true;
Kyle Butt491afad2016-08-18 22:09:25 +00001058 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001059 }
1060
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001061 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1062 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1063 TrueBBI.ExtraCost2, Prediction) &&
1064 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1065 // Triangle:
1066 // EBB
1067 // | \_
1068 // | |
1069 // | TBB
1070 // | /
1071 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001072 Tokens.push_back(
1073 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001074 Enqueued = true;
1075 }
1076
1077 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1078 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1079 TrueBBI.ExtraCost2, Prediction) &&
1080 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001081 Tokens.push_back(
1082 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001083 Enqueued = true;
1084 }
1085
1086 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1087 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1088 TrueBBI.ExtraCost2, Prediction) &&
1089 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1090 // Simple (split, no rejoin):
1091 // EBB
1092 // | \_
1093 // | |
1094 // | TBB---> exit
1095 // |
1096 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001097 Tokens.push_back(
1098 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001099 Enqueued = true;
1100 }
1101
1102 if (CanRevCond) {
1103 // Try the other path...
1104 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1105 Prediction.getCompl()) &&
1106 MeetIfcvtSizeLimit(*FalseBBI.BB,
1107 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1108 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1109 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001110 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1111 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001112 Enqueued = true;
1113 }
1114
1115 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1116 Prediction.getCompl()) &&
1117 MeetIfcvtSizeLimit(*FalseBBI.BB,
1118 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +00001119 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +00001120 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001121 Tokens.push_back(
1122 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001123 Enqueued = true;
1124 }
1125
1126 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1127 MeetIfcvtSizeLimit(*FalseBBI.BB,
1128 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1129 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1130 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001131 Tokens.push_back(
1132 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001133 Enqueued = true;
1134 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001135 }
1136
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001137 BBI.IsEnqueued = Enqueued;
1138 BBI.IsBeingAnalyzed = false;
1139 BBI.IsAnalyzed = true;
1140 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001141 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001142}
1143
Matthias Braun2c931792016-08-17 02:51:57 +00001144/// Analyze all blocks and find entries for all if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001145void IfConverter::AnalyzeBlocks(
1146 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001147 for (MachineBasicBlock &MBB : MF)
Matthias Braun08f47042016-08-17 02:52:01 +00001148 AnalyzeBlock(MBB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001149
Evan Cheng20e05992007-06-01 00:12:12 +00001150 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +00001151 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001152}
1153
Matthias Braun2c931792016-08-17 02:51:57 +00001154/// Returns true either if ToMBB is the next block after MBB or that all the
1155/// intervening blocks are empty (given MBB can fall through to its next block).
Matthias Braun08f47042016-08-17 02:52:01 +00001156static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1157 MachineFunction::iterator PI = MBB.getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001158 MachineFunction::iterator I = std::next(PI);
Matthias Braun08f47042016-08-17 02:52:01 +00001159 MachineFunction::iterator TI = ToMBB.getIterator();
1160 MachineFunction::iterator E = MBB.getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001161 while (I != TI) {
1162 // Check isSuccessor to avoid case where the next block is empty, but
1163 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001164 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001165 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001166 PI = I++;
1167 }
Evan Cheng312b7232007-06-04 06:47:22 +00001168 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001169}
1170
Matthias Braun2c931792016-08-17 02:51:57 +00001171/// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1172/// can be if-converted. If predecessor is already enqueued, dequeue it!
Matthias Braun08f47042016-08-17 02:52:01 +00001173void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1174 for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001175 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Matthias Braun08f47042016-08-17 02:52:01 +00001176 if (PBBI.IsDone || PBBI.BB == &MBB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001177 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001178 PBBI.IsAnalyzed = false;
1179 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001180 }
1181}
1182
Matthias Braun2c931792016-08-17 02:51:57 +00001183/// Inserts an unconditional branch from \p MBB to \p ToMBB.
Matthias Braun08f47042016-08-17 02:52:01 +00001184static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
Evan Chengc2237ce2007-05-29 22:31:16 +00001185 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001186 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001187 SmallVector<MachineOperand, 0> NoCond;
Matthias Braun08f47042016-08-17 02:52:01 +00001188 TII->InsertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001189}
1190
Matthias Braun2c931792016-08-17 02:51:57 +00001191/// Remove true / false edges if either / both are no longer successors.
Evan Cheng288f1542007-06-08 22:01:07 +00001192void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001193 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001194 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001195 if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
Evan Cheng0598b2d2007-06-18 22:44:57 +00001196 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001197}
1198
Matthias Braund616ccc2013-10-11 19:04:37 +00001199/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Jonas Paulsson196986c2016-08-03 05:46:35 +00001200/// values defined in MI which are also live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001201static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Jonas Paulsson196986c2016-08-03 05:46:35 +00001202 const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1203 ->getSubtarget().getRegisterInfo();
1204
1205 // Before stepping forward past MI, remember which regs were live
1206 // before MI. This is needed to set the Undef flag only when reg is
1207 // dead.
1208 SparseSet<unsigned> LiveBeforeMI;
1209 LiveBeforeMI.setUniverse(TRI->getNumRegs());
Matthias Braunb1e05582016-08-17 02:51:59 +00001210 for (unsigned Reg : Redefs)
Jonas Paulsson196986c2016-08-03 05:46:35 +00001211 LiveBeforeMI.insert(Reg);
1212
Pete Cooper7605e372015-05-05 20:14:22 +00001213 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001214 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001215
Pete Cooper7605e372015-05-05 20:14:22 +00001216 // Now add the implicit uses for each of the clobbered values.
Matthias Braun08f47042016-08-17 02:52:01 +00001217 for (auto Clobber : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001218 // FIXME: Const cast here is nasty, but better than making StepForward
1219 // take a mutable instruction instead of const.
Matthias Braun08f47042016-08-17 02:52:01 +00001220 unsigned Reg = Clobber.first;
1221 MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
Pete Cooper27483912015-05-06 22:51:04 +00001222 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001223 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001224 if (Op.isRegMask()) {
1225 // First handle regmasks. They clobber any entries in the mask which
1226 // means that we need a def for those registers.
Matthias Braun08f47042016-08-17 02:52:01 +00001227 if (LiveBeforeMI.count(Reg))
1228 MIB.addReg(Reg, RegState::Implicit);
Pete Cooperce9ad752015-05-05 22:09:41 +00001229
1230 // We also need to add an implicit def of this register for the later
1231 // use to read from.
1232 // For the register allocator to have allocated a register clobbered
1233 // by the call which is used later, it must be the case that
1234 // the call doesn't return.
Matthias Braun08f47042016-08-17 02:52:01 +00001235 MIB.addReg(Reg, RegState::Implicit | RegState::Define);
Pete Cooperce9ad752015-05-05 22:09:41 +00001236 continue;
1237 }
1238 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001239 if (Op.isDead()) {
1240 // If we found a dead def, but it needs to be live, then remove the dead
1241 // flag.
1242 if (Redefs.contains(Op.getReg()))
1243 Op.setIsDead(false);
1244 }
Matthias Braun08f47042016-08-17 02:52:01 +00001245 if (LiveBeforeMI.count(Reg))
1246 MIB.addReg(Reg, RegState::Implicit);
Matthias Braund616ccc2013-10-11 19:04:37 +00001247 }
1248}
1249
Matthias Braun2c931792016-08-17 02:51:57 +00001250/// Remove kill flags from operands with a registers in the \p DontKill set.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001251static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001252 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001253 if (!O->isReg() || !O->isKill())
1254 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001255 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001256 O->setIsKill(false);
1257 }
1258}
1259
Matthias Braun2c931792016-08-17 02:51:57 +00001260/// Walks a range of machine instructions and removes kill flags for registers
1261/// in the \p DontKill set.
Matthias Braund616ccc2013-10-11 19:04:37 +00001262static void RemoveKills(MachineBasicBlock::iterator I,
1263 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001264 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001265 const MCRegisterInfo &MCRI) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001266 for (MachineInstr &MI : make_range(I, E))
1267 RemoveKills(MI, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001268}
1269
Matthias Braun2c931792016-08-17 02:51:57 +00001270/// If convert a simple (split, no rejoin) sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001271bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001272 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1273 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1274 BBInfo *CvtBBI = &TrueBBI;
1275 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001276
Owen Anderson4f6bf042008-08-14 22:49:33 +00001277 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001278 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001279 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001280
Matthias Braun08f47042016-08-17 02:52:01 +00001281 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1282 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001283 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001284 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001285 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001286 BBI.IsAnalyzed = false;
1287 CvtBBI->IsAnalyzed = false;
1288 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001289 }
Evan Chengd0e66912007-05-23 07:23:16 +00001290
Matthias Braun08f47042016-08-17 02:52:01 +00001291 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001292 // Conservatively abort if-conversion if BB's address is taken.
1293 return false;
1294
Evan Cheng3a51c852007-06-16 09:34:52 +00001295 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001296 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001297 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001298
Bob Wilson45814342010-06-19 05:33:57 +00001299 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001300 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001301 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001302 Redefs.addLiveIns(CvtMBB);
1303 Redefs.addLiveIns(NextMBB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001304
1305 // Compute a set of registers which must not be killed by instructions in
1306 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001307 DontKill.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001308 DontKill.addLiveIns(NextMBB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001309
Matthias Braun08f47042016-08-17 02:52:01 +00001310 if (CvtMBB.pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001311 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001312 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001313 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001314 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001315
1316 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1317 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001318 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001319 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001320 RemoveKills(CvtMBB.begin(), CvtMBB.end(), DontKill, *TRI);
1321 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001322
Evan Cheng92fb5452007-06-15 07:36:12 +00001323 // Merge converted block into entry block.
1324 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1325 MergeBlocks(BBI, *CvtBBI);
1326 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001327
Evan Chenge4ec9182007-06-06 02:08:52 +00001328 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001329 if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1330 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001331 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001332 // Now ifcvt'd block will look like this:
1333 // BB:
1334 // ...
1335 // t, f = cmp
1336 // if t op
1337 // b BBf
1338 //
1339 // We cannot further ifcvt this block because the unconditional branch
1340 // will have to be predicated on the new condition, that will not be
1341 // available if cmp executes.
1342 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001343 }
Evan Chenge26c0912007-05-21 22:22:58 +00001344
Evan Cheng288f1542007-06-08 22:01:07 +00001345 RemoveExtraEdges(BBI);
1346
Evan Chengd0e66912007-05-23 07:23:16 +00001347 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001348 if (!IterIfcvt)
1349 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001350 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001351 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001352
1353 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001354 return true;
1355}
1356
Matthias Braun2c931792016-08-17 02:51:57 +00001357/// If convert a triangle sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001358bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001359 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001360 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1361 BBInfo *CvtBBI = &TrueBBI;
1362 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001363 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001364
Owen Anderson4f6bf042008-08-14 22:49:33 +00001365 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001366 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001367 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001368
Matthias Braun08f47042016-08-17 02:52:01 +00001369 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1370 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001371 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001372 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001373 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001374 BBI.IsAnalyzed = false;
1375 CvtBBI->IsAnalyzed = false;
1376 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001377 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001378
Matthias Braun08f47042016-08-17 02:52:01 +00001379 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001380 // Conservatively abort if-conversion if BB's address is taken.
1381 return false;
1382
Evan Cheng3a51c852007-06-16 09:34:52 +00001383 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001384 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001385 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001386
Evan Cheng3a51c852007-06-16 09:34:52 +00001387 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001388 if (ReverseBranchCondition(*CvtBBI)) {
1389 // BB has been changed, modify its predecessors (except for this
1390 // one) so they don't get ifcvt'ed based on bad intel.
Matthias Braun08f47042016-08-17 02:52:01 +00001391 for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001392 if (PBB == BBI.BB)
1393 continue;
1394 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1395 if (PBBI.IsEnqueued) {
1396 PBBI.IsAnalyzed = false;
1397 PBBI.IsEnqueued = false;
1398 }
Evan Chengadd97762007-06-14 23:34:09 +00001399 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001400 }
1401 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001402
Bob Wilson45814342010-06-19 05:33:57 +00001403 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001404 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001405 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001406 Redefs.addLiveIns(CvtMBB);
1407 Redefs.addLiveIns(NextMBB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001408
Andrew Trick276dd452013-10-14 20:45:17 +00001409 DontKill.clear();
1410
Craig Topperc0196b12014-04-14 00:51:57 +00001411 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001412 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001413
Manman Renb6819182014-01-29 23:18:47 +00001414 if (HasEarlyExit) {
Matthias Braun08f47042016-08-17 02:52:01 +00001415 // Get probabilities before modifying CvtMBB and BBI.BB.
1416 CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1417 CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1418 BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1419 BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
Manman Renb6819182014-01-29 23:18:47 +00001420 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001421
Matthias Braun08f47042016-08-17 02:52:01 +00001422 if (CvtMBB.pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001423 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001424 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001425 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001426 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001427
1428 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1429 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001430 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001431 } else {
1432 // Predicate the 'true' block after removing its branch.
Matthias Braun08f47042016-08-17 02:52:01 +00001433 CvtBBI->NonPredSize -= TII->RemoveBranch(CvtMBB);
1434 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001435
Evan Cheng0598b2d2007-06-18 22:44:57 +00001436 // Now merge the entry of the triangle with the true block.
1437 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001438 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001439 }
1440
Evan Cheng312b7232007-06-04 06:47:22 +00001441 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001442 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001443 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1444 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001445 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001446 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001447
Cong Houd97c1002015-12-01 05:29:22 +00001448 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
Matthias Braun08f47042016-08-17 02:52:01 +00001449 // NewNext = New_Prob(BBI.BB, NextMBB) =
1450 // Prob(BBI.BB, NextMBB) +
1451 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
Cong Houd97c1002015-12-01 05:29:22 +00001452 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
Matthias Braun08f47042016-08-17 02:52:01 +00001453 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1454 auto NewTrueBB = getNextBlock(*BBI.BB);
Cong Houd97c1002015-12-01 05:29:22 +00001455 auto NewNext = BBNext + BBCvt * CvtNext;
David Majnemer42531262016-08-12 03:55:06 +00001456 auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001457 if (NewTrueBBIter != BBI.BB->succ_end())
1458 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001459
1460 auto NewFalse = BBCvt * CvtFalse;
1461 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1462 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001463 }
Evan Cheng7783f822007-06-08 09:36:04 +00001464
1465 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001466 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001467 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001468 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001469 bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001470 if (!isFallThrough) {
1471 // Only merge them if the true block does not fallthrough to the false
1472 // block. By not merging them, we make it possible to iteratively
1473 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001474 if (!HasEarlyExit &&
Matthias Braun08f47042016-08-17 02:52:01 +00001475 NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
1476 !NextMBB.hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001477 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001478 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001479 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001480 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001481 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001482 }
Evan Cheng7783f822007-06-08 09:36:04 +00001483 // Mixed predicated and unpredicated code. This cannot be iteratively
1484 // predicated.
1485 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001486 }
Evan Chenge26c0912007-05-21 22:22:58 +00001487
Evan Cheng288f1542007-06-08 22:01:07 +00001488 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001489
Evan Chengd0e66912007-05-23 07:23:16 +00001490 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001491 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001492 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001493 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001494 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001495 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001496 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001497
1498 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001499 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001500}
1501
Kyle Buttce0196d2016-08-19 18:17:04 +00001502/// If convert a diamond sub-CFG.
1503/// \p BBI is the head of the diamond
1504/// \p NumDups1 - number of shared instructions at the beginning of TrueBBI and
1505/// FalseBBI
1506/// \p NumDups2 - number of shared instructions at the end of TrueBBI and
1507/// FalseBBI
1508/// \p TClobbersPred - True if the true block clobbers the predicate in the
1509/// non-shared portion.
1510/// \p TClobbersPred - True if the false block clobbers the predicate in the
1511/// non-shared portion.
1512bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1513 unsigned NumDups1, unsigned NumDups2,
1514 bool TClobbersPred, bool FClobbersPred) {
1515 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1516 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1517 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1518 // True block must fall through or end with an unanalyzable terminator.
1519 if (!TailBB) {
1520 if (blockAlwaysFallThrough(TrueBBI))
1521 TailBB = FalseBBI.TrueBB;
1522 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1523 }
Evan Chenge26c0912007-05-21 22:22:58 +00001524
Evan Cheng51eb2c32007-06-18 08:37:25 +00001525 if (TrueBBI.IsDone || FalseBBI.IsDone ||
Kyle Buttce0196d2016-08-19 18:17:04 +00001526 TrueBBI.BB->pred_size() > 1 ||
1527 FalseBBI.BB->pred_size() > 1) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001528 // Something has changed. It's no longer safe to predicate these blocks.
1529 BBI.IsAnalyzed = false;
1530 TrueBBI.IsAnalyzed = false;
1531 FalseBBI.IsAnalyzed = false;
1532 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001533 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001534
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001535 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1536 // Conservatively abort if-conversion if either BB has its address taken.
1537 return false;
1538
Bob Wilson1e5da552010-06-29 00:55:23 +00001539 // Put the predicated instructions from the 'true' block before the
1540 // instructions from the 'false' block, unless the true block would clobber
1541 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001542 BBInfo *BBI1 = &TrueBBI;
1543 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001544 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001545 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001546 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001547 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1548 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001549
Evan Cheng3a51c852007-06-16 09:34:52 +00001550 // Figure out the more profitable ordering.
1551 bool DoSwap = false;
Kyle Butt491afad2016-08-18 22:09:25 +00001552 if (TClobbersPred && !FClobbersPred)
Evan Cheng3a51c852007-06-16 09:34:52 +00001553 DoSwap = true;
Kyle Butt491afad2016-08-18 22:09:25 +00001554 else if (TClobbersPred == FClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001555 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001556 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001557 }
1558 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001559 std::swap(BBI1, BBI2);
1560 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001561 }
Evan Cheng79484222007-06-05 23:46:14 +00001562
Evan Cheng51eb2c32007-06-18 08:37:25 +00001563 // Remove the conditional branch from entry to the blocks.
1564 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1565
Matthias Braun08f47042016-08-17 02:52:01 +00001566 MachineBasicBlock &MBB1 = *BBI1->BB;
1567 MachineBasicBlock &MBB2 = *BBI2->BB;
1568
Krzysztof Parzyszeka003b762016-08-11 18:42:06 +00001569 // Initialize the Redefs:
1570 // - BB2 live-in regs need implicit uses before being redefined by BB1
1571 // instructions.
1572 // - BB1 live-out regs need implicit uses before being redefined by BB2
1573 // instructions. We start with BB1 live-ins so we have the live-out regs
1574 // after tracking the BB1 instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001575 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001576 Redefs.addLiveIns(MBB1);
1577 Redefs.addLiveIns(MBB2);
Evan Chengf128bdc2010-06-16 07:35:02 +00001578
Evan Cheng51eb2c32007-06-18 08:37:25 +00001579 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001580 // Skip dbg_value instructions
Matthias Braun08f47042016-08-17 02:52:01 +00001581 MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1582 MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001583 BBI1->NonPredSize -= NumDups1;
1584 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001585
1586 // Skip past the dups on each side separately since there may be
1587 // differing dbg_value entries.
1588 for (unsigned i = 0; i < NumDups1; ++DI1) {
1589 if (!DI1->isDebugValue())
1590 ++i;
1591 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001592 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001593 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001594 if (!DI2->isDebugValue())
1595 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001596 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001597
Matthias Braund616ccc2013-10-11 19:04:37 +00001598 // Compute a set of registers which must not be killed by instructions in BB1:
1599 // This is everything used+live in BB2 after the duplicated instructions. We
1600 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001601 DontKill.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001602 for (const MachineInstr &MI :
1603 make_range(MBB2.rbegin(), MachineBasicBlock::reverse_iterator(DI2)))
Matthias Braunb1e05582016-08-17 02:51:59 +00001604 DontKill.stepBackward(MI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001605
Matthias Braun08f47042016-08-17 02:52:01 +00001606 for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
Pete Cooper7605e372015-05-05 20:14:22 +00001607 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
Matthias Braunb1e05582016-08-17 02:51:59 +00001608 Redefs.stepForward(MI, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001609 }
Matthias Braun08f47042016-08-17 02:52:01 +00001610 BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1611 MBB2.erase(MBB2.begin(), DI2);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001612
Kyle Buttce0196d2016-08-19 18:17:04 +00001613 // Remove branch from the 'true' block, unless it was not analyzable.
1614 // Non-analyzable branches need to be preserved, since in such cases,
1615 // the CFG structure is not an actual diamond (the join block may not
1616 // be present).
1617 if (BBI1->IsBrAnalyzable)
1618 BBI1->NonPredSize -= TII->RemoveBranch(MBB1);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001619 // Remove duplicated instructions.
Matthias Braun08f47042016-08-17 02:52:01 +00001620 DI1 = MBB1.end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001621 for (unsigned i = 0; i != NumDups2; ) {
1622 // NumDups2 only counted non-dbg_value instructions, so this won't
1623 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001624 assert(DI1 != MBB1.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001625 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001626 // skip dbg_value instructions
1627 if (!DI1->isDebugValue())
1628 ++i;
1629 }
Matthias Braun08f47042016-08-17 02:52:01 +00001630 MBB1.erase(DI1, MBB1.end());
Evan Cheng79484222007-06-05 23:46:14 +00001631
Matthias Braund616ccc2013-10-11 19:04:37 +00001632 // Kill flags in the true block for registers living into the false block
1633 // must be removed.
Matthias Braun08f47042016-08-17 02:52:01 +00001634 RemoveKills(MBB1.begin(), MBB1.end(), DontKill, *TRI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001635
Kyle Buttce0196d2016-08-19 18:17:04 +00001636 // Remove 'false' block branch (unless it was not analyzable), and find
1637 // the last instruction to predicate.
1638 if (BBI2->IsBrAnalyzable)
1639 BBI2->NonPredSize -= TII->RemoveBranch(MBB2);
1640 DI2 = MBB2.end();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001641 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001642 // NumDups2 only counted non-dbg_value instructions, so this won't
1643 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001644 assert(DI2 != MBB2.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001645 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001646 // skip dbg_value instructions
1647 if (!DI2->isDebugValue())
1648 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001649 }
Evan Cheng4266a792011-12-19 22:01:30 +00001650
1651 // Remember which registers would later be defined by the false block.
1652 // This allows us not to predicate instructions in the true block that would
1653 // later be re-defined. That is, rather than
1654 // subeq r0, r1, #1
1655 // addne r0, r1, #1
1656 // generate:
1657 // sub r0, r1, #1
1658 // addne r0, r1, #1
1659 SmallSet<unsigned, 4> RedefsByFalse;
1660 SmallSet<unsigned, 4> ExtUses;
Matthias Braun08f47042016-08-17 02:52:01 +00001661 if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1662 for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001663 if (FI.isDebugValue())
Evan Cheng4266a792011-12-19 22:01:30 +00001664 continue;
1665 SmallVector<unsigned, 4> Defs;
Matthias Braunb1e05582016-08-17 02:51:59 +00001666 for (const MachineOperand &MO : FI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001667 if (!MO.isReg())
1668 continue;
1669 unsigned Reg = MO.getReg();
1670 if (!Reg)
1671 continue;
1672 if (MO.isDef()) {
1673 Defs.push_back(Reg);
1674 } else if (!RedefsByFalse.count(Reg)) {
1675 // These are defined before ctrl flow reach the 'false' instructions.
1676 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001677 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1678 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001679 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001680 }
1681 }
1682
Matthias Braunb1e05582016-08-17 02:51:59 +00001683 for (unsigned Reg : Defs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001684 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001685 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1686 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001687 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001688 }
1689 }
1690 }
1691 }
1692
1693 // Predicate the 'true' block.
Matthias Braun08f47042016-08-17 02:52:01 +00001694 PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001695
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001696 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1697 // a non-predicated in BBI2, then we don't want to predicate the one from
1698 // BBI2. The reason is that if we merged these blocks, we would end up with
1699 // two predicated terminators in the same block.
Matthias Braun08f47042016-08-17 02:52:01 +00001700 if (!MBB2.empty() && (DI2 == MBB2.end())) {
1701 MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1702 MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1703 if (BBI1T != MBB1.end() && TII->isPredicated(*BBI1T) &&
1704 BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001705 --DI2;
1706 }
1707
Evan Cheng4266a792011-12-19 22:01:30 +00001708 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001709 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001710
Evan Cheng0598b2d2007-06-18 22:44:57 +00001711 // Merge the true block into the entry of the diamond.
Kyle Buttce0196d2016-08-19 18:17:04 +00001712 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1713 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001714
Bob Wilson2371f4f2009-05-13 23:25:24 +00001715 // If the if-converted block falls through or unconditionally branches into
1716 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001717 // fold the tail block in as well. Otherwise, unless it falls through to the
1718 // tail, add a unconditional branch to it.
1719 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001720 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001721 bool CanMergeTail = !TailBBI.HasFallThrough &&
1722 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001723 // The if-converted block can still have a predicated terminator
1724 // (e.g. a predicated return). If that is the case, we cannot merge
1725 // it with the tail block.
1726 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001727 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001728 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001729 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1730 // check if there are any other predecessors besides those.
1731 unsigned NumPreds = TailBB->pred_size();
1732 if (NumPreds > 1)
1733 CanMergeTail = false;
1734 else if (NumPreds == 1 && CanMergeTail) {
1735 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
Kyle Buttce0196d2016-08-19 18:17:04 +00001736 if (*PI != &MBB1 && *PI != &MBB2)
Bob Wilson1e5da552010-06-29 00:55:23 +00001737 CanMergeTail = false;
1738 }
1739 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001740 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001741 TailBBI.IsDone = true;
1742 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001743 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Matthias Braun08f47042016-08-17 02:52:01 +00001744 InsertUncondBranch(*BBI.BB, *TailBB, TII);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001745 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001746 }
Evan Chenge26c0912007-05-21 22:22:58 +00001747 }
1748
Bob Wilson1e5da552010-06-29 00:55:23 +00001749 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1750 // which can happen here if TailBB is unanalyzable and is merged, so
1751 // explicitly remove BBI1 and BBI2 as successors.
Kyle Buttce0196d2016-08-19 18:17:04 +00001752 BBI.BB->removeSuccessor(&MBB1);
1753 BBI.BB->removeSuccessor(&MBB2, true);
Evan Cheng288f1542007-06-08 22:01:07 +00001754 RemoveExtraEdges(BBI);
1755
Evan Cheng79484222007-06-05 23:46:14 +00001756 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001757 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001758 InvalidatePreds(*BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001759
1760 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001761 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001762}
1763
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001764static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001765 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001766 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001767 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001768 return false;
1769
Matthias Braunb1e05582016-08-17 02:51:59 +00001770 for (const MachineOperand &MO : MI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001771 if (!MO.isReg())
1772 continue;
1773 unsigned Reg = MO.getReg();
1774 if (!Reg)
1775 continue;
1776 if (MO.isDef() && !LaterRedefs.count(Reg))
1777 return false;
1778 }
1779
1780 return true;
1781}
1782
Matthias Braun2c931792016-08-17 02:51:57 +00001783/// Predicate instructions from the start of the block to the specified end with
1784/// the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001785void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001786 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001787 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001788 SmallSet<unsigned, 4> *LaterRedefs) {
1789 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001790 bool MaySpec = LaterRedefs != nullptr;
Matthias Braunb1e05582016-08-17 02:51:59 +00001791 for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001792 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001793 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001794 // It may be possible not to predicate an instruction if it's the 'true'
1795 // side of a diamond and the 'false' side may re-define the instruction's
1796 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001797 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001798 AnyUnpred = true;
1799 continue;
1800 }
1801 // If any instruction is predicated, then every instruction after it must
1802 // be predicated.
1803 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001804 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001805#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001806 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001807#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001808 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001809 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001810
Bob Wilson45814342010-06-19 05:33:57 +00001811 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001812 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001813 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001814 }
Evan Chengd0e66912007-05-23 07:23:16 +00001815
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001816 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001817
Evan Cheng92fb5452007-06-15 07:36:12 +00001818 BBI.IsAnalyzed = false;
1819 BBI.NonPredSize = 0;
1820
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001821 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001822 if (AnyUnpred)
1823 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001824}
1825
Matthias Braun2c931792016-08-17 02:51:57 +00001826/// Copy and predicate instructions from source BB to the destination block.
1827/// Skip end of block branches if IgnoreBr is true.
Evan Cheng92fb5452007-06-15 07:36:12 +00001828void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001829 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001830 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001831 MachineFunction &MF = *ToBBI.BB->getParent();
1832
Matthias Braun08f47042016-08-17 02:52:01 +00001833 MachineBasicBlock &FromMBB = *FromBBI.BB;
1834 for (MachineInstr &I : FromMBB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001835 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001836 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001837 break;
1838
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001839 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001840 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001841 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001842 unsigned ExtraPredCost = TII->getPredicationCost(I);
1843 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001844 if (NumCycles > 1)
1845 ToBBI.ExtraCost += NumCycles-1;
1846 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001847
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001848 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001849 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001850#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001851 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001852#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001853 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001854 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001855 }
1856
Bob Wilson45814342010-06-19 05:33:57 +00001857 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001858 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001859 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001860
1861 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001862 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001863 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001864 }
1865
Bob Wilson1e5da552010-06-29 00:55:23 +00001866 if (!IgnoreBr) {
Matthias Braun08f47042016-08-17 02:52:01 +00001867 std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
1868 FromMBB.succ_end());
1869 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00001870 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001871
Matthias Braunb1e05582016-08-17 02:51:59 +00001872 for (MachineBasicBlock *Succ : Succs) {
Bob Wilson1e5da552010-06-29 00:55:23 +00001873 // Fallthrough edge can't be transferred.
1874 if (Succ == FallThrough)
1875 continue;
1876 ToBBI.BB->addSuccessor(Succ);
1877 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001878 }
1879
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001880 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1881 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001882
1883 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1884 ToBBI.IsAnalyzed = false;
1885
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001886 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001887}
1888
Matthias Braun2c931792016-08-17 02:51:57 +00001889/// Move all instructions from FromBB to the end of ToBB. This will leave
1890/// FromBB as an empty block, so remove all of its successor edges except for
1891/// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
1892/// being moved, add those successor edges to ToBBI.
Bob Wilson1e5da552010-06-29 00:55:23 +00001893void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Matthias Braun08f47042016-08-17 02:52:01 +00001894 MachineBasicBlock &FromMBB = *FromBBI.BB;
1895 assert(!FromMBB.hasAddressTaken() &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001896 "Removing a BB whose address is taken!");
1897
Matthias Braun08f47042016-08-17 02:52:01 +00001898 // In case FromMBB contains terminators (e.g. return instruction),
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001899 // first move the non-terminator instructions, then the terminators.
Matthias Braun08f47042016-08-17 02:52:01 +00001900 MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001901 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
Matthias Braun08f47042016-08-17 02:52:01 +00001902 ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001903
1904 // If FromBB has non-predicated terminator we should copy it at the end.
Matthias Braun08f47042016-08-17 02:52:01 +00001905 if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001906 ToTI = ToBBI.BB->end();
Matthias Braun08f47042016-08-17 02:52:01 +00001907 ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
Evan Chengd0e66912007-05-23 07:23:16 +00001908
Cong Houb9e8d482015-12-17 01:29:08 +00001909 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1910 // unknown probabilities into known ones.
1911 // FIXME: This usage is too tricky and in the future we would like to
1912 // eliminate all unknown probabilities in MBB.
1913 ToBBI.BB->normalizeSuccProbs();
1914
Matthias Braun08f47042016-08-17 02:52:01 +00001915 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
1916 FromMBB.succ_end());
1917 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00001918 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Matthias Braun08f47042016-08-17 02:52:01 +00001919 // The edge probability from ToBBI.BB to FromMBB, which is only needed when
1920 // AddEdges is true and FromMBB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00001921 auto To2FromProb = BranchProbability::getZero();
Matthias Braun08f47042016-08-17 02:52:01 +00001922 if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
1923 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
1924 // Set the edge probability from ToBBI.BB to FromMBB to zero to avoid the
Cong Houd97c1002015-12-01 05:29:22 +00001925 // edge probability being merged to other edges when this edge is removed
1926 // later.
Matthias Braun08f47042016-08-17 02:52:01 +00001927 ToBBI.BB->setSuccProbability(find(ToBBI.BB->successors(), &FromMBB),
David Majnemer42531262016-08-12 03:55:06 +00001928 BranchProbability::getZero());
Cong Houd97c1002015-12-01 05:29:22 +00001929 }
1930
Matthias Braunb1e05582016-08-17 02:51:59 +00001931 for (MachineBasicBlock *Succ : FromSuccs) {
Evan Cheng288f1542007-06-08 22:01:07 +00001932 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001933 if (Succ == FallThrough)
1934 continue;
Cong Houd40105d2015-09-18 20:22:41 +00001935
Cong Houd97c1002015-12-01 05:29:22 +00001936 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00001937 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001938 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
Matthias Braun08f47042016-08-17 02:52:01 +00001939 // which is a portion of the edge probability from FromMBB to Succ. The
1940 // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
Cong Houd97c1002015-12-01 05:29:22 +00001941 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
Matthias Braun08f47042016-08-17 02:52:01 +00001942 NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001943
Matthias Braun08f47042016-08-17 02:52:01 +00001944 // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
1945 // only happens when if-converting a diamond CFG and FromMBB is the
1946 // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
1947 // could just use the probabilities on FromMBB's out-edges when adding
Cong Houd97c1002015-12-01 05:29:22 +00001948 // new successors.
1949 if (!To2FromProb.isZero())
1950 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00001951 }
1952
Matthias Braun08f47042016-08-17 02:52:01 +00001953 FromMBB.removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001954
1955 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001956 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00001957 // probability of this edge by adding NewProb to it. An example is shown
Matthias Braun08f47042016-08-17 02:52:01 +00001958 // below, in which A is ToBBI.BB and B is FromMBB. In this case we
Cong Houd97c1002015-12-01 05:29:22 +00001959 // don't have to set C as A's successor as it already is. We only need to
1960 // update the edge probability on A->C. Note that B will not be
1961 // immediately removed from A's successors. It is possible that B->D is
1962 // not removed either if D is a fallthrough of B. Later the edge A->D
1963 // (generated here) and B->D will be combined into one edge. To maintain
1964 // correct edge probability of this combined edge, we need to set the edge
1965 // probability of A->B to zero, which is already done above. The edge
1966 // probability on A->D is calculated by scaling the original probability
1967 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00001968 //
1969 // Before ifcvt: After ifcvt (assume B->D is kept):
1970 //
1971 // A A
1972 // /| /|\
1973 // / B / B|
1974 // | /| | ||
1975 // |/ | | |/
1976 // C D C D
1977 //
1978 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00001979 ToBBI.BB->setSuccProbability(
David Majnemer42531262016-08-12 03:55:06 +00001980 find(ToBBI.BB->successors(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00001981 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001982 else
Cong Houd97c1002015-12-01 05:29:22 +00001983 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001984 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001985 }
1986
Bob Wilson2371f4f2009-05-13 23:25:24 +00001987 // Now FromBBI always falls through to the next block!
Matthias Braun08f47042016-08-17 02:52:01 +00001988 if (NBB && !FromMBB.isSuccessor(NBB))
1989 FromMBB.addSuccessor(NBB);
Evan Cheng288f1542007-06-08 22:01:07 +00001990
Cong Houc1069892015-12-13 09:26:17 +00001991 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
1992 // we've done above.
1993 ToBBI.BB->normalizeSuccProbs();
1994
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001995 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001996 FromBBI.Predicate.clear();
1997
Evan Chengd0e66912007-05-23 07:23:16 +00001998 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001999 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00002000 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00002001 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002002 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00002003 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00002004
Evan Cheng4dd31a72007-06-11 22:26:22 +00002005 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00002006 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00002007 ToBBI.IsAnalyzed = false;
2008 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00002009}
Akira Hatanaka4a616192015-06-08 18:50:43 +00002010
2011FunctionPass *
2012llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00002013 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00002014}