blob: d225162860c249602a166b0ac391a706040b3364 [file] [log] [blame]
Evan Chengf5e53a52007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
Justin Lebaracc47102016-04-01 01:09:03 +000010// This file implements the machine instruction level if-conversion pass, which
11// tries to convert conditional branches into predicated instructions.
Evan Chengf5e53a52007-05-16 02:00:57 +000012//
13//===----------------------------------------------------------------------===//
14
Evan Chengf5e53a52007-05-16 02:00:57 +000015#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "BranchFolding.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000020#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000021#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000022#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000027#include "llvm/CodeGen/TargetSchedule.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000028#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000029#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000030#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000035#include "llvm/Target/TargetSubtargetInfo.h"
Cong Houd97c1002015-12-01 05:29:22 +000036#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000037#include <utility>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000038
Evan Chengf5e53a52007-05-16 02:00:57 +000039using namespace llvm;
40
Chandler Carruth1b9dde02014-04-22 02:02:50 +000041#define DEBUG_TYPE "ifcvt"
42
Chris Lattner769c86b2008-01-07 05:40:58 +000043// Hidden options for help debugging.
44static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
45static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
46static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000047static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000048 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000049static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000050 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000051static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000052 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000053static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000054 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000055static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000056 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000057static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000058 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000059static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000060 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000061static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
62 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000063
Evan Cheng2117d1f2007-06-09 01:03:43 +000064STATISTIC(NumSimple, "Number of simple if-conversions performed");
65STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
66STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000067STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000068STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
69STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
70STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
71STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000072STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000073STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000074
75namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000076 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000077 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000078 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000079 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000080 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
81 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000082 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000083 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000084 ICTriangle, // BB is entry of a triangle sub-CFG.
Evan Cheng4dd31a72007-06-11 22:26:22 +000085 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Chengf5e53a52007-05-16 02:00:57 +000086 };
87
88 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
89 /// if-conversion feasibility analysis. This includes results from
Jacques Pienaar71c30a12016-07-15 14:41:04 +000090 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000091 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000092 /// diamond shape), its size, whether it's predicable, and whether any
93 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000094 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +000095 /// IsDone - True if BB is not to be considered for ifcvt.
96 /// IsBeingAnalyzed - True if BB is currently being analyzed.
97 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
98 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
Jacques Pienaar71c30a12016-07-15 14:41:04 +000099 /// IsBrAnalyzable - True if analyzeBranch() returns false.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000100 /// HasFallThrough - True if BB may fallthrough to the following BB.
101 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000102 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000103 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000104 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000105 /// ExtraCost - Extra cost for multi-cycle instructions.
106 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000107 /// BB - Corresponding MachineBasicBlock.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000108 /// TrueBB / FalseBB- See analyzeBranch().
Evan Chengd0e66912007-05-23 07:23:16 +0000109 /// BrCond - Conditions for end of block conditional branches.
110 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000111 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000112 bool IsDone : 1;
113 bool IsBeingAnalyzed : 1;
114 bool IsAnalyzed : 1;
115 bool IsEnqueued : 1;
116 bool IsBrAnalyzable : 1;
117 bool HasFallThrough : 1;
118 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000119 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000120 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000121 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000122 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000123 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000124 MachineBasicBlock *BB;
125 MachineBasicBlock *TrueBB;
126 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000127 SmallVector<MachineOperand, 4> BrCond;
128 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000129 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000130 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
131 HasFallThrough(false), IsUnpredicable(false),
Evan Cheng23402fc2007-06-15 21:18:05 +0000132 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Craig Topperc0196b12014-04-14 00:51:57 +0000133 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
134 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000135 };
136
Bob Wilson59475732010-06-15 18:19:27 +0000137 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000138 /// BBI - Corresponding BBInfo.
139 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000140 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000141 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000142 /// NumDups - Number of instructions that would be duplicated due
143 /// to this if-conversion. (For diamonds, the number of
144 /// identical instructions at the beginnings of both
145 /// paths).
146 /// NumDups2 - For diamonds, the number of identical instructions
147 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000148 struct IfcvtToken {
149 BBInfo &BBI;
150 IfcvtKind Kind;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000151 bool NeedSubsumption;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000152 unsigned NumDups;
153 unsigned NumDups2;
154 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson2371f4f2009-05-13 23:25:24 +0000155 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000156 };
157
158 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
159 /// basic block number.
160 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000161 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000162
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000163 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000164 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000165 const TargetRegisterInfo *TRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000166 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000167 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000168
Juergen Ributzka310034e2013-12-14 06:52:56 +0000169 LivePhysRegs Redefs;
170 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000171
Evan Chengc5adcca2012-06-08 21:53:50 +0000172 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000173 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000174 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000175 std::function<bool(const Function &)> PredicateFtor;
176
Evan Chengf5e53a52007-05-16 02:00:57 +0000177 public:
178 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000179 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000180 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000181 initializeIfConverterPass(*PassRegistry::getPassRegistry());
182 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000183
Craig Topper4584cd52014-03-07 09:26:03 +0000184 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000185 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000186 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000187 MachineFunctionPass::getAnalysisUsage(AU);
188 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000189
Craig Topper4584cd52014-03-07 09:26:03 +0000190 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000191
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000192 MachineFunctionProperties getRequiredProperties() const override {
193 return MachineFunctionProperties().set(
194 MachineFunctionProperties::Property::AllVRegsAllocated);
195 }
196
Evan Chengf5e53a52007-05-16 02:00:57 +0000197 private:
Evan Cheng312b7232007-06-04 06:47:22 +0000198 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersonf31f33e2010-10-01 22:45:50 +0000199 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000200 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000201 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000202 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000203 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000204 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
205 unsigned &Dups1, unsigned &Dups2) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000206 void ScanInstructions(BBInfo &BBI);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000207 void AnalyzeBlock(MachineBasicBlock *MBB,
208 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000209 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng7783f822007-06-08 09:36:04 +0000210 bool isTriangle = false, bool RevBranch = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000211 void AnalyzeBlocks(MachineFunction &MF,
212 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000213 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000214 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000215 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
216 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000217 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
218 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000219 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000220 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000221 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000222 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000223 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000224 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000225 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000226 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000227
Evan Chengdebf9c52010-11-03 00:45:17 +0000228 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
229 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000230 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000231 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000232 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000233 }
234
Evan Chengdebf9c52010-11-03 00:45:17 +0000235 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
236 unsigned TCycle, unsigned TExtra,
237 MachineBasicBlock &FBB,
238 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000239 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000240 return TCycle > 0 && FCycle > 0 &&
241 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000242 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000243 }
244
Evan Chengbe9859e2007-06-07 02:12:15 +0000245 // blockAlwaysFallThrough - Block ends without a terminator.
246 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000247 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000248 }
249
Evan Cheng3a51c852007-06-16 09:34:52 +0000250 // IfcvtTokenCmp - Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000251 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
252 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000253 int Incr1 = (C1->Kind == ICDiamond)
254 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
255 int Incr2 = (C2->Kind == ICDiamond)
256 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
257 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000258 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000259 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000260 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000261 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000262 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000263 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000264 // Favors diamond over triangle, etc.
265 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
266 return true;
267 else if (C1->Kind == C2->Kind)
268 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
269 }
270 }
271 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000272 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000273 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000274
Evan Chengf5e53a52007-05-16 02:00:57 +0000275 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000276}
Evan Chengf5e53a52007-05-16 02:00:57 +0000277
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000278char &llvm::IfConverterID = IfConverter::ID;
279
Owen Anderson8ac477f2010-10-12 19:48:12 +0000280INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000281INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000282INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000283
Evan Chengf5e53a52007-05-16 02:00:57 +0000284bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000285 if (skipFunction(*MF.getFunction()) ||
286 (PredicateFtor && !PredicateFtor(*MF.getFunction())))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000287 return false;
288
Eric Christopher3d4276f2015-01-27 07:31:29 +0000289 const TargetSubtargetInfo &ST = MF.getSubtarget();
290 TLI = ST.getTargetLowering();
291 TII = ST.getInstrInfo();
292 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000293 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000294 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000295 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000296 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000297
Evan Chengf5e53a52007-05-16 02:00:57 +0000298 if (!TII) return false;
299
Evan Chengc5adcca2012-06-08 21:53:50 +0000300 PreRegAlloc = MRI->isSSA();
301
302 bool BFChange = false;
303 if (!PreRegAlloc) {
304 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000305 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000306 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000307 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000308 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000309
David Greene72e47cd2010-01-04 22:02:01 +0000310 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000311 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000312
313 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000314 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000315 return false;
316 }
David Greene72e47cd2010-01-04 22:02:01 +0000317 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000318
Evan Chengf5e53a52007-05-16 02:00:57 +0000319 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000320 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000321
Justin Lebar3a7bc572016-02-22 17:51:28 +0000322 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000323 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000324 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
325 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
326 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000327 // Do an initial analysis for each basic block and find all the potential
328 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000329 bool Change = false;
330 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000331 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000332 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000333 Tokens.pop_back();
334 BBInfo &BBI = Token->BBI;
335 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000336 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000337 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000338
Evan Cheng4dd31a72007-06-11 22:26:22 +0000339 // If the block has been evicted out of the queue or it has already been
340 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000341 if (BBI.IsDone)
342 BBI.IsEnqueued = false;
343 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000344 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000345
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000346 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000347
Evan Cheng312b7232007-06-04 06:47:22 +0000348 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000349 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000350 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000351 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000352 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000353 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000354 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000355 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
356 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000357 << "): BB#" << BBI.BB->getNumber() << " ("
358 << ((Kind == ICSimpleFalse)
359 ? BBI.FalseBB->getNumber()
360 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000361 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000362 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000363 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000364 if (isFalse) ++NumSimpleFalse;
365 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000366 }
Evan Cheng312b7232007-06-04 06:47:22 +0000367 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000368 }
Evan Chengd0e66912007-05-23 07:23:16 +0000369 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000370 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000371 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000372 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000373 bool isFalse = Kind == ICTriangleFalse;
374 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000375 if (DisableTriangle && !isFalse && !isRev) break;
376 if (DisableTriangleR && !isFalse && isRev) break;
377 if (DisableTriangleF && isFalse && !isRev) break;
378 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000379 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000380 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000381 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000382 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000383 DEBUG(dbgs() << " rev");
384 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000385 << BBI.TrueBB->getNumber() << ",F:"
386 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000387 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000388 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000389 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000390 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000391 if (isRev) ++NumTriangleFRev;
392 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000393 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000394 if (isRev) ++NumTriangleRev;
395 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000396 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000397 }
Evan Chengd0e66912007-05-23 07:23:16 +0000398 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000399 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000400 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000401 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000402 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000403 << BBI.TrueBB->getNumber() << ",F:"
404 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000405 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000406 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000407 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000408 break;
409 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000410 }
411
Evan Cheng312b7232007-06-04 06:47:22 +0000412 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000413
Evan Cheng92fb5452007-06-15 07:36:12 +0000414 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
415 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
416 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000417 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000418 }
Evan Chengd0e66912007-05-23 07:23:16 +0000419
Evan Chengd0e66912007-05-23 07:23:16 +0000420 if (!Change)
421 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000422 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000423 }
Evan Cheng478b8052007-05-18 01:55:58 +0000424
Evan Cheng3a51c852007-06-16 09:34:52 +0000425 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000426 BBAnalysis.clear();
427
Evan Chengcf9e8a92010-06-18 22:17:13 +0000428 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000429 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000430 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000431 getAnalysisIfAvailable<MachineModuleInfo>());
432 }
433
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000434 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000435 return MadeChange;
436}
437
Evan Cheng3a51c852007-06-16 09:34:52 +0000438/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
439/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000440static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000441 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000442 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
443 E = BB->succ_end(); SI != E; ++SI) {
444 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000445 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000446 return SuccBB;
447 }
Craig Topperc0196b12014-04-14 00:51:57 +0000448 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000449}
450
Evan Cheng3a51c852007-06-16 09:34:52 +0000451/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000452/// branch. Swap block's 'true' and 'false' successors.
Evan Cheng312b7232007-06-04 06:47:22 +0000453bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000454 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000455 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
456 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000457 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000458 std::swap(BBI.TrueBB, BBI.FalseBB);
459 return true;
460 }
461 return false;
462}
463
Evan Cheng2117d1f2007-06-09 01:03:43 +0000464/// getNextBlock - Returns the next block in the function blocks ordering. If
465/// it is the end, returns NULL.
466static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000467 MachineFunction::iterator I = BB->getIterator();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000468 MachineFunction::iterator E = BB->getParent()->end();
469 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000470 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000471 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000472}
473
Evan Cheng7783f822007-06-08 09:36:04 +0000474/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000475/// predecessor) forms a valid simple shape for ifcvt. It also returns the
476/// number of instructions that the ifcvt would need to duplicate if performed
477/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000478bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000479 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000480 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000481 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000482 return false;
483
Evan Chenga955c022007-06-19 21:45:13 +0000484 if (TrueBBI.IsBrAnalyzable)
485 return false;
486
Evan Cheng23402fc2007-06-15 21:18:05 +0000487 if (TrueBBI.BB->pred_size() > 1) {
488 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000489 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000490 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000491 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000492 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000493 }
494
Evan Chenga955c022007-06-19 21:45:13 +0000495 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000496}
497
Evan Cheng7783f822007-06-08 09:36:04 +0000498/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000499/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000500/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000501/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000502/// returns the number of instructions that the ifcvt would need to duplicate
503/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000504bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000505 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000506 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000507 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000508 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000509 return false;
510
Evan Cheng23402fc2007-06-15 21:18:05 +0000511 if (TrueBBI.BB->pred_size() > 1) {
512 if (TrueBBI.CannotBeCopied)
513 return false;
514
Evan Cheng92fb5452007-06-15 07:36:12 +0000515 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000516 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000517 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000518 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000519 --Size;
520 else {
521 MachineBasicBlock *FExit = FalseBranch
522 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
523 if (FExit)
524 // Require a conditional branch
525 ++Size;
526 }
527 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000528 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000529 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000530 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000531 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000532
Evan Cheng7783f822007-06-08 09:36:04 +0000533 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
534 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000535 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000536 if (++I == TrueBBI.BB->getParent()->end())
537 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000538 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000539 }
Evan Cheng7783f822007-06-08 09:36:04 +0000540 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000541}
542
Evan Cheng7783f822007-06-08 09:36:04 +0000543/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000544/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000545bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
546 unsigned &Dups1, unsigned &Dups2) const {
547 Dups1 = Dups2 = 0;
548 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
549 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000550 return false;
551
Evan Cheng2117d1f2007-06-09 01:03:43 +0000552 MachineBasicBlock *TT = TrueBBI.TrueBB;
553 MachineBasicBlock *FT = FalseBBI.TrueBB;
554
555 if (!TT && blockAlwaysFallThrough(TrueBBI))
556 TT = getNextBlock(TrueBBI.BB);
557 if (!FT && blockAlwaysFallThrough(FalseBBI))
558 FT = getNextBlock(FalseBBI.BB);
559 if (TT != FT)
560 return false;
Craig Topperc0196b12014-04-14 00:51:57 +0000561 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng2117d1f2007-06-09 01:03:43 +0000562 return false;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000563 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
564 return false;
565
566 // FIXME: Allow true block to have an early exit?
567 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
568 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000569 return false;
570
Bob Wilsone1961fe2010-10-26 00:02:24 +0000571 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach6201b992010-06-07 21:28:55 +0000572 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
573 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilsone1961fe2010-10-26 00:02:24 +0000574 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
575 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
576 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000577 // Skip dbg_value instructions. These do not count.
Bob Wilsone1961fe2010-10-26 00:02:24 +0000578 if (TIB->isDebugValue()) {
579 while (TIB != TIE && TIB->isDebugValue())
580 ++TIB;
581 if (TIB == TIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000582 break;
583 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000584 if (FIB->isDebugValue()) {
585 while (FIB != FIE && FIB->isDebugValue())
586 ++FIB;
587 if (FIB == FIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000588 break;
589 }
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000590 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000591 break;
592 ++Dups1;
593 ++TIB;
594 ++FIB;
595 }
596
597 // Now, in preparation for counting duplicate instructions at the ends of the
598 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000599 // If both blocks are returning don't skip the branches, since they will
600 // likely be both identical return instructions. In such cases the return
601 // can be left unpredicated.
602 // Check for already containing all of the block.
603 if (TIB == TIE || FIB == FIE)
604 return true;
605 --TIE;
606 --FIE;
607 if (!TrueBBI.BB->succ_empty() || !FalseBBI.BB->succ_empty()) {
608 while (TIE != TIB && TIE->isBranch())
609 --TIE;
610 while (FIE != FIB && FIE->isBranch())
611 --FIE;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000612 }
613
614 // If Dups1 includes all of a block, then don't count duplicate
615 // instructions at the end of the blocks.
616 if (TIB == TIE || FIB == FIE)
617 return true;
618
619 // Count duplicate instructions at the ends of the blocks.
620 while (TIE != TIB && FIE != FIB) {
621 // Skip dbg_value instructions. These do not count.
622 if (TIE->isDebugValue()) {
623 while (TIE != TIB && TIE->isDebugValue())
624 --TIE;
625 if (TIE == TIB)
626 break;
627 }
628 if (FIE->isDebugValue()) {
629 while (FIE != FIB && FIE->isDebugValue())
630 --FIE;
631 if (FIE == FIB)
632 break;
633 }
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000634 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000635 break;
636 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000637 --TIE;
638 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000639 }
640
641 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000642}
643
Evan Cheng4dd31a72007-06-11 22:26:22 +0000644/// ScanInstructions - Scan all the instructions in the block to determine if
645/// the block is predicable. In most cases, that means all the instructions
Chris Lattnera98c6792008-01-07 01:56:04 +0000646/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng4dd31a72007-06-11 22:26:22 +0000647/// instruction which can clobber a predicate (e.g. condition code register).
648/// If so, the block is not predicable unless it's the last instruction.
649void IfConverter::ScanInstructions(BBInfo &BBI) {
650 if (BBI.IsDone)
651 return;
652
Evan Chengc5adcca2012-06-08 21:53:50 +0000653 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000654 // First analyze the end of BB branches.
Craig Topperc0196b12014-04-14 00:51:57 +0000655 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000656 BBI.BrCond.clear();
657 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000658 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000659 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000660
661 if (BBI.BrCond.size()) {
662 // No false branch. This BB must end with a conditional branch and a
663 // fallthrough.
664 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000665 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000666 if (!BBI.FalseBB) {
667 // Malformed bcc? True and false blocks are the same?
668 BBI.IsUnpredicable = true;
669 return;
670 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000671 }
672
673 // Then scan all the instructions.
674 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000675 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000676 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000677 BBI.ClobbersPred = false;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000678 for (auto &MI : *BBI.BB) {
679 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000680 continue;
681
Justin Lebar7dba2e02016-04-15 01:38:41 +0000682 // It's unsafe to duplicate convergent instructions in this context, so set
683 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
684 // following CFG, which is subject to our "simple" transformation.
685 //
686 // BB0 // if (c1) goto BB1; else goto BB2;
687 // / \
688 // BB1 |
689 // | BB2 // if (c2) goto TBB; else goto FBB;
690 // | / |
691 // | / |
692 // TBB |
693 // | |
694 // | FBB
695 // |
696 // exit
697 //
698 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
699 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
700 // TBB contains a convergent instruction. This is safe iff doing so does
701 // not add a control-flow dependency to the convergent instruction -- i.e.,
702 // it's safe iff the set of control flows that leads us to the convergent
703 // instruction does not get smaller after the transformation.
704 //
705 // Originally we executed TBB if c1 || c2. After the transformation, there
706 // are two copies of TBB's instructions. We get to the first if c1, and we
707 // get to the second if !c1 && c2.
708 //
709 // There are clearly fewer ways to satisfy the condition "c1" than
710 // "c1 || c2". Since we've shrunk the set of control flows which lead to
711 // our convergent instruction, the transformation is unsafe.
712 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000713 BBI.CannotBeCopied = true;
714
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000715 bool isPredicated = TII->isPredicated(MI);
716 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000717
Joey Goulya5153cb2013-09-09 14:21:49 +0000718 // A conditional branch is not predicable, but it may be eliminated.
719 if (isCondBr)
720 continue;
721
722 if (!isPredicated) {
723 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000724 unsigned ExtraPredCost = TII->getPredicationCost(MI);
725 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000726 if (NumCycles > 1)
727 BBI.ExtraCost += NumCycles-1;
728 BBI.ExtraCost2 += ExtraPredCost;
729 } else if (!AlreadyPredicated) {
730 // FIXME: This instruction is already predicated before the
731 // if-conversion pass. It's probably something like a conditional move.
732 // Mark this block unpredicable for now.
733 BBI.IsUnpredicable = true;
734 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000735 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000736
737 if (BBI.ClobbersPred && !isPredicated) {
738 // Predicate modification instruction should end the block (except for
739 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000740 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000741 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000742 BBI.IsUnpredicable = true;
743 return;
744 }
745
Evan Chengfbc73092007-07-10 17:50:43 +0000746 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
747 // still potentially predicable.
748 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000749 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000750 BBI.ClobbersPred = true;
751
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000752 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000753 BBI.IsUnpredicable = true;
754 return;
755 }
756 }
757}
758
759/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
760/// predicated by the specified predicate.
761bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000762 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng4dd31a72007-06-11 22:26:22 +0000763 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000764 // If the block is dead or unpredicable, then it cannot be predicated.
765 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000766 return false;
767
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000768 // If it is already predicated but we couldn't analyze its terminator, the
769 // latter might fallthrough, but we can't determine where to.
770 // Conservatively avoid if-converting again.
771 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
772 return false;
773
Quentin Colombetbdab2272013-07-24 20:20:37 +0000774 // If it is already predicated, check if the new predicate subsumes
775 // its predicate.
776 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000777 return false;
778
779 if (BBI.BrCond.size()) {
780 if (!isTriangle)
781 return false;
782
Bob Wilson2371f4f2009-05-13 23:25:24 +0000783 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000784 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
785 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000786 if (RevBranch) {
787 if (TII->ReverseBranchCondition(Cond))
788 return false;
789 }
790 if (TII->ReverseBranchCondition(RevPred) ||
791 !TII->SubsumesPredicate(Cond, RevPred))
792 return false;
793 }
794
795 return true;
796}
797
Evan Cheng7783f822007-06-08 09:36:04 +0000798/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +0000799/// the specified block. Record its successors and whether it looks like an
800/// if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000801void IfConverter::AnalyzeBlock(
802 MachineBasicBlock *MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000803 struct BBState {
804 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
805 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000806
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000807 /// This flag is true if MBB's successors have been analyzed.
808 bool SuccsAnalyzed;
809 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000810
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000811 // Push MBB to the stack.
812 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000813
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000814 while (!BBStack.empty()) {
815 BBState &State = BBStack.back();
816 MachineBasicBlock *BB = State.MBB;
817 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000818
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000819 if (!State.SuccsAnalyzed) {
820 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
821 BBStack.pop_back();
822 continue;
823 }
Evan Cheng9030b982007-06-06 10:16:17 +0000824
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000825 BBI.BB = BB;
826 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000827
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000828 ScanInstructions(BBI);
Evan Chengb9bff582009-06-15 21:24:34 +0000829
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000830 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
831 // not considered for ifcvt anymore.
832 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
833 BBI.IsBeingAnalyzed = false;
834 BBI.IsAnalyzed = true;
835 BBStack.pop_back();
836 continue;
837 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000838
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000839 // Do not ifcvt if either path is a back edge to the entry block.
840 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
841 BBI.IsBeingAnalyzed = false;
842 BBI.IsAnalyzed = true;
843 BBStack.pop_back();
844 continue;
845 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000846
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000847 // Do not ifcvt if true and false fallthrough blocks are the same.
848 if (!BBI.FalseBB) {
849 BBI.IsBeingAnalyzed = false;
850 BBI.IsAnalyzed = true;
851 BBStack.pop_back();
852 continue;
853 }
Evan Cheng7783f822007-06-08 09:36:04 +0000854
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000855 // Push the False and True blocks to the stack.
856 State.SuccsAnalyzed = true;
857 BBStack.push_back(BBI.FalseBB);
858 BBStack.push_back(BBI.TrueBB);
859 continue;
860 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000861
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000862 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
863 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +0000864
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000865 if (TrueBBI.IsDone && FalseBBI.IsDone) {
866 BBI.IsBeingAnalyzed = false;
867 BBI.IsAnalyzed = true;
868 BBStack.pop_back();
869 continue;
870 }
871
872 SmallVector<MachineOperand, 4>
873 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
874 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
875
876 unsigned Dups = 0;
877 unsigned Dups2 = 0;
878 bool TNeedSub = !TrueBBI.Predicate.empty();
879 bool FNeedSub = !FalseBBI.Predicate.empty();
880 bool Enqueued = false;
881
882 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
883
884 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
885 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
886 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
887 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000888 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000889 Prediction) &&
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000890 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
891 FeasibilityAnalysis(FalseBBI, RevCond)) {
892 // Diamond:
893 // EBB
894 // / \_
895 // | |
896 // TBB FBB
897 // \ /
898 // TailBB
899 // Note TailBB can be empty.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000900 Tokens.push_back(llvm::make_unique<IfcvtToken>(
901 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
Evan Cheng3a51c852007-06-16 09:34:52 +0000902 Enqueued = true;
903 }
904
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000905 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
906 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
907 TrueBBI.ExtraCost2, Prediction) &&
908 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
909 // Triangle:
910 // EBB
911 // | \_
912 // | |
913 // | TBB
914 // | /
915 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000916 Tokens.push_back(
917 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000918 Enqueued = true;
919 }
920
921 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
922 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
923 TrueBBI.ExtraCost2, Prediction) &&
924 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000925 Tokens.push_back(
926 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000927 Enqueued = true;
928 }
929
930 if (ValidSimple(TrueBBI, Dups, Prediction) &&
931 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
932 TrueBBI.ExtraCost2, Prediction) &&
933 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
934 // Simple (split, no rejoin):
935 // EBB
936 // | \_
937 // | |
938 // | TBB---> exit
939 // |
940 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000941 Tokens.push_back(
942 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000943 Enqueued = true;
944 }
945
946 if (CanRevCond) {
947 // Try the other path...
948 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
949 Prediction.getCompl()) &&
950 MeetIfcvtSizeLimit(*FalseBBI.BB,
951 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
952 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
953 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000954 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
955 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000956 Enqueued = true;
957 }
958
959 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
960 Prediction.getCompl()) &&
961 MeetIfcvtSizeLimit(*FalseBBI.BB,
962 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000963 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000964 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000965 Tokens.push_back(
966 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000967 Enqueued = true;
968 }
969
970 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
971 MeetIfcvtSizeLimit(*FalseBBI.BB,
972 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
973 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
974 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000975 Tokens.push_back(
976 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000977 Enqueued = true;
978 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000979 }
980
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000981 BBI.IsEnqueued = Enqueued;
982 BBI.IsBeingAnalyzed = false;
983 BBI.IsAnalyzed = true;
984 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +0000985 }
Evan Cheng2e82cef2007-05-18 18:14:37 +0000986}
987
Evan Cheng905a8f42007-05-30 19:49:19 +0000988/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000989/// candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000990void IfConverter::AnalyzeBlocks(
991 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000992 for (auto &BB : MF)
993 AnalyzeBlock(&BB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +0000994
Evan Cheng20e05992007-06-01 00:12:12 +0000995 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +0000996 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +0000997}
998
Evan Cheng288f1542007-06-08 22:01:07 +0000999/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
1000/// that all the intervening blocks are empty (given BB can fall through to its
1001/// next block).
1002static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001003 MachineFunction::iterator PI = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001004 MachineFunction::iterator I = std::next(PI);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001005 MachineFunction::iterator TI = ToBB->getIterator();
Evan Cheng2c1acd62007-06-05 07:05:25 +00001006 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001007 while (I != TI) {
1008 // Check isSuccessor to avoid case where the next block is empty, but
1009 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001010 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001011 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001012 PI = I++;
1013 }
Evan Cheng312b7232007-06-04 06:47:22 +00001014 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001015}
1016
Evan Cheng51eb2c32007-06-18 08:37:25 +00001017/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
1018/// to determine if it can be if-converted. If predecessor is already enqueued,
1019/// dequeue it!
1020void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001021 for (const auto &Predecessor : BB->predecessors()) {
1022 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +00001023 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001024 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001025 PBBI.IsAnalyzed = false;
1026 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001027 }
1028}
1029
Evan Chengc2237ce2007-05-29 22:31:16 +00001030/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
1031///
1032static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
1033 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001034 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001035 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +00001036 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001037}
1038
Evan Cheng288f1542007-06-08 22:01:07 +00001039/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1040/// successors.
1041void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001042 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001043 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001044 if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
Evan Cheng0598b2d2007-06-18 22:44:57 +00001045 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001046}
1047
Matthias Braund616ccc2013-10-11 19:04:37 +00001048/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Peter Collingbourneaf567592016-06-24 18:57:29 +00001049/// values defined in MI which are not live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001050static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Pete Cooper7605e372015-05-05 20:14:22 +00001051 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001052 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001053
Pete Cooper7605e372015-05-05 20:14:22 +00001054 // Now add the implicit uses for each of the clobbered values.
1055 for (auto Reg : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001056 // FIXME: Const cast here is nasty, but better than making StepForward
1057 // take a mutable instruction instead of const.
Pete Cooper27483912015-05-06 22:51:04 +00001058 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1059 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001060 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001061 if (Op.isRegMask()) {
1062 // First handle regmasks. They clobber any entries in the mask which
1063 // means that we need a def for those registers.
Peter Collingbourneaf567592016-06-24 18:57:29 +00001064 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Pete Cooperce9ad752015-05-05 22:09:41 +00001065
1066 // We also need to add an implicit def of this register for the later
1067 // use to read from.
1068 // For the register allocator to have allocated a register clobbered
1069 // by the call which is used later, it must be the case that
1070 // the call doesn't return.
1071 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1072 continue;
1073 }
1074 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001075 if (Op.isDead()) {
1076 // If we found a dead def, but it needs to be live, then remove the dead
1077 // flag.
1078 if (Redefs.contains(Op.getReg()))
1079 Op.setIsDead(false);
1080 }
Peter Collingbourneaf567592016-06-24 18:57:29 +00001081 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Matthias Braund616ccc2013-10-11 19:04:37 +00001082 }
1083}
1084
1085/**
1086 * Remove kill flags from operands with a registers in the @p DontKill set.
1087 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001088static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001089 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001090 if (!O->isReg() || !O->isKill())
1091 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001092 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001093 O->setIsKill(false);
1094 }
1095}
1096
1097/**
1098 * Walks a range of machine instructions and removes kill flags for registers
1099 * in the @p DontKill set.
1100 */
1101static void RemoveKills(MachineBasicBlock::iterator I,
1102 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001103 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001104 const MCRegisterInfo &MCRI) {
1105 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001106 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001107}
1108
Evan Cheng312b7232007-06-04 06:47:22 +00001109/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001110///
Evan Cheng3a51c852007-06-16 09:34:52 +00001111bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001112 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1113 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1114 BBInfo *CvtBBI = &TrueBBI;
1115 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001116
Owen Anderson4f6bf042008-08-14 22:49:33 +00001117 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001118 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001119 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001120
Evan Cheng51eb2c32007-06-18 08:37:25 +00001121 if (CvtBBI->IsDone ||
1122 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001123 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001124 BBI.IsAnalyzed = false;
1125 CvtBBI->IsAnalyzed = false;
1126 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001127 }
Evan Chengd0e66912007-05-23 07:23:16 +00001128
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001129 if (CvtBBI->BB->hasAddressTaken())
1130 // Conservatively abort if-conversion if BB's address is taken.
1131 return false;
1132
Evan Cheng3a51c852007-06-16 09:34:52 +00001133 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001134 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001135 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001136
Bob Wilson45814342010-06-19 05:33:57 +00001137 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001138 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001139 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001140 Redefs.addLiveIns(*CvtBBI->BB);
1141 Redefs.addLiveIns(*NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001142
1143 // Compute a set of registers which must not be killed by instructions in
1144 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001145 DontKill.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001146 DontKill.addLiveIns(*NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001147
Evan Cheng92fb5452007-06-15 07:36:12 +00001148 if (CvtBBI->BB->pred_size() > 1) {
1149 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001150 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001151 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001152 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001153
1154 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1155 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001156 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001157 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001158 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001159 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001160
Evan Cheng92fb5452007-06-15 07:36:12 +00001161 // Merge converted block into entry block.
1162 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1163 MergeBlocks(BBI, *CvtBBI);
1164 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001165
Evan Chenge4ec9182007-06-06 02:08:52 +00001166 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001167 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001168 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001169 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001170 // Now ifcvt'd block will look like this:
1171 // BB:
1172 // ...
1173 // t, f = cmp
1174 // if t op
1175 // b BBf
1176 //
1177 // We cannot further ifcvt this block because the unconditional branch
1178 // will have to be predicated on the new condition, that will not be
1179 // available if cmp executes.
1180 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001181 }
Evan Chenge26c0912007-05-21 22:22:58 +00001182
Evan Cheng288f1542007-06-08 22:01:07 +00001183 RemoveExtraEdges(BBI);
1184
Evan Chengd0e66912007-05-23 07:23:16 +00001185 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001186 if (!IterIfcvt)
1187 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001188 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001189 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001190
1191 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001192 return true;
1193}
1194
Evan Chengaf716102007-05-16 21:54:37 +00001195/// IfConvertTriangle - If convert a triangle sub-CFG.
1196///
Evan Cheng3a51c852007-06-16 09:34:52 +00001197bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001198 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001199 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1200 BBInfo *CvtBBI = &TrueBBI;
1201 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001202 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001203
Owen Anderson4f6bf042008-08-14 22:49:33 +00001204 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001205 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001206 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001207
Evan Cheng51eb2c32007-06-18 08:37:25 +00001208 if (CvtBBI->IsDone ||
1209 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001210 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001211 BBI.IsAnalyzed = false;
1212 CvtBBI->IsAnalyzed = false;
1213 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001214 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001215
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001216 if (CvtBBI->BB->hasAddressTaken())
1217 // Conservatively abort if-conversion if BB's address is taken.
1218 return false;
1219
Evan Cheng3a51c852007-06-16 09:34:52 +00001220 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001221 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001222 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001223
Evan Cheng3a51c852007-06-16 09:34:52 +00001224 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001225 if (ReverseBranchCondition(*CvtBBI)) {
1226 // BB has been changed, modify its predecessors (except for this
1227 // one) so they don't get ifcvt'ed based on bad intel.
1228 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1229 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1230 MachineBasicBlock *PBB = *PI;
1231 if (PBB == BBI.BB)
1232 continue;
1233 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1234 if (PBBI.IsEnqueued) {
1235 PBBI.IsAnalyzed = false;
1236 PBBI.IsEnqueued = false;
1237 }
Evan Chengadd97762007-06-14 23:34:09 +00001238 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001239 }
1240 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001241
Bob Wilson45814342010-06-19 05:33:57 +00001242 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001243 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001244 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001245 Redefs.addLiveIns(*CvtBBI->BB);
1246 Redefs.addLiveIns(*NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001247
Andrew Trick276dd452013-10-14 20:45:17 +00001248 DontKill.clear();
1249
Craig Topperc0196b12014-04-14 00:51:57 +00001250 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001251 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001252
Manman Renb6819182014-01-29 23:18:47 +00001253 if (HasEarlyExit) {
Cong Houd97c1002015-12-01 05:29:22 +00001254 // Get probabilities before modifying CvtBBI->BB and BBI.BB.
1255 CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB);
1256 CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB);
1257 BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB);
1258 BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001259 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001260
Bob Wilson1e5da552010-06-29 00:55:23 +00001261 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001262 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001263 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001264 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001265 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001266
1267 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1268 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001269 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001270 } else {
1271 // Predicate the 'true' block after removing its branch.
1272 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001273 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001274
Evan Cheng0598b2d2007-06-18 22:44:57 +00001275 // Now merge the entry of the triangle with the true block.
1276 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001277 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001278 }
1279
Evan Cheng312b7232007-06-04 06:47:22 +00001280 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001281 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001282 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1283 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001284 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001285 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001286
Cong Houd97c1002015-12-01 05:29:22 +00001287 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1288 // NewNext = New_Prob(BBI.BB, NextBBI->BB) =
1289 // Prob(BBI.BB, NextBBI->BB) +
1290 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB)
1291 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1292 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB)
1293 auto NewTrueBB = getNextBlock(BBI.BB);
1294 auto NewNext = BBNext + BBCvt * CvtNext;
1295 auto NewTrueBBIter =
1296 std::find(BBI.BB->succ_begin(), BBI.BB->succ_end(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001297 if (NewTrueBBIter != BBI.BB->succ_end())
1298 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001299
1300 auto NewFalse = BBCvt * CvtFalse;
1301 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1302 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001303 }
Evan Cheng7783f822007-06-08 09:36:04 +00001304
1305 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001306 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001307 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001308 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001309 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001310 if (!isFallThrough) {
1311 // Only merge them if the true block does not fallthrough to the false
1312 // block. By not merging them, we make it possible to iteratively
1313 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001314 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001315 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1316 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001317 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001318 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001319 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001320 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1321 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001322 }
Evan Cheng7783f822007-06-08 09:36:04 +00001323 // Mixed predicated and unpredicated code. This cannot be iteratively
1324 // predicated.
1325 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001326 }
Evan Chenge26c0912007-05-21 22:22:58 +00001327
Evan Cheng288f1542007-06-08 22:01:07 +00001328 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001329
Evan Chengd0e66912007-05-23 07:23:16 +00001330 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001331 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001332 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001333 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001334 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001335 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001336 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001337
1338 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001339 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001340}
1341
Evan Chengaf716102007-05-16 21:54:37 +00001342/// IfConvertDiamond - If convert a diamond sub-CFG.
1343///
Evan Cheng51eb2c32007-06-18 08:37:25 +00001344bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1345 unsigned NumDups1, unsigned NumDups2) {
Evan Cheng312b7232007-06-04 06:47:22 +00001346 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2e82cef2007-05-18 18:14:37 +00001347 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng3a51c852007-06-16 09:34:52 +00001348 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson2371f4f2009-05-13 23:25:24 +00001349 // True block must fall through or end with an unanalyzable terminator.
Evan Cheng3a51c852007-06-16 09:34:52 +00001350 if (!TailBB) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001351 if (blockAlwaysFallThrough(TrueBBI))
1352 TailBB = FalseBBI.TrueBB;
1353 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Chengf5e53a52007-05-16 02:00:57 +00001354 }
Evan Chenge26c0912007-05-21 22:22:58 +00001355
Evan Cheng51eb2c32007-06-18 08:37:25 +00001356 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1357 TrueBBI.BB->pred_size() > 1 ||
1358 FalseBBI.BB->pred_size() > 1) {
1359 // Something has changed. It's no longer safe to predicate these blocks.
1360 BBI.IsAnalyzed = false;
1361 TrueBBI.IsAnalyzed = false;
1362 FalseBBI.IsAnalyzed = false;
1363 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001364 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001365
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001366 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1367 // Conservatively abort if-conversion if either BB has its address taken.
1368 return false;
1369
Bob Wilson1e5da552010-06-29 00:55:23 +00001370 // Put the predicated instructions from the 'true' block before the
1371 // instructions from the 'false' block, unless the true block would clobber
1372 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001373 BBInfo *BBI1 = &TrueBBI;
1374 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001375 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001376 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001377 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001378 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1379 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001380
Evan Cheng3a51c852007-06-16 09:34:52 +00001381 // Figure out the more profitable ordering.
1382 bool DoSwap = false;
1383 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1384 DoSwap = true;
1385 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001386 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001387 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001388 }
1389 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001390 std::swap(BBI1, BBI2);
1391 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001392 }
Evan Cheng79484222007-06-05 23:46:14 +00001393
Evan Cheng51eb2c32007-06-18 08:37:25 +00001394 // Remove the conditional branch from entry to the blocks.
1395 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1396
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001397 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001398 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001399 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001400 Redefs.addLiveIns(*BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001401
Evan Cheng51eb2c32007-06-18 08:37:25 +00001402 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001403 // Skip dbg_value instructions
Benjamin Kramer6b568962015-06-23 14:47:29 +00001404 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1405 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001406 BBI1->NonPredSize -= NumDups1;
1407 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001408
1409 // Skip past the dups on each side separately since there may be
1410 // differing dbg_value entries.
1411 for (unsigned i = 0; i < NumDups1; ++DI1) {
1412 if (!DI1->isDebugValue())
1413 ++i;
1414 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001415 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001416 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001417 if (!DI2->isDebugValue())
1418 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001419 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001420
Matthias Braund616ccc2013-10-11 19:04:37 +00001421 // Compute a set of registers which must not be killed by instructions in BB1:
1422 // This is everything used+live in BB2 after the duplicated instructions. We
1423 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001424 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001425 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1426 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001427 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001428 }
1429
1430 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1431 ++I) {
Pete Cooper7605e372015-05-05 20:14:22 +00001432 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1433 Redefs.stepForward(*I, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001434 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001435 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1436 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1437
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001438 // Remove branch from the 'true' block, unless it was not analyzable.
1439 // Non-analyzable branches need to be preserved, since in such cases,
1440 // the CFG structure is not an actual diamond (the join block may not
1441 // be present).
1442 if (BBI1->IsBrAnalyzable)
1443 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1444 // Remove duplicated instructions.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001445 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001446 for (unsigned i = 0; i != NumDups2; ) {
1447 // NumDups2 only counted non-dbg_value instructions, so this won't
1448 // run off the head of the list.
1449 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001450 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001451 // skip dbg_value instructions
1452 if (!DI1->isDebugValue())
1453 ++i;
1454 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001455 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001456
Matthias Braund616ccc2013-10-11 19:04:37 +00001457 // Kill flags in the true block for registers living into the false block
1458 // must be removed.
1459 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1460
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001461 // Remove 'false' block branch (unless it was not analyzable), and find
1462 // the last instruction to predicate.
1463 if (BBI2->IsBrAnalyzable)
1464 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001465 DI2 = BBI2->BB->end();
1466 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001467 // NumDups2 only counted non-dbg_value instructions, so this won't
1468 // run off the head of the list.
1469 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001470 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001471 // skip dbg_value instructions
1472 if (!DI2->isDebugValue())
1473 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001474 }
Evan Cheng4266a792011-12-19 22:01:30 +00001475
1476 // Remember which registers would later be defined by the false block.
1477 // This allows us not to predicate instructions in the true block that would
1478 // later be re-defined. That is, rather than
1479 // subeq r0, r1, #1
1480 // addne r0, r1, #1
1481 // generate:
1482 // sub r0, r1, #1
1483 // addne r0, r1, #1
1484 SmallSet<unsigned, 4> RedefsByFalse;
1485 SmallSet<unsigned, 4> ExtUses;
1486 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1487 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1488 if (FI->isDebugValue())
1489 continue;
1490 SmallVector<unsigned, 4> Defs;
1491 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1492 const MachineOperand &MO = FI->getOperand(i);
1493 if (!MO.isReg())
1494 continue;
1495 unsigned Reg = MO.getReg();
1496 if (!Reg)
1497 continue;
1498 if (MO.isDef()) {
1499 Defs.push_back(Reg);
1500 } else if (!RedefsByFalse.count(Reg)) {
1501 // These are defined before ctrl flow reach the 'false' instructions.
1502 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001503 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1504 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001505 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001506 }
1507 }
1508
1509 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1510 unsigned Reg = Defs[i];
1511 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001512 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1513 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001514 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001515 }
1516 }
1517 }
1518 }
1519
1520 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001521 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001522
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001523 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1524 // a non-predicated in BBI2, then we don't want to predicate the one from
1525 // BBI2. The reason is that if we merged these blocks, we would end up with
1526 // two predicated terminators in the same block.
1527 if (!BBI2->BB->empty() && (DI2 == BBI2->BB->end())) {
1528 MachineBasicBlock::iterator BBI1T = BBI1->BB->getFirstTerminator();
1529 MachineBasicBlock::iterator BBI2T = BBI2->BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001530 if (BBI1T != BBI1->BB->end() && TII->isPredicated(*BBI1T) &&
1531 BBI2T != BBI2->BB->end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001532 --DI2;
1533 }
1534
Evan Cheng4266a792011-12-19 22:01:30 +00001535 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001536 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001537
Evan Cheng0598b2d2007-06-18 22:44:57 +00001538 // Merge the true block into the entry of the diamond.
Craig Topperc0196b12014-04-14 00:51:57 +00001539 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1540 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001541
Bob Wilson2371f4f2009-05-13 23:25:24 +00001542 // If the if-converted block falls through or unconditionally branches into
1543 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001544 // fold the tail block in as well. Otherwise, unless it falls through to the
1545 // tail, add a unconditional branch to it.
1546 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001547 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001548 bool CanMergeTail = !TailBBI.HasFallThrough &&
1549 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001550 // The if-converted block can still have a predicated terminator
1551 // (e.g. a predicated return). If that is the case, we cannot merge
1552 // it with the tail block.
1553 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001554 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001555 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001556 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1557 // check if there are any other predecessors besides those.
1558 unsigned NumPreds = TailBB->pred_size();
1559 if (NumPreds > 1)
1560 CanMergeTail = false;
1561 else if (NumPreds == 1 && CanMergeTail) {
1562 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1563 if (*PI != BBI1->BB && *PI != BBI2->BB)
1564 CanMergeTail = false;
1565 }
1566 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001567 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001568 TailBBI.IsDone = true;
1569 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001570 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Evan Cheng0598b2d2007-06-18 22:44:57 +00001571 InsertUncondBranch(BBI.BB, TailBB, TII);
1572 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001573 }
Evan Chenge26c0912007-05-21 22:22:58 +00001574 }
1575
Bob Wilson1e5da552010-06-29 00:55:23 +00001576 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1577 // which can happen here if TailBB is unanalyzable and is merged, so
1578 // explicitly remove BBI1 and BBI2 as successors.
1579 BBI.BB->removeSuccessor(BBI1->BB);
Cong Houc1069892015-12-13 09:26:17 +00001580 BBI.BB->removeSuccessor(BBI2->BB, true);
Evan Cheng288f1542007-06-08 22:01:07 +00001581 RemoveExtraEdges(BBI);
1582
Evan Cheng79484222007-06-05 23:46:14 +00001583 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001584 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001585 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001586
1587 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001588 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001589}
1590
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001591static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001592 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001593 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001594 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001595 return false;
1596
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001597 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1598 const MachineOperand &MO = MI.getOperand(i);
Evan Cheng4266a792011-12-19 22:01:30 +00001599 if (!MO.isReg())
1600 continue;
1601 unsigned Reg = MO.getReg();
1602 if (!Reg)
1603 continue;
1604 if (MO.isDef() && !LaterRedefs.count(Reg))
1605 return false;
1606 }
1607
1608 return true;
1609}
1610
Evan Cheng51eb2c32007-06-18 08:37:25 +00001611/// PredicateBlock - Predicate instructions from the start of the block to the
1612/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001613void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001614 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001615 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001616 SmallSet<unsigned, 4> *LaterRedefs) {
1617 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001618 bool MaySpec = LaterRedefs != nullptr;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001619 for (MachineInstr &I : llvm::make_range(BBI.BB->begin(), E)) {
1620 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001621 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001622 // It may be possible not to predicate an instruction if it's the 'true'
1623 // side of a diamond and the 'false' side may re-define the instruction's
1624 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001625 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001626 AnyUnpred = true;
1627 continue;
1628 }
1629 // If any instruction is predicated, then every instruction after it must
1630 // be predicated.
1631 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001632 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001633#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001634 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001635#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001636 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001637 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001638
Bob Wilson45814342010-06-19 05:33:57 +00001639 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001640 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001641 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001642 }
Evan Chengd0e66912007-05-23 07:23:16 +00001643
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001644 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001645
Evan Cheng92fb5452007-06-15 07:36:12 +00001646 BBI.IsAnalyzed = false;
1647 BBI.NonPredSize = 0;
1648
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001649 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001650 if (AnyUnpred)
1651 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001652}
1653
Evan Cheng92fb5452007-06-15 07:36:12 +00001654/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1655/// the destination block. Skip end of block branches if IgnoreBr is true.
1656void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001657 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001658 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001659 MachineFunction &MF = *ToBBI.BB->getParent();
1660
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001661 for (auto &I : *FromBBI.BB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001662 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001663 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001664 break;
1665
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001666 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001667 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001668 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001669 unsigned ExtraPredCost = TII->getPredicationCost(I);
1670 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001671 if (NumCycles > 1)
1672 ToBBI.ExtraCost += NumCycles-1;
1673 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001674
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001675 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001676 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001677#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001678 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001679#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001680 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001681 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001682 }
1683
Bob Wilson45814342010-06-19 05:33:57 +00001684 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001685 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001686 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001687
1688 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001689 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001690 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001691 }
1692
Bob Wilson1e5da552010-06-29 00:55:23 +00001693 if (!IgnoreBr) {
1694 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1695 FromBBI.BB->succ_end());
1696 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001697 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001698
Bob Wilson1e5da552010-06-29 00:55:23 +00001699 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1700 MachineBasicBlock *Succ = Succs[i];
1701 // Fallthrough edge can't be transferred.
1702 if (Succ == FallThrough)
1703 continue;
1704 ToBBI.BB->addSuccessor(Succ);
1705 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001706 }
1707
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001708 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1709 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001710
1711 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1712 ToBBI.IsAnalyzed = false;
1713
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001714 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001715}
1716
Evan Cheng0f745da2007-05-18 00:20:58 +00001717/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00001718/// This will leave FromBB as an empty block, so remove all of its
1719/// successor edges except for the fall-through edge. If AddEdges is true,
1720/// i.e., when FromBBI's branch is being moved, add those successor edges to
1721/// ToBBI.
1722void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001723 assert(!FromBBI.BB->hasAddressTaken() &&
1724 "Removing a BB whose address is taken!");
1725
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001726 // In case FromBBI.BB contains terminators (e.g. return instruction),
1727 // first move the non-terminator instructions, then the terminators.
1728 MachineBasicBlock::iterator FromTI = FromBBI.BB->getFirstTerminator();
1729 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
1730 ToBBI.BB->splice(ToTI, FromBBI.BB, FromBBI.BB->begin(), FromTI);
1731
1732 // If FromBB has non-predicated terminator we should copy it at the end.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001733 if (FromTI != FromBBI.BB->end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001734 ToTI = ToBBI.BB->end();
1735 ToBBI.BB->splice(ToTI, FromBBI.BB, FromTI, FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00001736
Cong Houb9e8d482015-12-17 01:29:08 +00001737 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1738 // unknown probabilities into known ones.
1739 // FIXME: This usage is too tricky and in the future we would like to
1740 // eliminate all unknown probabilities in MBB.
1741 ToBBI.BB->normalizeSuccProbs();
1742
Cong Houd40105d2015-09-18 20:22:41 +00001743 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
1744 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00001745 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001746 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001747 // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001748 // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00001749 auto To2FromProb = BranchProbability::getZero();
Cong Houfa1917c2015-12-01 00:02:51 +00001750 if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
Cong Houd97c1002015-12-01 05:29:22 +00001751 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB);
1752 // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the
1753 // edge probability being merged to other edges when this edge is removed
1754 // later.
1755 ToBBI.BB->setSuccProbability(
1756 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB),
1757 BranchProbability::getZero());
1758 }
1759
Cong Houd40105d2015-09-18 20:22:41 +00001760 for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
1761 MachineBasicBlock *Succ = FromSuccs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00001762 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001763 if (Succ == FallThrough)
1764 continue;
Cong Houd40105d2015-09-18 20:22:41 +00001765
Cong Houd97c1002015-12-01 05:29:22 +00001766 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00001767 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001768 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
1769 // which is a portion of the edge probability from FromBBI.BB to Succ. The
1770 // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if
1771 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
1772 NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001773
Cong Houd97c1002015-12-01 05:29:22 +00001774 // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
Cong Houd40105d2015-09-18 20:22:41 +00001775 // only happens when if-converting a diamond CFG and FromBBI.BB is the
1776 // tail BB. In this case FromBBI.BB post-dominates ToBBI.BB and hence we
Cong Houd97c1002015-12-01 05:29:22 +00001777 // could just use the probabilities on FromBBI.BB's out-edges when adding
1778 // new successors.
1779 if (!To2FromProb.isZero())
1780 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00001781 }
1782
Evan Chengbe9859e2007-06-07 02:12:15 +00001783 FromBBI.BB->removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001784
1785 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001786 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00001787 // probability of this edge by adding NewProb to it. An example is shown
Cong Houd97c1002015-12-01 05:29:22 +00001788 // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we
1789 // don't have to set C as A's successor as it already is. We only need to
1790 // update the edge probability on A->C. Note that B will not be
1791 // immediately removed from A's successors. It is possible that B->D is
1792 // not removed either if D is a fallthrough of B. Later the edge A->D
1793 // (generated here) and B->D will be combined into one edge. To maintain
1794 // correct edge probability of this combined edge, we need to set the edge
1795 // probability of A->B to zero, which is already done above. The edge
1796 // probability on A->D is calculated by scaling the original probability
1797 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00001798 //
1799 // Before ifcvt: After ifcvt (assume B->D is kept):
1800 //
1801 // A A
1802 // /| /|\
1803 // / B / B|
1804 // | /| | ||
1805 // |/ | | |/
1806 // C D C D
1807 //
1808 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00001809 ToBBI.BB->setSuccProbability(
Cong Houd40105d2015-09-18 20:22:41 +00001810 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00001811 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001812 else
Cong Houd97c1002015-12-01 05:29:22 +00001813 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001814 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001815 }
1816
Bob Wilson2371f4f2009-05-13 23:25:24 +00001817 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00001818 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00001819 FromBBI.BB->addSuccessor(NBB);
1820
Cong Houc1069892015-12-13 09:26:17 +00001821 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
1822 // we've done above.
1823 ToBBI.BB->normalizeSuccProbs();
1824
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001825 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001826 FromBBI.Predicate.clear();
1827
Evan Chengd0e66912007-05-23 07:23:16 +00001828 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001829 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001830 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001831 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001832 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001833 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001834
Evan Cheng4dd31a72007-06-11 22:26:22 +00001835 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001836 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001837 ToBBI.IsAnalyzed = false;
1838 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001839}
Akira Hatanaka4a616192015-06-08 18:50:43 +00001840
1841FunctionPass *
1842llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00001843 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00001844}