blob: b17a253fe23fcd4463d50249e3c7f1ddb23bbe88 [file] [log] [blame]
Eugene Zelenkof1933322017-09-22 23:46:57 +00001//===- IfConversion.cpp - Machine code if conversion pass -----------------===//
Evan Chengf5e53a52007-05-16 02:00:57 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Evan Chengf5e53a52007-05-16 02:00:57 +00006//
7//===----------------------------------------------------------------------===//
8//
Justin Lebaracc47102016-04-01 01:09:03 +00009// This file implements the machine instruction level if-conversion pass, which
10// tries to convert conditional branches into predicated instructions.
Evan Chengf5e53a52007-05-16 02:00:57 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "BranchFolding.h"
15#include "llvm/ADT/STLExtras.h"
Kyle Buttd76755e2016-08-18 22:09:23 +000016#include "llvm/ADT/ScopeExit.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallSet.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/SparseSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/Statistic.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000021#include "llvm/ADT/iterator_range.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000023#include "llvm/CodeGen/MachineBasicBlock.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000024#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000025#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000026#include "llvm/CodeGen/MachineFunction.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000027#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000028#include "llvm/CodeGen/MachineInstr.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000029#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000031#include "llvm/CodeGen/MachineOperand.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000033#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000034#include "llvm/CodeGen/TargetLowering.h"
35#include "llvm/CodeGen/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000036#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000037#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000038#include "llvm/IR/DebugLoc.h"
39#include "llvm/MC/MCRegisterInfo.h"
40#include "llvm/Pass.h"
41#include "llvm/Support/BranchProbability.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000042#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000043#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000044#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/raw_ostream.h"
Cong Houd97c1002015-12-01 05:29:22 +000046#include <algorithm>
Eugene Zelenkof1933322017-09-22 23:46:57 +000047#include <cassert>
48#include <functional>
49#include <iterator>
50#include <memory>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000051#include <utility>
Eugene Zelenkof1933322017-09-22 23:46:57 +000052#include <vector>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000053
Evan Chengf5e53a52007-05-16 02:00:57 +000054using namespace llvm;
55
Matthias Braun1527baa2017-05-25 21:26:32 +000056#define DEBUG_TYPE "if-converter"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000057
Chris Lattner769c86b2008-01-07 05:40:58 +000058// Hidden options for help debugging.
59static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
60static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
61static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000062static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000063 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000064static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000065 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000066static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000067 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000068static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000069 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000070static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000071 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000072static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000073 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000074static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000075 cl::init(false), cl::Hidden);
Kyle Butta8c73712016-08-24 21:34:27 +000076static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
77 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000078static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
79 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000080
Evan Cheng2117d1f2007-06-09 01:03:43 +000081STATISTIC(NumSimple, "Number of simple if-conversions performed");
82STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
83STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000084STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000085STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
86STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
87STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
Kyle Butta8c73712016-08-24 21:34:27 +000088STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000089STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000090STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000091STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000092
93namespace {
Eugene Zelenkof1933322017-09-22 23:46:57 +000094
Nick Lewycky02d5f772009-10-25 06:33:48 +000095 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000096 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000097 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000098 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000099 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
100 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000101 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +0000102 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +0000103 ICTriangle, // BB is entry of a triangle sub-CFG.
Kyle Butta8c73712016-08-24 21:34:27 +0000104 ICDiamond, // BB is entry of a diamond sub-CFG.
105 ICForkedDiamond // BB is entry of an almost diamond sub-CFG, with a
106 // common tail that can be shared.
Evan Chengf5e53a52007-05-16 02:00:57 +0000107 };
108
Matthias Braun2c931792016-08-17 02:51:57 +0000109 /// One per MachineBasicBlock, this is used to cache the result
Evan Chengf5e53a52007-05-16 02:00:57 +0000110 /// if-conversion feasibility analysis. This includes results from
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000111 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +0000112 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +0000113 /// diamond shape), its size, whether it's predicable, and whether any
114 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +0000115 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +0000116 /// IsDone - True if BB is not to be considered for ifcvt.
117 /// IsBeingAnalyzed - True if BB is currently being analyzed.
118 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
119 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000120 /// IsBrAnalyzable - True if analyzeBranch() returns false.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000121 /// HasFallThrough - True if BB may fallthrough to the following BB.
122 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000123 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000124 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000125 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000126 /// ExtraCost - Extra cost for multi-cycle instructions.
127 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000128 /// BB - Corresponding MachineBasicBlock.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000129 /// TrueBB / FalseBB- See analyzeBranch().
Evan Chengd0e66912007-05-23 07:23:16 +0000130 /// BrCond - Conditions for end of block conditional branches.
131 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000132 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000133 bool IsDone : 1;
134 bool IsBeingAnalyzed : 1;
135 bool IsAnalyzed : 1;
136 bool IsEnqueued : 1;
137 bool IsBrAnalyzable : 1;
Kyle Butta8c73712016-08-24 21:34:27 +0000138 bool IsBrReversible : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000139 bool HasFallThrough : 1;
140 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000141 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000142 bool ClobbersPred : 1;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000143 unsigned NonPredSize = 0;
144 unsigned ExtraCost = 0;
145 unsigned ExtraCost2 = 0;
146 MachineBasicBlock *BB = nullptr;
147 MachineBasicBlock *TrueBB = nullptr;
148 MachineBasicBlock *FalseBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000149 SmallVector<MachineOperand, 4> BrCond;
150 SmallVector<MachineOperand, 4> Predicate;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000151
Evan Cheng3a51c852007-06-16 09:34:52 +0000152 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000153 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
Kyle Butta8c73712016-08-24 21:34:27 +0000154 IsBrReversible(false), HasFallThrough(false),
155 IsUnpredicable(false), CannotBeCopied(false),
Eugene Zelenkof1933322017-09-22 23:46:57 +0000156 ClobbersPred(false) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000157 };
158
Matthias Braun2c931792016-08-17 02:51:57 +0000159 /// Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000160 /// BBI - Corresponding BBInfo.
161 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000162 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000163 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000164 /// NumDups - Number of instructions that would be duplicated due
165 /// to this if-conversion. (For diamonds, the number of
166 /// identical instructions at the beginnings of both
167 /// paths).
168 /// NumDups2 - For diamonds, the number of identical instructions
169 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000170 struct IfcvtToken {
171 BBInfo &BBI;
172 IfcvtKind Kind;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000173 unsigned NumDups;
174 unsigned NumDups2;
Kyle Butt6262ca32016-08-24 21:34:24 +0000175 bool NeedSubsumption : 1;
176 bool TClobbersPred : 1;
177 bool FClobbersPred : 1;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000178
Kyle Butt6262ca32016-08-24 21:34:24 +0000179 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
180 bool tc = false, bool fc = false)
181 : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
182 TClobbersPred(tc), FClobbersPred(fc) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000183 };
184
Matthias Braun2c931792016-08-17 02:51:57 +0000185 /// Results of if-conversion feasibility analysis indexed by basic block
186 /// number.
Evan Chengf5e53a52007-05-16 02:00:57 +0000187 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000188 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000189
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000190 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000191 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000192 const TargetRegisterInfo *TRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000193 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000194 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000195
Juergen Ributzka310034e2013-12-14 06:52:56 +0000196 LivePhysRegs Redefs;
Andrew Trick276dd452013-10-14 20:45:17 +0000197
Evan Chengc5adcca2012-06-08 21:53:50 +0000198 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000199 bool MadeChange;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000200 int FnNum = -1;
Matthias Braun8b38ffa2016-10-24 23:23:02 +0000201 std::function<bool(const MachineFunction &)> PredicateFtor;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000202
Evan Chengf5e53a52007-05-16 02:00:57 +0000203 public:
204 static char ID;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000205
Matthias Braun8b38ffa2016-10-24 23:23:02 +0000206 IfConverter(std::function<bool(const MachineFunction &)> Ftor = nullptr)
Eugene Zelenkof1933322017-09-22 23:46:57 +0000207 : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000208 initializeIfConverterPass(*PassRegistry::getPassRegistry());
209 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000210
Craig Topper4584cd52014-03-07 09:26:03 +0000211 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000212 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000213 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000214 MachineFunctionPass::getAnalysisUsage(AU);
215 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000216
Craig Topper4584cd52014-03-07 09:26:03 +0000217 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000218
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000219 MachineFunctionProperties getRequiredProperties() const override {
220 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000221 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000222 }
223
Evan Chengf5e53a52007-05-16 02:00:57 +0000224 private:
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000225 bool reverseBranchCondition(BBInfo &BBI) const;
Owen Andersonf31f33e2010-10-01 22:45:50 +0000226 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000227 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000228 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000229 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000230 BranchProbability Prediction) const;
Kyle Butt6262ca32016-08-24 21:34:24 +0000231 bool CountDuplicatedInstructions(
232 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
233 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
234 unsigned &Dups1, unsigned &Dups2,
235 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
236 bool SkipUnconditionalBranches) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000237 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
Kyle Butt6262ca32016-08-24 21:34:24 +0000238 unsigned &Dups1, unsigned &Dups2,
239 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butta8c73712016-08-24 21:34:27 +0000240 bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
241 unsigned &Dups1, unsigned &Dups2,
242 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000243 void AnalyzeBranches(BBInfo &BBI);
244 void ScanInstructions(BBInfo &BBI,
245 MachineBasicBlock::iterator &Begin,
Kyle Butt6262ca32016-08-24 21:34:24 +0000246 MachineBasicBlock::iterator &End,
247 bool BranchUnpredicable = false) const;
248 bool RescanInstructions(
249 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
250 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
251 BBInfo &TrueBBI, BBInfo &FalseBBI) const;
Matthias Braun08f47042016-08-17 02:52:01 +0000252 void AnalyzeBlock(MachineBasicBlock &MBB,
Justin Lebar3a7bc572016-02-22 17:51:28 +0000253 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000254 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Pred,
Kyle Butt6262ca32016-08-24 21:34:24 +0000255 bool isTriangle = false, bool RevBranch = false,
256 bool hasCommonTail = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000257 void AnalyzeBlocks(MachineFunction &MF,
258 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Matthias Braun08f47042016-08-17 02:52:01 +0000259 void InvalidatePreds(MachineBasicBlock &MBB);
Evan Cheng3a51c852007-06-16 09:34:52 +0000260 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
261 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Kyle Butta8c73712016-08-24 21:34:27 +0000262 bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
263 unsigned NumDups1, unsigned NumDups2,
264 bool TClobbersPred, bool FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +0000265 bool RemoveBranch, bool MergeAddEdges);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000266 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
Kyle Butt6262ca32016-08-24 21:34:24 +0000267 unsigned NumDups1, unsigned NumDups2,
268 bool TClobbers, bool FClobbers);
Kyle Butta8c73712016-08-24 21:34:27 +0000269 bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
270 unsigned NumDups1, unsigned NumDups2,
271 bool TClobbers, bool FClobbers);
Evan Chengd0e66912007-05-23 07:23:16 +0000272 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000273 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000274 SmallVectorImpl<MachineOperand> &Cond,
Matthias Braunc6613872018-11-06 19:00:11 +0000275 SmallSet<MCPhysReg, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000276 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000277 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000278 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000279 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000280
Evan Chengdebf9c52010-11-03 00:45:17 +0000281 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
282 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000283 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000284 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000285 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000286 }
287
Evan Chengdebf9c52010-11-03 00:45:17 +0000288 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
289 unsigned TCycle, unsigned TExtra,
290 MachineBasicBlock &FBB,
291 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000292 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000293 return TCycle > 0 && FCycle > 0 &&
294 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000295 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000296 }
297
Matthias Braun2c931792016-08-17 02:51:57 +0000298 /// Returns true if Block ends without a terminator.
Evan Chengbe9859e2007-06-07 02:12:15 +0000299 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000300 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000301 }
302
Matthias Braun2c931792016-08-17 02:51:57 +0000303 /// Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000304 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
305 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000306 int Incr1 = (C1->Kind == ICDiamond)
307 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
308 int Incr2 = (C2->Kind == ICDiamond)
309 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
310 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000311 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000312 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000313 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000314 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000315 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000316 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000317 // Favors diamond over triangle, etc.
318 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
319 return true;
320 else if (C1->Kind == C2->Kind)
321 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
322 }
323 }
324 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000325 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000326 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000327
Eugene Zelenkof1933322017-09-22 23:46:57 +0000328} // end anonymous namespace
329
330char IfConverter::ID = 0;
Evan Chengf5e53a52007-05-16 02:00:57 +0000331
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000332char &llvm::IfConverterID = IfConverter::ID;
333
Matthias Braun1527baa2017-05-25 21:26:32 +0000334INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000335INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Matthias Braun1527baa2017-05-25 21:26:32 +0000336INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000337
Evan Chengf5e53a52007-05-16 02:00:57 +0000338bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000339 if (skipFunction(MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000340 return false;
341
Eric Christopher3d4276f2015-01-27 07:31:29 +0000342 const TargetSubtargetInfo &ST = MF.getSubtarget();
343 TLI = ST.getTargetLowering();
344 TII = ST.getInstrInfo();
345 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000346 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000347 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000348 MRI = &MF.getRegInfo();
Sanjay Patel0d7df362018-04-08 19:56:04 +0000349 SchedModel.init(&ST);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000350
Evan Chengf5e53a52007-05-16 02:00:57 +0000351 if (!TII) return false;
352
Evan Chengc5adcca2012-06-08 21:53:50 +0000353 PreRegAlloc = MRI->isSSA();
354
355 bool BFChange = false;
356 if (!PreRegAlloc) {
357 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000358 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000359 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000360 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000361 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000362
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000363 LLVM_DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
364 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000365
366 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000367 LLVM_DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000368 return false;
369 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000370 LLVM_DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000371
Evan Chengf5e53a52007-05-16 02:00:57 +0000372 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000373 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000374
Justin Lebar3a7bc572016-02-22 17:51:28 +0000375 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000376 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000377 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
378 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
379 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000380 // Do an initial analysis for each basic block and find all the potential
381 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000382 bool Change = false;
383 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000384 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000385 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000386 Tokens.pop_back();
387 BBInfo &BBI = Token->BBI;
388 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000389 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000390 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000391
Evan Cheng4dd31a72007-06-11 22:26:22 +0000392 // If the block has been evicted out of the queue or it has already been
393 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000394 if (BBI.IsDone)
395 BBI.IsEnqueued = false;
396 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000397 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000398
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000399 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000400
Evan Cheng312b7232007-06-04 06:47:22 +0000401 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000402 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000403 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000404 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000405 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000406 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000407 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000408 LLVM_DEBUG(dbgs() << "Ifcvt (Simple"
409 << (Kind == ICSimpleFalse ? " false" : "")
410 << "): " << printMBBReference(*BBI.BB) << " ("
411 << ((Kind == ICSimpleFalse) ? BBI.FalseBB->getNumber()
412 : BBI.TrueBB->getNumber())
413 << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000414 RetVal = IfConvertSimple(BBI, Kind);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000415 LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000416 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000417 if (isFalse) ++NumSimpleFalse;
418 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000419 }
Evan Cheng312b7232007-06-04 06:47:22 +0000420 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000421 }
Evan Chengd0e66912007-05-23 07:23:16 +0000422 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000423 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000424 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000425 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000426 bool isFalse = Kind == ICTriangleFalse;
427 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000428 if (DisableTriangle && !isFalse && !isRev) break;
429 if (DisableTriangleR && !isFalse && isRev) break;
430 if (DisableTriangleF && isFalse && !isRev) break;
431 if (DisableTriangleFR && isFalse && isRev) break;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000432 LLVM_DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000433 if (isFalse)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000434 LLVM_DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000435 if (isRev)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000436 LLVM_DEBUG(dbgs() << " rev");
437 LLVM_DEBUG(dbgs() << "): " << printMBBReference(*BBI.BB)
438 << " (T:" << BBI.TrueBB->getNumber()
439 << ",F:" << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000440 RetVal = IfConvertTriangle(BBI, Kind);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000441 LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000442 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000443 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000444 if (isRev) ++NumTriangleFRev;
445 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000446 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000447 if (isRev) ++NumTriangleRev;
448 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000449 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000450 }
Evan Chengd0e66912007-05-23 07:23:16 +0000451 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000452 }
Eugene Zelenkof1933322017-09-22 23:46:57 +0000453 case ICDiamond:
Evan Chenge93ccc02007-06-08 19:10:51 +0000454 if (DisableDiamond) break;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000455 LLVM_DEBUG(dbgs() << "Ifcvt (Diamond): " << printMBBReference(*BBI.BB)
456 << " (T:" << BBI.TrueBB->getNumber()
457 << ",F:" << BBI.FalseBB->getNumber() << ") ");
Kyle Butt6262ca32016-08-24 21:34:24 +0000458 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
459 Token->TClobbersPred,
460 Token->FClobbersPred);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000461 LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000462 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000463 break;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000464 case ICForkedDiamond:
Kyle Butta8c73712016-08-24 21:34:27 +0000465 if (DisableForkedDiamond) break;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000466 LLVM_DEBUG(dbgs() << "Ifcvt (Forked Diamond): "
467 << printMBBReference(*BBI.BB)
468 << " (T:" << BBI.TrueBB->getNumber()
469 << ",F:" << BBI.FalseBB->getNumber() << ") ");
Kyle Butta8c73712016-08-24 21:34:27 +0000470 RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
471 Token->TClobbersPred,
472 Token->FClobbersPred);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000473 LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Kyle Butta8c73712016-08-24 21:34:27 +0000474 if (RetVal) ++NumForkedDiamonds;
475 break;
476 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000477
Krzysztof Parzyszek6ca02b22017-09-14 15:53:11 +0000478 if (RetVal && MRI->tracksLiveness())
479 recomputeLivenessFlags(*BBI.BB);
480
Evan Cheng312b7232007-06-04 06:47:22 +0000481 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000482
Evan Cheng92fb5452007-06-15 07:36:12 +0000483 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
484 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
485 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000486 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000487 }
Evan Chengd0e66912007-05-23 07:23:16 +0000488
Evan Chengd0e66912007-05-23 07:23:16 +0000489 if (!Change)
490 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000491 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000492 }
Evan Cheng478b8052007-05-18 01:55:58 +0000493
Evan Cheng3a51c852007-06-16 09:34:52 +0000494 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000495 BBAnalysis.clear();
496
Evan Chengcf9e8a92010-06-18 22:17:13 +0000497 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000498 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000499 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000500 getAnalysisIfAvailable<MachineModuleInfo>());
501 }
502
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000503 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000504 return MadeChange;
505}
506
Matthias Braun2c931792016-08-17 02:51:57 +0000507/// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000508static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000509 MachineBasicBlock *TrueBB) {
Matthias Braunb1e05582016-08-17 02:51:59 +0000510 for (MachineBasicBlock *SuccBB : BB->successors()) {
Evan Cheng0f745da2007-05-18 00:20:58 +0000511 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000512 return SuccBB;
513 }
Craig Topperc0196b12014-04-14 00:51:57 +0000514 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000515}
516
Matthias Braun2c931792016-08-17 02:51:57 +0000517/// Reverse the condition of the end of the block branch. Swap block's 'true'
518/// and 'false' successors.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000519bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000520 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000521 if (!TII->reverseBranchCondition(BBI.BrCond)) {
522 TII->removeBranch(*BBI.BB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000523 TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000524 std::swap(BBI.TrueBB, BBI.FalseBB);
525 return true;
526 }
527 return false;
528}
529
Matthias Braun2c931792016-08-17 02:51:57 +0000530/// Returns the next block in the function blocks ordering. If it is the end,
531/// returns NULL.
Matthias Braun08f47042016-08-17 02:52:01 +0000532static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
533 MachineFunction::iterator I = MBB.getIterator();
534 MachineFunction::iterator E = MBB.getParent()->end();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000535 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000536 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000537 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000538}
539
Matthias Braun2c931792016-08-17 02:51:57 +0000540/// Returns true if the 'true' block (along with its predecessor) forms a valid
541/// simple shape for ifcvt. It also returns the number of instructions that the
542/// ifcvt would need to duplicate if performed in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000543bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000544 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000545 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000546 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000547 return false;
548
Evan Chenga955c022007-06-19 21:45:13 +0000549 if (TrueBBI.IsBrAnalyzable)
550 return false;
551
Evan Cheng23402fc2007-06-15 21:18:05 +0000552 if (TrueBBI.BB->pred_size() > 1) {
553 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000554 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000555 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000556 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000557 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000558 }
559
Evan Chenga955c022007-06-19 21:45:13 +0000560 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000561}
562
Matthias Braun2c931792016-08-17 02:51:57 +0000563/// Returns true if the 'true' and 'false' blocks (along with their common
564/// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
565/// true, it checks if 'true' block's false branch branches to the 'false' block
566/// rather than the other way around. It also returns the number of instructions
567/// that the ifcvt would need to duplicate if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000568bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000569 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000570 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000571 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000572 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000573 return false;
574
Evan Cheng23402fc2007-06-15 21:18:05 +0000575 if (TrueBBI.BB->pred_size() > 1) {
576 if (TrueBBI.CannotBeCopied)
577 return false;
578
Evan Cheng92fb5452007-06-15 07:36:12 +0000579 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000580 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000581 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000582 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000583 --Size;
584 else {
585 MachineBasicBlock *FExit = FalseBranch
586 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
587 if (FExit)
588 // Require a conditional branch
589 ++Size;
590 }
591 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000592 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000593 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000594 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000595 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000596
Evan Cheng7783f822007-06-08 09:36:04 +0000597 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
598 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000599 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000600 if (++I == TrueBBI.BB->getParent()->end())
601 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000602 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000603 }
Evan Cheng7783f822007-06-08 09:36:04 +0000604 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000605}
606
Kyle Butt4f0e2872016-08-06 01:52:33 +0000607/// Count duplicated instructions and move the iterators to show where they
608/// are.
609/// @param TIB True Iterator Begin
610/// @param FIB False Iterator Begin
611/// These two iterators initially point to the first instruction of the two
612/// blocks, and finally point to the first non-shared instruction.
613/// @param TIE True Iterator End
614/// @param FIE False Iterator End
615/// These two iterators initially point to End() for the two blocks() and
616/// finally point to the first shared instruction in the tail.
617/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
618/// two blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000619/// @param Dups1 count of duplicated instructions at the beginning of the 2
620/// blocks.
621/// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
622/// @param SkipUnconditionalBranches if true, Don't make sure that
623/// unconditional branches at the end of the blocks are the same. True is
624/// passed when the blocks are analyzable to allow for fallthrough to be
625/// handled.
626/// @return false if the shared portion prevents if conversion.
627bool IfConverter::CountDuplicatedInstructions(
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000628 MachineBasicBlock::iterator &TIB,
629 MachineBasicBlock::iterator &FIB,
630 MachineBasicBlock::iterator &TIE,
631 MachineBasicBlock::iterator &FIE,
632 unsigned &Dups1, unsigned &Dups2,
633 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
Kyle Butt6262ca32016-08-24 21:34:24 +0000634 bool SkipUnconditionalBranches) const {
Bob Wilsone1961fe2010-10-26 00:02:24 +0000635 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000636 // Skip dbg_value instructions. These do not count.
Florian Hahn3c8b8c92016-12-16 11:10:26 +0000637 TIB = skipDebugInstructionsForward(TIB, TIE);
Florian Hahn3c8b8c92016-12-16 11:10:26 +0000638 FIB = skipDebugInstructionsForward(FIB, FIE);
Kyle Buttc4614b32017-01-26 20:02:47 +0000639 if (TIB == TIE || FIB == FIE)
Kyle Buttfe916822016-08-06 01:52:31 +0000640 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000641 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000642 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000643 // A pred-clobbering instruction in the shared portion prevents
644 // if-conversion.
645 std::vector<MachineOperand> PredDefs;
646 if (TII->DefinesPredicate(*TIB, PredDefs))
647 return false;
Kyle Butt93e94e82016-09-02 01:20:06 +0000648 // If we get all the way to the branch instructions, don't count them.
649 if (!TIB->isBranch())
650 ++Dups1;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000651 ++TIB;
652 ++FIB;
653 }
654
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000655 // Check for already containing all of the block.
656 if (TIB == TIE || FIB == FIE)
Kyle Butt6262ca32016-08-24 21:34:24 +0000657 return true;
Kyle Buttd76755e2016-08-18 22:09:23 +0000658 // Now, in preparation for counting duplicate instructions at the ends of the
Kyle Buttc4614b32017-01-26 20:02:47 +0000659 // blocks, switch to reverse_iterators. Note that getReverse() returns an
660 // iterator that points to the same instruction, unlike std::reverse_iterator.
661 // We have to do our own shifting so that we get the same range.
662 MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
663 MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
664 const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
665 const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
Kyle Buttd76755e2016-08-18 22:09:23 +0000666
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000667 if (!TBB.succ_empty() || !FBB.succ_empty()) {
Kyle Butt6262ca32016-08-24 21:34:24 +0000668 if (SkipUnconditionalBranches) {
Kyle Buttc4614b32017-01-26 20:02:47 +0000669 while (RTIE != RTIB && RTIE->isUnconditionalBranch())
670 ++RTIE;
671 while (RFIE != RFIB && RFIE->isUnconditionalBranch())
672 ++RFIE;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000673 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000674 }
675
Bob Wilsone1961fe2010-10-26 00:02:24 +0000676 // Count duplicate instructions at the ends of the blocks.
Kyle Buttc4614b32017-01-26 20:02:47 +0000677 while (RTIE != RTIB && RFIE != RFIB) {
Bob Wilsone1961fe2010-10-26 00:02:24 +0000678 // Skip dbg_value instructions. These do not count.
Kyle Buttc4614b32017-01-26 20:02:47 +0000679 // Note that these are reverse iterators going forward.
680 RTIE = skipDebugInstructionsForward(RTIE, RTIB);
681 RFIE = skipDebugInstructionsForward(RFIE, RFIB);
682 if (RTIE == RTIB || RFIE == RFIB)
Kyle Buttfe916822016-08-06 01:52:31 +0000683 break;
Kyle Buttc4614b32017-01-26 20:02:47 +0000684 if (!RTIE->isIdenticalTo(*RFIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000685 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000686 // We have to verify that any branch instructions are the same, and then we
687 // don't count them toward the # of duplicate instructions.
Kyle Buttc4614b32017-01-26 20:02:47 +0000688 if (!RTIE->isBranch())
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000689 ++Dups2;
Kyle Buttc4614b32017-01-26 20:02:47 +0000690 ++RTIE;
691 ++RFIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000692 }
Kyle Buttc4614b32017-01-26 20:02:47 +0000693 TIE = std::next(RTIE.getReverse());
694 FIE = std::next(RFIE.getReverse());
Kyle Butt6262ca32016-08-24 21:34:24 +0000695 return true;
696}
697
698/// RescanInstructions - Run ScanInstructions on a pair of blocks.
699/// @param TIB - True Iterator Begin, points to first non-shared instruction
700/// @param FIB - False Iterator Begin, points to first non-shared instruction
701/// @param TIE - True Iterator End, points past last non-shared instruction
702/// @param FIE - False Iterator End, points past last non-shared instruction
703/// @param TrueBBI - BBInfo to update for the true block.
704/// @param FalseBBI - BBInfo to update for the false block.
705/// @returns - false if either block cannot be predicated or if both blocks end
706/// with a predicate-clobbering instruction.
707bool IfConverter::RescanInstructions(
708 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
709 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
710 BBInfo &TrueBBI, BBInfo &FalseBBI) const {
711 bool BranchUnpredicable = true;
712 TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
713 ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
714 if (TrueBBI.IsUnpredicable)
715 return false;
716 ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
717 if (FalseBBI.IsUnpredicable)
718 return false;
719 if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
720 return false;
721 return true;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000722}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000723
Kyle Butt092c4dd2016-08-29 18:27:12 +0000724#ifndef NDEBUG
725static void verifySameBranchInstructions(
726 MachineBasicBlock *MBB1,
727 MachineBasicBlock *MBB2) {
Kyle Buttc4614b32017-01-26 20:02:47 +0000728 const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
729 const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
730 MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
731 MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
732 while (E1 != B1 && E2 != B2) {
733 skipDebugInstructionsForward(E1, B1);
734 skipDebugInstructionsForward(E2, B2);
735 if (E1 == B1 && E2 == B2)
Kyle Butt092c4dd2016-08-29 18:27:12 +0000736 break;
737
Kyle Buttc4614b32017-01-26 20:02:47 +0000738 if (E1 == B1) {
Kyle Butt092c4dd2016-08-29 18:27:12 +0000739 assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
740 break;
741 }
Kyle Buttc4614b32017-01-26 20:02:47 +0000742 if (E2 == B2) {
Kyle Butt092c4dd2016-08-29 18:27:12 +0000743 assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
744 break;
745 }
746
747 if (E1->isBranch() || E2->isBranch())
748 assert(E1->isIdenticalTo(*E2) &&
749 "Branch mis-match, branch instructions don't match.");
750 else
751 break;
Kyle Buttc4614b32017-01-26 20:02:47 +0000752 ++E1;
753 ++E2;
Kyle Butt092c4dd2016-08-29 18:27:12 +0000754 }
755}
756#endif
757
Kyle Butta8c73712016-08-24 21:34:27 +0000758/// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
759/// with their common predecessor) form a diamond if a common tail block is
760/// extracted.
761/// While not strictly a diamond, this pattern would form a diamond if
762/// tail-merging had merged the shared tails.
763/// EBB
764/// _/ \_
765/// | |
766/// TBB FBB
767/// / \ / \
768/// FalseBB TrueBB FalseBB
769/// Currently only handles analyzable branches.
770/// Specifically excludes actual diamonds to avoid overlap.
771bool IfConverter::ValidForkedDiamond(
772 BBInfo &TrueBBI, BBInfo &FalseBBI,
773 unsigned &Dups1, unsigned &Dups2,
774 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
775 Dups1 = Dups2 = 0;
776 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
777 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
778 return false;
779
780 if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
781 return false;
782 // Don't IfConvert blocks that can't be folded into their predecessor.
783 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
784 return false;
785
786 // This function is specifically looking for conditional tails, as
787 // unconditional tails are already handled by the standard diamond case.
788 if (TrueBBI.BrCond.size() == 0 ||
789 FalseBBI.BrCond.size() == 0)
790 return false;
791
792 MachineBasicBlock *TT = TrueBBI.TrueBB;
793 MachineBasicBlock *TF = TrueBBI.FalseBB;
794 MachineBasicBlock *FT = FalseBBI.TrueBB;
795 MachineBasicBlock *FF = FalseBBI.FalseBB;
796
797 if (!TT)
798 TT = getNextBlock(*TrueBBI.BB);
799 if (!TF)
800 TF = getNextBlock(*TrueBBI.BB);
801 if (!FT)
802 FT = getNextBlock(*FalseBBI.BB);
803 if (!FF)
804 FF = getNextBlock(*FalseBBI.BB);
805
806 if (!TT || !TF)
807 return false;
808
809 // Check successors. If they don't match, bail.
810 if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
811 return false;
812
813 bool FalseReversed = false;
814 if (TF == FT && TT == FF) {
815 // If the branches are opposing, but we can't reverse, don't do it.
816 if (!FalseBBI.IsBrReversible)
817 return false;
818 FalseReversed = true;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000819 reverseBranchCondition(FalseBBI);
Kyle Butta8c73712016-08-24 21:34:27 +0000820 }
821 auto UnReverseOnExit = make_scope_exit([&]() {
822 if (FalseReversed)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000823 reverseBranchCondition(FalseBBI);
Kyle Butta8c73712016-08-24 21:34:27 +0000824 });
825
826 // Count duplicate instructions at the beginning of the true and false blocks.
827 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
828 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
829 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
830 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
831 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
832 *TrueBBI.BB, *FalseBBI.BB,
833 /* SkipUnconditionalBranches */ true))
834 return false;
835
836 TrueBBICalc.BB = TrueBBI.BB;
837 FalseBBICalc.BB = FalseBBI.BB;
838 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
839 return false;
840
841 // The size is used to decide whether to if-convert, and the shared portions
842 // are subtracted off. Because of the subtraction, we just use the size that
843 // was calculated by the original ScanInstructions, as it is correct.
844 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
845 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
846 return true;
847}
848
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000849/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
850/// with their common predecessor) forms a valid diamond shape for ifcvt.
Kyle Butt6262ca32016-08-24 21:34:24 +0000851bool IfConverter::ValidDiamond(
852 BBInfo &TrueBBI, BBInfo &FalseBBI,
853 unsigned &Dups1, unsigned &Dups2,
854 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000855 Dups1 = Dups2 = 0;
856 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
857 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
858 return false;
859
860 MachineBasicBlock *TT = TrueBBI.TrueBB;
861 MachineBasicBlock *FT = FalseBBI.TrueBB;
862
863 if (!TT && blockAlwaysFallThrough(TrueBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000864 TT = getNextBlock(*TrueBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000865 if (!FT && blockAlwaysFallThrough(FalseBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000866 FT = getNextBlock(*FalseBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000867 if (TT != FT)
868 return false;
869 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
870 return false;
871 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
872 return false;
873
874 // FIXME: Allow true block to have an early exit?
Kyle Butt6262ca32016-08-24 21:34:24 +0000875 if (TrueBBI.FalseBB || FalseBBI.FalseBB)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000876 return false;
877
878 // Count duplicate instructions at the beginning and end of the true and
879 // false blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000880 // Skip unconditional branches only if we are considering an analyzable
881 // diamond. Otherwise the branches must be the same.
882 bool SkipUnconditionalBranches =
883 TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000884 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
885 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
886 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
887 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
Kyle Butt6262ca32016-08-24 21:34:24 +0000888 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
889 *TrueBBI.BB, *FalseBBI.BB,
890 SkipUnconditionalBranches))
891 return false;
892
893 TrueBBICalc.BB = TrueBBI.BB;
894 FalseBBICalc.BB = FalseBBI.BB;
895 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
896 return false;
897 // The size is used to decide whether to if-convert, and the shared portions
898 // are subtracted off. Because of the subtraction, we just use the size that
899 // was calculated by the original ScanInstructions, as it is correct.
900 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
901 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000902 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000903}
904
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000905/// AnalyzeBranches - Look at the branches at the end of a block to determine if
906/// the block is predicable.
907void IfConverter::AnalyzeBranches(BBInfo &BBI) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000908 if (BBI.IsDone)
909 return;
910
Craig Topperc0196b12014-04-14 00:51:57 +0000911 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000912 BBI.BrCond.clear();
913 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000914 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Kyle Butta8c73712016-08-24 21:34:27 +0000915 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
916 BBI.IsBrReversible = (RevCond.size() == 0) ||
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000917 !TII->reverseBranchCondition(RevCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000918 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000919
920 if (BBI.BrCond.size()) {
921 // No false branch. This BB must end with a conditional branch and a
922 // fallthrough.
923 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000924 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000925 if (!BBI.FalseBB) {
926 // Malformed bcc? True and false blocks are the same?
927 BBI.IsUnpredicable = true;
Evan Chengb9bff582009-06-15 21:24:34 +0000928 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000929 }
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000930}
Evan Cheng4dd31a72007-06-11 22:26:22 +0000931
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000932/// ScanInstructions - Scan all the instructions in the block to determine if
933/// the block is predicable. In most cases, that means all the instructions
934/// in the block are isPredicable(). Also checks if the block contains any
935/// instruction which can clobber a predicate (e.g. condition code register).
936/// If so, the block is not predicable unless it's the last instruction.
937void IfConverter::ScanInstructions(BBInfo &BBI,
938 MachineBasicBlock::iterator &Begin,
Kyle Butt6262ca32016-08-24 21:34:24 +0000939 MachineBasicBlock::iterator &End,
940 bool BranchUnpredicable) const {
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000941 if (BBI.IsDone || BBI.IsUnpredicable)
942 return;
943
944 bool AlreadyPredicated = !BBI.Predicate.empty();
945
Evan Cheng4dd31a72007-06-11 22:26:22 +0000946 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000947 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000948 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000949 BBI.ClobbersPred = false;
Matthias Braunb1e05582016-08-17 02:51:59 +0000950 for (MachineInstr &MI : make_range(Begin, End)) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000951 if (MI.isDebugInstr())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000952 continue;
953
Justin Lebar7dba2e02016-04-15 01:38:41 +0000954 // It's unsafe to duplicate convergent instructions in this context, so set
955 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
956 // following CFG, which is subject to our "simple" transformation.
957 //
958 // BB0 // if (c1) goto BB1; else goto BB2;
959 // / \
960 // BB1 |
961 // | BB2 // if (c2) goto TBB; else goto FBB;
962 // | / |
963 // | / |
964 // TBB |
965 // | |
966 // | FBB
967 // |
968 // exit
969 //
970 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
971 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
972 // TBB contains a convergent instruction. This is safe iff doing so does
973 // not add a control-flow dependency to the convergent instruction -- i.e.,
974 // it's safe iff the set of control flows that leads us to the convergent
975 // instruction does not get smaller after the transformation.
976 //
977 // Originally we executed TBB if c1 || c2. After the transformation, there
978 // are two copies of TBB's instructions. We get to the first if c1, and we
979 // get to the second if !c1 && c2.
980 //
981 // There are clearly fewer ways to satisfy the condition "c1" than
982 // "c1 || c2". Since we've shrunk the set of control flows which lead to
983 // our convergent instruction, the transformation is unsafe.
984 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000985 BBI.CannotBeCopied = true;
986
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000987 bool isPredicated = TII->isPredicated(MI);
988 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000989
Kyle Butt6262ca32016-08-24 21:34:24 +0000990 if (BranchUnpredicable && MI.isBranch()) {
991 BBI.IsUnpredicable = true;
992 return;
993 }
994
Joey Goulya5153cb2013-09-09 14:21:49 +0000995 // A conditional branch is not predicable, but it may be eliminated.
996 if (isCondBr)
997 continue;
998
999 if (!isPredicated) {
1000 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001001 unsigned ExtraPredCost = TII->getPredicationCost(MI);
1002 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +00001003 if (NumCycles > 1)
1004 BBI.ExtraCost += NumCycles-1;
1005 BBI.ExtraCost2 += ExtraPredCost;
1006 } else if (!AlreadyPredicated) {
1007 // FIXME: This instruction is already predicated before the
1008 // if-conversion pass. It's probably something like a conditional move.
1009 // Mark this block unpredicable for now.
1010 BBI.IsUnpredicable = true;
1011 return;
Evan Cheng96c14572007-07-06 23:24:39 +00001012 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001013
1014 if (BBI.ClobbersPred && !isPredicated) {
1015 // Predicate modification instruction should end the block (except for
1016 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +00001017 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +00001018 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001019 BBI.IsUnpredicable = true;
1020 return;
1021 }
1022
Evan Chengfbc73092007-07-10 17:50:43 +00001023 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1024 // still potentially predicable.
1025 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001026 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001027 BBI.ClobbersPred = true;
1028
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001029 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001030 BBI.IsUnpredicable = true;
1031 return;
1032 }
1033 }
1034}
1035
Matthias Braun2c931792016-08-17 02:51:57 +00001036/// Determine if the block is a suitable candidate to be predicated by the
1037/// specified predicate.
Kyle Butt6262ca32016-08-24 21:34:24 +00001038/// @param BBI BBInfo for the block to check
1039/// @param Pred Predicate array for the branch that leads to BBI
1040/// @param isTriangle true if the Analysis is for a triangle
1041/// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1042/// case
1043/// @param hasCommonTail true if BBI shares a tail with a sibling block that
1044/// contains any instruction that would make the block unpredicable.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001045bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001046 SmallVectorImpl<MachineOperand> &Pred,
Kyle Butt6262ca32016-08-24 21:34:24 +00001047 bool isTriangle, bool RevBranch,
1048 bool hasCommonTail) {
Evan Cheng3a51c852007-06-16 09:34:52 +00001049 // If the block is dead or unpredicable, then it cannot be predicated.
Kyle Butt6262ca32016-08-24 21:34:24 +00001050 // Two blocks may share a common unpredicable tail, but this doesn't prevent
1051 // them from being if-converted. The non-shared portion is assumed to have
1052 // been checked
1053 if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001054 return false;
1055
Ahmed Bougacha7173b662015-03-21 01:23:15 +00001056 // If it is already predicated but we couldn't analyze its terminator, the
1057 // latter might fallthrough, but we can't determine where to.
1058 // Conservatively avoid if-converting again.
1059 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1060 return false;
1061
Quentin Colombetbdab2272013-07-24 20:20:37 +00001062 // If it is already predicated, check if the new predicate subsumes
1063 // its predicate.
1064 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001065 return false;
1066
Kyle Butt6262ca32016-08-24 21:34:24 +00001067 if (!hasCommonTail && BBI.BrCond.size()) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001068 if (!isTriangle)
1069 return false;
1070
Bob Wilson2371f4f2009-05-13 23:25:24 +00001071 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +00001072 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1073 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +00001074 if (RevBranch) {
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001075 if (TII->reverseBranchCondition(Cond))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001076 return false;
1077 }
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001078 if (TII->reverseBranchCondition(RevPred) ||
Evan Cheng4dd31a72007-06-11 22:26:22 +00001079 !TII->SubsumesPredicate(Cond, RevPred))
1080 return false;
1081 }
1082
1083 return true;
1084}
1085
Matthias Braun2c931792016-08-17 02:51:57 +00001086/// Analyze the structure of the sub-CFG starting from the specified block.
1087/// Record its successors and whether it looks like an if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001088void IfConverter::AnalyzeBlock(
Matthias Braun08f47042016-08-17 02:52:01 +00001089 MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001090 struct BBState {
Matthias Braun08f47042016-08-17 02:52:01 +00001091 BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001092 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +00001093
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001094 /// This flag is true if MBB's successors have been analyzed.
1095 bool SuccsAnalyzed;
1096 };
Evan Cheng0f745da2007-05-18 00:20:58 +00001097
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001098 // Push MBB to the stack.
1099 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001100
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001101 while (!BBStack.empty()) {
1102 BBState &State = BBStack.back();
1103 MachineBasicBlock *BB = State.MBB;
1104 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +00001105
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001106 if (!State.SuccsAnalyzed) {
1107 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1108 BBStack.pop_back();
1109 continue;
1110 }
Evan Cheng9030b982007-06-06 10:16:17 +00001111
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001112 BBI.BB = BB;
1113 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +00001114
Kyle Butt54bf3ce2016-08-06 01:52:34 +00001115 AnalyzeBranches(BBI);
1116 MachineBasicBlock::iterator Begin = BBI.BB->begin();
1117 MachineBasicBlock::iterator End = BBI.BB->end();
1118 ScanInstructions(BBI, Begin, End);
Evan Chengb9bff582009-06-15 21:24:34 +00001119
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001120 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1121 // not considered for ifcvt anymore.
1122 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1123 BBI.IsBeingAnalyzed = false;
1124 BBI.IsAnalyzed = true;
1125 BBStack.pop_back();
1126 continue;
1127 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001128
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001129 // Do not ifcvt if either path is a back edge to the entry block.
1130 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1131 BBI.IsBeingAnalyzed = false;
1132 BBI.IsAnalyzed = true;
1133 BBStack.pop_back();
1134 continue;
1135 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001136
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001137 // Do not ifcvt if true and false fallthrough blocks are the same.
1138 if (!BBI.FalseBB) {
1139 BBI.IsBeingAnalyzed = false;
1140 BBI.IsAnalyzed = true;
1141 BBStack.pop_back();
1142 continue;
1143 }
Evan Cheng7783f822007-06-08 09:36:04 +00001144
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001145 // Push the False and True blocks to the stack.
1146 State.SuccsAnalyzed = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001147 BBStack.push_back(*BBI.FalseBB);
1148 BBStack.push_back(*BBI.TrueBB);
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001149 continue;
1150 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +00001151
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001152 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1153 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +00001154
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001155 if (TrueBBI.IsDone && FalseBBI.IsDone) {
1156 BBI.IsBeingAnalyzed = false;
1157 BBI.IsAnalyzed = true;
1158 BBStack.pop_back();
1159 continue;
1160 }
1161
1162 SmallVector<MachineOperand, 4>
1163 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001164 bool CanRevCond = !TII->reverseBranchCondition(RevCond);
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001165
1166 unsigned Dups = 0;
1167 unsigned Dups2 = 0;
1168 bool TNeedSub = !TrueBBI.Predicate.empty();
1169 bool FNeedSub = !FalseBBI.Predicate.empty();
1170 bool Enqueued = false;
1171
1172 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1173
Kyle Butt6262ca32016-08-24 21:34:24 +00001174 if (CanRevCond) {
1175 BBInfo TrueBBICalc, FalseBBICalc;
Kyle Butta8c73712016-08-24 21:34:27 +00001176 auto feasibleDiamond = [&]() {
1177 bool MeetsSize = MeetIfcvtSizeLimit(
1178 *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1179 TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1180 *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1181 FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1182 Prediction);
1183 bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1184 /* IsTriangle */ false, /* RevCond */ false,
1185 /* hasCommonTail */ true);
1186 bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1187 /* IsTriangle */ false, /* RevCond */ false,
1188 /* hasCommonTail */ true);
1189 return MeetsSize && TrueFeasible && FalseFeasible;
1190 };
1191
Kyle Butt6262ca32016-08-24 21:34:24 +00001192 if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
Kyle Butta8c73712016-08-24 21:34:27 +00001193 TrueBBICalc, FalseBBICalc)) {
1194 if (feasibleDiamond()) {
1195 // Diamond:
1196 // EBB
1197 // / \_
1198 // | |
1199 // TBB FBB
1200 // \ /
1201 // TailBB
1202 // Note TailBB can be empty.
1203 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1204 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1205 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1206 Enqueued = true;
1207 }
1208 } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1209 TrueBBICalc, FalseBBICalc)) {
1210 if (feasibleDiamond()) {
1211 // ForkedDiamond:
1212 // if TBB and FBB have a common tail that includes their conditional
1213 // branch instructions, then we can If Convert this pattern.
1214 // EBB
1215 // _/ \_
1216 // | |
1217 // TBB FBB
1218 // / \ / \
1219 // FalseBB TrueBB FalseBB
1220 //
1221 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1222 BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1223 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1224 Enqueued = true;
1225 }
Kyle Butt6262ca32016-08-24 21:34:24 +00001226 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001227 }
1228
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001229 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1230 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1231 TrueBBI.ExtraCost2, Prediction) &&
1232 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1233 // Triangle:
1234 // EBB
1235 // | \_
1236 // | |
1237 // | TBB
1238 // | /
1239 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001240 Tokens.push_back(
1241 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001242 Enqueued = true;
1243 }
1244
1245 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1246 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1247 TrueBBI.ExtraCost2, Prediction) &&
1248 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001249 Tokens.push_back(
1250 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001251 Enqueued = true;
1252 }
1253
1254 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1255 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1256 TrueBBI.ExtraCost2, Prediction) &&
1257 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1258 // Simple (split, no rejoin):
1259 // EBB
1260 // | \_
1261 // | |
1262 // | TBB---> exit
1263 // |
1264 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001265 Tokens.push_back(
1266 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001267 Enqueued = true;
1268 }
1269
1270 if (CanRevCond) {
1271 // Try the other path...
1272 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1273 Prediction.getCompl()) &&
1274 MeetIfcvtSizeLimit(*FalseBBI.BB,
1275 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1276 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1277 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001278 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1279 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001280 Enqueued = true;
1281 }
1282
1283 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1284 Prediction.getCompl()) &&
1285 MeetIfcvtSizeLimit(*FalseBBI.BB,
1286 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +00001287 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +00001288 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001289 Tokens.push_back(
1290 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001291 Enqueued = true;
1292 }
1293
1294 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1295 MeetIfcvtSizeLimit(*FalseBBI.BB,
1296 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1297 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1298 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001299 Tokens.push_back(
1300 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001301 Enqueued = true;
1302 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001303 }
1304
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001305 BBI.IsEnqueued = Enqueued;
1306 BBI.IsBeingAnalyzed = false;
1307 BBI.IsAnalyzed = true;
1308 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001309 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001310}
1311
Matthias Braun2c931792016-08-17 02:51:57 +00001312/// Analyze all blocks and find entries for all if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001313void IfConverter::AnalyzeBlocks(
1314 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001315 for (MachineBasicBlock &MBB : MF)
Matthias Braun08f47042016-08-17 02:52:01 +00001316 AnalyzeBlock(MBB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001317
Evan Cheng20e05992007-06-01 00:12:12 +00001318 // Sort to favor more complex ifcvt scheme.
Fangrui Songefd94c52019-04-23 14:51:27 +00001319 llvm::stable_sort(Tokens, IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001320}
1321
Matthias Braun2c931792016-08-17 02:51:57 +00001322/// Returns true either if ToMBB is the next block after MBB or that all the
1323/// intervening blocks are empty (given MBB can fall through to its next block).
Matthias Braun08f47042016-08-17 02:52:01 +00001324static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1325 MachineFunction::iterator PI = MBB.getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001326 MachineFunction::iterator I = std::next(PI);
Matthias Braun08f47042016-08-17 02:52:01 +00001327 MachineFunction::iterator TI = ToMBB.getIterator();
1328 MachineFunction::iterator E = MBB.getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001329 while (I != TI) {
1330 // Check isSuccessor to avoid case where the next block is empty, but
1331 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001332 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001333 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001334 PI = I++;
1335 }
Mikael Holmen21c867c2017-05-10 13:06:13 +00001336 // Finally see if the last I is indeed a successor to PI.
1337 return PI->isSuccessor(&*I);
Evan Chenge26c0912007-05-21 22:22:58 +00001338}
1339
Matthias Braun2c931792016-08-17 02:51:57 +00001340/// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1341/// can be if-converted. If predecessor is already enqueued, dequeue it!
Matthias Braun08f47042016-08-17 02:52:01 +00001342void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1343 for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001344 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Matthias Braun08f47042016-08-17 02:52:01 +00001345 if (PBBI.IsDone || PBBI.BB == &MBB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001346 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001347 PBBI.IsAnalyzed = false;
1348 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001349 }
1350}
1351
Matthias Braun2c931792016-08-17 02:51:57 +00001352/// Inserts an unconditional branch from \p MBB to \p ToMBB.
Matthias Braun08f47042016-08-17 02:52:01 +00001353static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
Evan Chengc2237ce2007-05-29 22:31:16 +00001354 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001355 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001356 SmallVector<MachineOperand, 0> NoCond;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001357 TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001358}
1359
Matthias Braund616ccc2013-10-11 19:04:37 +00001360/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Jonas Paulsson196986c2016-08-03 05:46:35 +00001361/// values defined in MI which are also live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001362static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001363 const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
Jonas Paulsson196986c2016-08-03 05:46:35 +00001364
1365 // Before stepping forward past MI, remember which regs were live
1366 // before MI. This is needed to set the Undef flag only when reg is
1367 // dead.
Matthias Braunc6613872018-11-06 19:00:11 +00001368 SparseSet<MCPhysReg, identity<MCPhysReg>> LiveBeforeMI;
Jonas Paulsson196986c2016-08-03 05:46:35 +00001369 LiveBeforeMI.setUniverse(TRI->getNumRegs());
Matthias Braunb1e05582016-08-17 02:51:59 +00001370 for (unsigned Reg : Redefs)
Jonas Paulsson196986c2016-08-03 05:46:35 +00001371 LiveBeforeMI.insert(Reg);
1372
Matthias Braunc6613872018-11-06 19:00:11 +00001373 SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001374 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001375
Pete Cooper7605e372015-05-05 20:14:22 +00001376 // Now add the implicit uses for each of the clobbered values.
Matthias Braun08f47042016-08-17 02:52:01 +00001377 for (auto Clobber : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001378 // FIXME: Const cast here is nasty, but better than making StepForward
1379 // take a mutable instruction instead of const.
Matthias Braun08f47042016-08-17 02:52:01 +00001380 unsigned Reg = Clobber.first;
1381 MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
Pete Cooper27483912015-05-06 22:51:04 +00001382 MachineInstr *OpMI = Op.getParent();
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001383 MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001384 if (Op.isRegMask()) {
1385 // First handle regmasks. They clobber any entries in the mask which
1386 // means that we need a def for those registers.
Matthias Braun08f47042016-08-17 02:52:01 +00001387 if (LiveBeforeMI.count(Reg))
1388 MIB.addReg(Reg, RegState::Implicit);
Pete Cooperce9ad752015-05-05 22:09:41 +00001389
1390 // We also need to add an implicit def of this register for the later
1391 // use to read from.
1392 // For the register allocator to have allocated a register clobbered
1393 // by the call which is used later, it must be the case that
1394 // the call doesn't return.
Matthias Braun08f47042016-08-17 02:52:01 +00001395 MIB.addReg(Reg, RegState::Implicit | RegState::Define);
Pete Cooperce9ad752015-05-05 22:09:41 +00001396 continue;
1397 }
Matthias Braun08f47042016-08-17 02:52:01 +00001398 if (LiveBeforeMI.count(Reg))
1399 MIB.addReg(Reg, RegState::Implicit);
Krzysztof Parzyszekdcb1bca2016-09-28 20:07:41 +00001400 else {
1401 bool HasLiveSubReg = false;
1402 for (MCSubRegIterator S(Reg, TRI); S.isValid(); ++S) {
1403 if (!LiveBeforeMI.count(*S))
1404 continue;
1405 HasLiveSubReg = true;
1406 break;
1407 }
1408 if (HasLiveSubReg)
1409 MIB.addReg(Reg, RegState::Implicit);
1410 }
Matthias Braund616ccc2013-10-11 19:04:37 +00001411 }
1412}
1413
Matthias Braun2c931792016-08-17 02:51:57 +00001414/// If convert a simple (split, no rejoin) sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001415bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001416 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1417 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1418 BBInfo *CvtBBI = &TrueBBI;
1419 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001420
Owen Anderson4f6bf042008-08-14 22:49:33 +00001421 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001422 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001423 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001424
Matthias Braun08f47042016-08-17 02:52:01 +00001425 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1426 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001427 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001428 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001429 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001430 BBI.IsAnalyzed = false;
1431 CvtBBI->IsAnalyzed = false;
1432 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001433 }
Evan Chengd0e66912007-05-23 07:23:16 +00001434
Matthias Braun08f47042016-08-17 02:52:01 +00001435 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001436 // Conservatively abort if-conversion if BB's address is taken.
1437 return false;
1438
Evan Cheng3a51c852007-06-16 09:34:52 +00001439 if (Kind == ICSimpleFalse)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001440 if (TII->reverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001441 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001442
Matthias Braun0c989a82016-12-08 00:15:51 +00001443 Redefs.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001444
1445 if (MRI->tracksLiveness()) {
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +00001446 // Initialize liveins to the first BB. These are potentially redefined by
Matthias Braun11723322017-01-05 20:01:19 +00001447 // predicated instructions.
1448 Redefs.addLiveIns(CvtMBB);
1449 Redefs.addLiveIns(NextMBB);
Matthias Braun11723322017-01-05 20:01:19 +00001450 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001451
Mikael Holmen45bd32f2017-06-26 09:33:04 +00001452 // Remove the branches from the entry so we can add the contents of the true
1453 // block to it.
1454 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1455
Matthias Braun08f47042016-08-17 02:52:01 +00001456 if (CvtMBB.pred_size() > 1) {
Bob Wilson2371f4f2009-05-13 23:25:24 +00001457 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001458 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001459 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001460
Mikael Holmen8b106802017-08-11 06:57:08 +00001461 // Keep the CFG updated.
Matthias Braun08f47042016-08-17 02:52:01 +00001462 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001463 } else {
Mikael Holmen45bd32f2017-06-26 09:33:04 +00001464 // Predicate the instructions in the true block.
Matthias Braun08f47042016-08-17 02:52:01 +00001465 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001466
Mikael Holmen8b106802017-08-11 06:57:08 +00001467 // Merge converted block into entry block. The BB to Cvt edge is removed
1468 // by MergeBlocks.
Evan Cheng92fb5452007-06-15 07:36:12 +00001469 MergeBlocks(BBI, *CvtBBI);
1470 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001471
Evan Chenge4ec9182007-06-06 02:08:52 +00001472 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001473 if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1474 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001475 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001476 // Now ifcvt'd block will look like this:
1477 // BB:
1478 // ...
1479 // t, f = cmp
1480 // if t op
1481 // b BBf
1482 //
1483 // We cannot further ifcvt this block because the unconditional branch
1484 // will have to be predicated on the new condition, that will not be
1485 // available if cmp executes.
1486 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001487 }
Evan Chenge26c0912007-05-21 22:22:58 +00001488
Evan Chengd0e66912007-05-23 07:23:16 +00001489 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001490 if (!IterIfcvt)
1491 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001492 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001493 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001494
1495 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001496 return true;
1497}
1498
Matthias Braun2c931792016-08-17 02:51:57 +00001499/// If convert a triangle sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001500bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001501 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001502 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1503 BBInfo *CvtBBI = &TrueBBI;
1504 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001505 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001506
Owen Anderson4f6bf042008-08-14 22:49:33 +00001507 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001508 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001509 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001510
Matthias Braun08f47042016-08-17 02:52:01 +00001511 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1512 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001513 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001514 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001515 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001516 BBI.IsAnalyzed = false;
1517 CvtBBI->IsAnalyzed = false;
1518 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001519 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001520
Matthias Braun08f47042016-08-17 02:52:01 +00001521 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001522 // Conservatively abort if-conversion if BB's address is taken.
1523 return false;
1524
Evan Cheng3a51c852007-06-16 09:34:52 +00001525 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001526 if (TII->reverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001527 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001528
Evan Cheng3a51c852007-06-16 09:34:52 +00001529 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001530 if (reverseBranchCondition(*CvtBBI)) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001531 // BB has been changed, modify its predecessors (except for this
1532 // one) so they don't get ifcvt'ed based on bad intel.
Matthias Braun08f47042016-08-17 02:52:01 +00001533 for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001534 if (PBB == BBI.BB)
1535 continue;
1536 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1537 if (PBBI.IsEnqueued) {
1538 PBBI.IsAnalyzed = false;
1539 PBBI.IsEnqueued = false;
1540 }
Evan Chengadd97762007-06-14 23:34:09 +00001541 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001542 }
1543 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001544
Bob Wilson45814342010-06-19 05:33:57 +00001545 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001546 // predicated instructions.
Matthias Braun0c989a82016-12-08 00:15:51 +00001547 Redefs.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001548 if (MRI->tracksLiveness()) {
1549 Redefs.addLiveIns(CvtMBB);
1550 Redefs.addLiveIns(NextMBB);
1551 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001552
Craig Topperc0196b12014-04-14 00:51:57 +00001553 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001554 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001555
Manman Renb6819182014-01-29 23:18:47 +00001556 if (HasEarlyExit) {
Matthias Braun08f47042016-08-17 02:52:01 +00001557 // Get probabilities before modifying CvtMBB and BBI.BB.
1558 CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1559 CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1560 BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1561 BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
Manman Renb6819182014-01-29 23:18:47 +00001562 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001563
Mikael Holmen45bd32f2017-06-26 09:33:04 +00001564 // Remove the branches from the entry so we can add the contents of the true
1565 // block to it.
1566 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1567
Matthias Braun08f47042016-08-17 02:52:01 +00001568 if (CvtMBB.pred_size() > 1) {
Bob Wilson2371f4f2009-05-13 23:25:24 +00001569 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001570 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001571 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001572 } else {
1573 // Predicate the 'true' block after removing its branch.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001574 CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
Matthias Braun08f47042016-08-17 02:52:01 +00001575 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001576
Mikael Holmence3ec452017-05-12 06:28:58 +00001577 // Now merge the entry of the triangle with the true block.
Bob Wilson1e5da552010-06-29 00:55:23 +00001578 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001579 }
1580
Mikael Holmen8b106802017-08-11 06:57:08 +00001581 // Keep the CFG updated.
1582 BBI.BB->removeSuccessor(&CvtMBB, true);
1583
Evan Cheng312b7232007-06-04 06:47:22 +00001584 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001585 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001586 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1587 CvtBBI->BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001588 if (TII->reverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001589 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001590
Cong Houd97c1002015-12-01 05:29:22 +00001591 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
Matthias Braun08f47042016-08-17 02:52:01 +00001592 // NewNext = New_Prob(BBI.BB, NextMBB) =
1593 // Prob(BBI.BB, NextMBB) +
1594 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
Cong Houd97c1002015-12-01 05:29:22 +00001595 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
Matthias Braun08f47042016-08-17 02:52:01 +00001596 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1597 auto NewTrueBB = getNextBlock(*BBI.BB);
Cong Houd97c1002015-12-01 05:29:22 +00001598 auto NewNext = BBNext + BBCvt * CvtNext;
David Majnemer42531262016-08-12 03:55:06 +00001599 auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001600 if (NewTrueBBIter != BBI.BB->succ_end())
1601 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001602
1603 auto NewFalse = BBCvt * CvtFalse;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001604 TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
Cong Houd97c1002015-12-01 05:29:22 +00001605 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001606 }
Evan Cheng7783f822007-06-08 09:36:04 +00001607
1608 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001609 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001610 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001611 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001612 bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001613 if (!isFallThrough) {
1614 // Only merge them if the true block does not fallthrough to the false
1615 // block. By not merging them, we make it possible to iteratively
1616 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001617 if (!HasEarlyExit &&
Tobias Grosser8cf785f2017-05-29 06:12:18 +00001618 NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
Matthias Braun08f47042016-08-17 02:52:01 +00001619 !NextMBB.hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001620 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001621 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001622 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001623 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001624 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001625 }
Evan Cheng7783f822007-06-08 09:36:04 +00001626 // Mixed predicated and unpredicated code. This cannot be iteratively
1627 // predicated.
1628 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001629 }
Evan Chenge26c0912007-05-21 22:22:58 +00001630
Evan Chengd0e66912007-05-23 07:23:16 +00001631 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001632 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001633 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001634 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001635 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001636 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001637 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001638
1639 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001640 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001641}
1642
Kyle Butta8c73712016-08-24 21:34:27 +00001643/// Common code shared between diamond conversions.
1644/// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1645/// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1646/// and FalseBBI
1647/// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1648/// and \p FalseBBI
Kyle Butt092c4dd2016-08-29 18:27:12 +00001649/// \p RemoveBranch - Remove the common branch of the two blocks before
1650/// predicating. Only false for unanalyzable fallthrough
1651/// cases. The caller will replace the branch if necessary.
Kyle Butta8c73712016-08-24 21:34:27 +00001652/// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1653/// unanalyzable fallthrough
1654bool IfConverter::IfConvertDiamondCommon(
1655 BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1656 unsigned NumDups1, unsigned NumDups2,
1657 bool TClobbersPred, bool FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001658 bool RemoveBranch, bool MergeAddEdges) {
Evan Chenge26c0912007-05-21 22:22:58 +00001659
Evan Cheng51eb2c32007-06-18 08:37:25 +00001660 if (TrueBBI.IsDone || FalseBBI.IsDone ||
Kyle Butta8c73712016-08-24 21:34:27 +00001661 TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001662 // Something has changed. It's no longer safe to predicate these blocks.
1663 BBI.IsAnalyzed = false;
1664 TrueBBI.IsAnalyzed = false;
1665 FalseBBI.IsAnalyzed = false;
1666 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001667 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001668
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001669 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1670 // Conservatively abort if-conversion if either BB has its address taken.
1671 return false;
1672
Bob Wilson1e5da552010-06-29 00:55:23 +00001673 // Put the predicated instructions from the 'true' block before the
1674 // instructions from the 'false' block, unless the true block would clobber
1675 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001676 BBInfo *BBI1 = &TrueBBI;
1677 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001678 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001679 if (TII->reverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001680 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001681 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1682 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001683
Evan Cheng3a51c852007-06-16 09:34:52 +00001684 // Figure out the more profitable ordering.
1685 bool DoSwap = false;
Kyle Butt6262ca32016-08-24 21:34:24 +00001686 if (TClobbersPred && !FClobbersPred)
Evan Cheng3a51c852007-06-16 09:34:52 +00001687 DoSwap = true;
Kyle Butte31cc842016-09-02 18:29:28 +00001688 else if (!TClobbersPred && !FClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001689 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001690 DoSwap = true;
Kyle Butte31cc842016-09-02 18:29:28 +00001691 } else if (TClobbersPred && FClobbersPred)
1692 llvm_unreachable("Predicate info cannot be clobbered by both sides.");
Evan Cheng3a51c852007-06-16 09:34:52 +00001693 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001694 std::swap(BBI1, BBI2);
1695 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001696 }
Evan Cheng79484222007-06-05 23:46:14 +00001697
Evan Cheng51eb2c32007-06-18 08:37:25 +00001698 // Remove the conditional branch from entry to the blocks.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001699 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001700
Matthias Braun08f47042016-08-17 02:52:01 +00001701 MachineBasicBlock &MBB1 = *BBI1->BB;
1702 MachineBasicBlock &MBB2 = *BBI2->BB;
1703
Krzysztof Parzyszeka003b762016-08-11 18:42:06 +00001704 // Initialize the Redefs:
1705 // - BB2 live-in regs need implicit uses before being redefined by BB1
1706 // instructions.
1707 // - BB1 live-out regs need implicit uses before being redefined by BB2
1708 // instructions. We start with BB1 live-ins so we have the live-out regs
1709 // after tracking the BB1 instructions.
Matthias Braun0c989a82016-12-08 00:15:51 +00001710 Redefs.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001711 if (MRI->tracksLiveness()) {
1712 Redefs.addLiveIns(MBB1);
1713 Redefs.addLiveIns(MBB2);
1714 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001715
Evan Cheng51eb2c32007-06-18 08:37:25 +00001716 // Remove the duplicated instructions at the beginnings of both paths.
Krzysztof Parzyszekfbee8572018-04-19 17:26:46 +00001717 // Skip dbg_value instructions.
Matthias Braun08f47042016-08-17 02:52:01 +00001718 MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1719 MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001720 BBI1->NonPredSize -= NumDups1;
1721 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001722
1723 // Skip past the dups on each side separately since there may be
Krzysztof Parzyszekfbee8572018-04-19 17:26:46 +00001724 // differing dbg_value entries. NumDups1 can include a "return"
1725 // instruction, if it's not marked as "branch".
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001726 for (unsigned i = 0; i < NumDups1; ++DI1) {
Krzysztof Parzyszekfbee8572018-04-19 17:26:46 +00001727 if (DI1 == MBB1.end())
1728 break;
Shiva Chen801bf7e2018-05-09 02:42:00 +00001729 if (!DI1->isDebugInstr())
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001730 ++i;
1731 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001732 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001733 ++DI2;
Krzysztof Parzyszekfbee8572018-04-19 17:26:46 +00001734 if (DI2 == MBB2.end())
1735 break;
Shiva Chen801bf7e2018-05-09 02:42:00 +00001736 if (!DI2->isDebugInstr())
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001737 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001738 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001739
Matthias Braun11723322017-01-05 20:01:19 +00001740 if (MRI->tracksLiveness()) {
Matthias Braun11723322017-01-05 20:01:19 +00001741 for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
Matthias Braunc6613872018-11-06 19:00:11 +00001742 SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Dummy;
Matthias Braun11723322017-01-05 20:01:19 +00001743 Redefs.stepForward(MI, Dummy);
1744 }
Matthias Braund616ccc2013-10-11 19:04:37 +00001745 }
Krzysztof Parzyszekfbee8572018-04-19 17:26:46 +00001746
Matthias Braun08f47042016-08-17 02:52:01 +00001747 BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1748 MBB2.erase(MBB2.begin(), DI2);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001749
Krzysztof Parzyszekfbee8572018-04-19 17:26:46 +00001750 // The branches have been checked to match, so it is safe to remove the
1751 // branch in BB1 and rely on the copy in BB2. The complication is that
1752 // the blocks may end with a return instruction, which may or may not
1753 // be marked as "branch". If it's not, then it could be included in
1754 // "dups1", leaving the blocks potentially empty after moving the common
1755 // duplicates.
Kyle Butt092c4dd2016-08-29 18:27:12 +00001756#ifndef NDEBUG
1757 // Unanalyzable branches must match exactly. Check that now.
1758 if (!BBI1->IsBrAnalyzable)
1759 verifySameBranchInstructions(&MBB1, &MBB2);
1760#endif
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001761 BBI1->NonPredSize -= TII->removeBranch(*BBI1->BB);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001762 // Remove duplicated instructions.
Matthias Braun08f47042016-08-17 02:52:01 +00001763 DI1 = MBB1.end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001764 for (unsigned i = 0; i != NumDups2; ) {
1765 // NumDups2 only counted non-dbg_value instructions, so this won't
1766 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001767 assert(DI1 != MBB1.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001768 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001769 // skip dbg_value instructions
Shiva Chen801bf7e2018-05-09 02:42:00 +00001770 if (!DI1->isDebugInstr())
Jim Grosbach412800d2010-06-14 21:30:32 +00001771 ++i;
1772 }
Matthias Braun08f47042016-08-17 02:52:01 +00001773 MBB1.erase(DI1, MBB1.end());
Evan Cheng79484222007-06-05 23:46:14 +00001774
Kyle Butta8c73712016-08-24 21:34:27 +00001775 DI2 = BBI2->BB->end();
Kyle Butt092c4dd2016-08-29 18:27:12 +00001776 // The branches have been checked to match. Skip over the branch in the false
1777 // block so that we don't try to predicate it.
1778 if (RemoveBranch)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001779 BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
Kyle Butt092c4dd2016-08-29 18:27:12 +00001780 else {
Krzysztof Parzyszekfbee8572018-04-19 17:26:46 +00001781 // Make DI2 point to the end of the range where the common "tail"
1782 // instructions could be found.
1783 while (DI2 != MBB2.begin()) {
1784 MachineBasicBlock::iterator Prev = std::prev(DI2);
Shiva Chen801bf7e2018-05-09 02:42:00 +00001785 if (!Prev->isBranch() && !Prev->isDebugInstr())
Krzysztof Parzyszekfbee8572018-04-19 17:26:46 +00001786 break;
1787 DI2 = Prev;
1788 }
Kyle Butt092c4dd2016-08-29 18:27:12 +00001789 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001790 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001791 // NumDups2 only counted non-dbg_value instructions, so this won't
1792 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001793 assert(DI2 != MBB2.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001794 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001795 // skip dbg_value instructions
Shiva Chen801bf7e2018-05-09 02:42:00 +00001796 if (!DI2->isDebugInstr())
Jim Grosbach412800d2010-06-14 21:30:32 +00001797 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001798 }
Evan Cheng4266a792011-12-19 22:01:30 +00001799
1800 // Remember which registers would later be defined by the false block.
1801 // This allows us not to predicate instructions in the true block that would
1802 // later be re-defined. That is, rather than
1803 // subeq r0, r1, #1
1804 // addne r0, r1, #1
1805 // generate:
1806 // sub r0, r1, #1
1807 // addne r0, r1, #1
Matthias Braunc6613872018-11-06 19:00:11 +00001808 SmallSet<MCPhysReg, 4> RedefsByFalse;
1809 SmallSet<MCPhysReg, 4> ExtUses;
Matthias Braun08f47042016-08-17 02:52:01 +00001810 if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1811 for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
Shiva Chen801bf7e2018-05-09 02:42:00 +00001812 if (FI.isDebugInstr())
Evan Cheng4266a792011-12-19 22:01:30 +00001813 continue;
Matthias Braunc6613872018-11-06 19:00:11 +00001814 SmallVector<MCPhysReg, 4> Defs;
Matthias Braunb1e05582016-08-17 02:51:59 +00001815 for (const MachineOperand &MO : FI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001816 if (!MO.isReg())
1817 continue;
1818 unsigned Reg = MO.getReg();
1819 if (!Reg)
1820 continue;
1821 if (MO.isDef()) {
1822 Defs.push_back(Reg);
1823 } else if (!RedefsByFalse.count(Reg)) {
1824 // These are defined before ctrl flow reach the 'false' instructions.
1825 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001826 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1827 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001828 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001829 }
1830 }
1831
Matthias Braunc6613872018-11-06 19:00:11 +00001832 for (MCPhysReg Reg : Defs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001833 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001834 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1835 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001836 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001837 }
1838 }
1839 }
1840 }
1841
1842 // Predicate the 'true' block.
Matthias Braun08f47042016-08-17 02:52:01 +00001843 PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001844
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001845 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1846 // a non-predicated in BBI2, then we don't want to predicate the one from
1847 // BBI2. The reason is that if we merged these blocks, we would end up with
1848 // two predicated terminators in the same block.
Krzysztof Parzyszekfbee8572018-04-19 17:26:46 +00001849 // Also, if the branches in MBB1 and MBB2 were non-analyzable, then don't
1850 // predicate them either. They were checked to be identical, and so the
1851 // same branch would happen regardless of which path was taken.
Matthias Braun08f47042016-08-17 02:52:01 +00001852 if (!MBB2.empty() && (DI2 == MBB2.end())) {
1853 MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1854 MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
Krzysztof Parzyszekfbee8572018-04-19 17:26:46 +00001855 bool BB1Predicated = BBI1T != MBB1.end() && TII->isPredicated(*BBI1T);
1856 bool BB2NonPredicated = BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T);
1857 if (BB2NonPredicated && (BB1Predicated || !BBI2->IsBrAnalyzable))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001858 --DI2;
1859 }
1860
Evan Cheng4266a792011-12-19 22:01:30 +00001861 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001862 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001863
Evan Cheng0598b2d2007-06-18 22:44:57 +00001864 // Merge the true block into the entry of the diamond.
Kyle Butta8c73712016-08-24 21:34:27 +00001865 MergeBlocks(BBI, *BBI1, MergeAddEdges);
1866 MergeBlocks(BBI, *BBI2, MergeAddEdges);
1867 return true;
1868}
1869
1870/// If convert an almost-diamond sub-CFG where the true
1871/// and false blocks share a common tail.
1872bool IfConverter::IfConvertForkedDiamond(
1873 BBInfo &BBI, IfcvtKind Kind,
1874 unsigned NumDups1, unsigned NumDups2,
1875 bool TClobbersPred, bool FClobbersPred) {
1876 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1877 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1878
1879 // Save the debug location for later.
1880 DebugLoc dl;
1881 MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1882 if (TIE != TrueBBI.BB->end())
1883 dl = TIE->getDebugLoc();
1884 // Removing branches from both blocks is safe, because we have already
1885 // determined that both blocks have the same branch instructions. The branch
1886 // will be added back at the end, unpredicated.
1887 if (!IfConvertDiamondCommon(
1888 BBI, TrueBBI, FalseBBI,
1889 NumDups1, NumDups2,
1890 TClobbersPred, FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001891 /* RemoveBranch */ true, /* MergeAddEdges */ true))
Kyle Butta8c73712016-08-24 21:34:27 +00001892 return false;
1893
1894 // Add back the branch.
1895 // Debug location saved above when removing the branch from BBI2
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001896 TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
Kyle Butta8c73712016-08-24 21:34:27 +00001897 TrueBBI.BrCond, dl);
1898
Kyle Butta8c73712016-08-24 21:34:27 +00001899 // Update block info.
1900 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1901 InvalidatePreds(*BBI.BB);
1902
1903 // FIXME: Must maintain LiveIns.
1904 return true;
1905}
1906
1907/// If convert a diamond sub-CFG.
1908bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1909 unsigned NumDups1, unsigned NumDups2,
1910 bool TClobbersPred, bool FClobbersPred) {
1911 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1912 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1913 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1914
1915 // True block must fall through or end with an unanalyzable terminator.
1916 if (!TailBB) {
1917 if (blockAlwaysFallThrough(TrueBBI))
1918 TailBB = FalseBBI.TrueBB;
1919 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1920 }
1921
1922 if (!IfConvertDiamondCommon(
1923 BBI, TrueBBI, FalseBBI,
1924 NumDups1, NumDups2,
Kyle Butt86999212016-09-02 18:29:26 +00001925 TClobbersPred, FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001926 /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
Kyle Butta8c73712016-08-24 21:34:27 +00001927 /* MergeAddEdges */ TailBB == nullptr))
1928 return false;
Evan Cheng30565992007-06-06 00:57:55 +00001929
Bob Wilson2371f4f2009-05-13 23:25:24 +00001930 // If the if-converted block falls through or unconditionally branches into
1931 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001932 // fold the tail block in as well. Otherwise, unless it falls through to the
1933 // tail, add a unconditional branch to it.
1934 if (TailBB) {
Mikael Holmen8b106802017-08-11 06:57:08 +00001935 // We need to remove the edges to the true and false blocks manually since
1936 // we didn't let IfConvertDiamondCommon update the CFG.
1937 BBI.BB->removeSuccessor(TrueBBI.BB);
1938 BBI.BB->removeSuccessor(FalseBBI.BB, true);
1939
Pete Cooper77c703f2011-11-04 23:49:14 +00001940 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001941 bool CanMergeTail = !TailBBI.HasFallThrough &&
1942 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001943 // The if-converted block can still have a predicated terminator
1944 // (e.g. a predicated return). If that is the case, we cannot merge
1945 // it with the tail block.
1946 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001947 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001948 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001949 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1950 // check if there are any other predecessors besides those.
1951 unsigned NumPreds = TailBB->pred_size();
1952 if (NumPreds > 1)
1953 CanMergeTail = false;
1954 else if (NumPreds == 1 && CanMergeTail) {
1955 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
Kyle Butta8c73712016-08-24 21:34:27 +00001956 if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
Bob Wilson1e5da552010-06-29 00:55:23 +00001957 CanMergeTail = false;
1958 }
1959 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001960 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001961 TailBBI.IsDone = true;
1962 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001963 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Matthias Braun08f47042016-08-17 02:52:01 +00001964 InsertUncondBranch(*BBI.BB, *TailBB, TII);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001965 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001966 }
Evan Chenge26c0912007-05-21 22:22:58 +00001967 }
1968
Evan Cheng79484222007-06-05 23:46:14 +00001969 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001970 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001971 InvalidatePreds(*BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001972
1973 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001974 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001975}
1976
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001977static bool MaySpeculate(const MachineInstr &MI,
Matthias Braunc6613872018-11-06 19:00:11 +00001978 SmallSet<MCPhysReg, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001979 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001980 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001981 return false;
1982
Matthias Braunb1e05582016-08-17 02:51:59 +00001983 for (const MachineOperand &MO : MI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001984 if (!MO.isReg())
1985 continue;
1986 unsigned Reg = MO.getReg();
1987 if (!Reg)
1988 continue;
1989 if (MO.isDef() && !LaterRedefs.count(Reg))
1990 return false;
1991 }
1992
1993 return true;
1994}
1995
Matthias Braun2c931792016-08-17 02:51:57 +00001996/// Predicate instructions from the start of the block to the specified end with
1997/// the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001998void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001999 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00002000 SmallVectorImpl<MachineOperand> &Cond,
Matthias Braunc6613872018-11-06 19:00:11 +00002001 SmallSet<MCPhysReg, 4> *LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00002002 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002003 bool MaySpec = LaterRedefs != nullptr;
Matthias Braunb1e05582016-08-17 02:51:59 +00002004 for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
Shiva Chen801bf7e2018-05-09 02:42:00 +00002005 if (I.isDebugInstr() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00002006 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00002007 // It may be possible not to predicate an instruction if it's the 'true'
2008 // side of a diamond and the 'false' side may re-define the instruction's
2009 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00002010 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00002011 AnyUnpred = true;
2012 continue;
2013 }
2014 // If any instruction is predicated, then every instruction after it must
2015 // be predicated.
2016 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002017 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00002018#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002019 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00002020#endif
Craig Topperc0196b12014-04-14 00:51:57 +00002021 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00002022 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002023
Bob Wilson45814342010-06-19 05:33:57 +00002024 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002025 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002026 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00002027 }
Evan Chengd0e66912007-05-23 07:23:16 +00002028
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002029 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00002030
Evan Cheng92fb5452007-06-15 07:36:12 +00002031 BBI.IsAnalyzed = false;
2032 BBI.NonPredSize = 0;
2033
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002034 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00002035 if (AnyUnpred)
2036 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00002037}
2038
Matthias Braun2c931792016-08-17 02:51:57 +00002039/// Copy and predicate instructions from source BB to the destination block.
2040/// Skip end of block branches if IgnoreBr is true.
Evan Cheng92fb5452007-06-15 07:36:12 +00002041void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00002042 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00002043 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00002044 MachineFunction &MF = *ToBBI.BB->getParent();
2045
Matthias Braun08f47042016-08-17 02:52:01 +00002046 MachineBasicBlock &FromMBB = *FromBBI.BB;
2047 for (MachineInstr &I : FromMBB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00002048 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002049 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00002050 break;
2051
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002052 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00002053 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00002054 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002055 unsigned ExtraPredCost = TII->getPredicationCost(I);
2056 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00002057 if (NumCycles > 1)
2058 ToBBI.ExtraCost += NumCycles-1;
2059 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00002060
Shiva Chen801bf7e2018-05-09 02:42:00 +00002061 if (!TII->isPredicated(I) && !MI->isDebugInstr()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002062 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00002063#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002064 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00002065#endif
Craig Topperc0196b12014-04-14 00:51:57 +00002066 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00002067 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002068 }
2069
Bob Wilson45814342010-06-19 05:33:57 +00002070 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002071 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002072 UpdatePredRedefs(*MI, Redefs);
Evan Cheng92fb5452007-06-15 07:36:12 +00002073 }
2074
Bob Wilson1e5da552010-06-29 00:55:23 +00002075 if (!IgnoreBr) {
Matthias Braun08f47042016-08-17 02:52:01 +00002076 std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2077 FromMBB.succ_end());
2078 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00002079 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00002080
Matthias Braunb1e05582016-08-17 02:51:59 +00002081 for (MachineBasicBlock *Succ : Succs) {
Bob Wilson1e5da552010-06-29 00:55:23 +00002082 // Fallthrough edge can't be transferred.
2083 if (Succ == FallThrough)
2084 continue;
2085 ToBBI.BB->addSuccessor(Succ);
2086 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00002087 }
2088
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002089 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2090 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002091
2092 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2093 ToBBI.IsAnalyzed = false;
2094
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002095 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00002096}
2097
Matthias Braun2c931792016-08-17 02:51:57 +00002098/// Move all instructions from FromBB to the end of ToBB. This will leave
2099/// FromBB as an empty block, so remove all of its successor edges except for
2100/// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
Mikael Holmen8b106802017-08-11 06:57:08 +00002101/// being moved, add those successor edges to ToBBI and remove the old edge
2102/// from ToBBI to FromBBI.
Bob Wilson1e5da552010-06-29 00:55:23 +00002103void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Matthias Braun08f47042016-08-17 02:52:01 +00002104 MachineBasicBlock &FromMBB = *FromBBI.BB;
2105 assert(!FromMBB.hasAddressTaken() &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00002106 "Removing a BB whose address is taken!");
2107
Matthias Braun08f47042016-08-17 02:52:01 +00002108 // In case FromMBB contains terminators (e.g. return instruction),
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002109 // first move the non-terminator instructions, then the terminators.
Matthias Braun08f47042016-08-17 02:52:01 +00002110 MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002111 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
Matthias Braun08f47042016-08-17 02:52:01 +00002112 ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002113
2114 // If FromBB has non-predicated terminator we should copy it at the end.
Matthias Braun08f47042016-08-17 02:52:01 +00002115 if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002116 ToTI = ToBBI.BB->end();
Matthias Braun08f47042016-08-17 02:52:01 +00002117 ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
Evan Chengd0e66912007-05-23 07:23:16 +00002118
Cong Houb9e8d482015-12-17 01:29:08 +00002119 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2120 // unknown probabilities into known ones.
2121 // FIXME: This usage is too tricky and in the future we would like to
2122 // eliminate all unknown probabilities in MBB.
Krzysztof Parzyszek5b8fae52017-03-06 19:12:42 +00002123 if (ToBBI.IsBrAnalyzable)
2124 ToBBI.BB->normalizeSuccProbs();
Cong Houb9e8d482015-12-17 01:29:08 +00002125
Matthias Braun08f47042016-08-17 02:52:01 +00002126 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
2127 FromMBB.succ_end());
2128 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00002129 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Matthias Braun08f47042016-08-17 02:52:01 +00002130 // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2131 // AddEdges is true and FromMBB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00002132 auto To2FromProb = BranchProbability::getZero();
Matthias Braun08f47042016-08-17 02:52:01 +00002133 if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
Mikael Holmen8b106802017-08-11 06:57:08 +00002134 // Remove the old edge but remember the edge probability so we can calculate
2135 // the correct weights on the new edges being added further down.
Matthias Braun08f47042016-08-17 02:52:01 +00002136 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
Mikael Holmen8b106802017-08-11 06:57:08 +00002137 ToBBI.BB->removeSuccessor(&FromMBB);
Cong Houd97c1002015-12-01 05:29:22 +00002138 }
2139
Matthias Braunb1e05582016-08-17 02:51:59 +00002140 for (MachineBasicBlock *Succ : FromSuccs) {
Evan Cheng288f1542007-06-08 22:01:07 +00002141 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00002142 if (Succ == FallThrough)
2143 continue;
Cong Houd40105d2015-09-18 20:22:41 +00002144
Cong Houd97c1002015-12-01 05:29:22 +00002145 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00002146 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002147 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
Matthias Braun08f47042016-08-17 02:52:01 +00002148 // which is a portion of the edge probability from FromMBB to Succ. The
2149 // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +00002150 // FromBBI is a successor of ToBBI.BB. See comment below for exception).
Matthias Braun08f47042016-08-17 02:52:01 +00002151 NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002152
Matthias Braun08f47042016-08-17 02:52:01 +00002153 // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2154 // only happens when if-converting a diamond CFG and FromMBB is the
2155 // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
2156 // could just use the probabilities on FromMBB's out-edges when adding
Cong Houd97c1002015-12-01 05:29:22 +00002157 // new successors.
2158 if (!To2FromProb.isZero())
2159 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00002160 }
2161
Matthias Braun08f47042016-08-17 02:52:01 +00002162 FromMBB.removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002163
2164 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002165 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00002166 // probability of this edge by adding NewProb to it. An example is shown
Matthias Braun08f47042016-08-17 02:52:01 +00002167 // below, in which A is ToBBI.BB and B is FromMBB. In this case we
Cong Houd97c1002015-12-01 05:29:22 +00002168 // don't have to set C as A's successor as it already is. We only need to
2169 // update the edge probability on A->C. Note that B will not be
2170 // immediately removed from A's successors. It is possible that B->D is
2171 // not removed either if D is a fallthrough of B. Later the edge A->D
2172 // (generated here) and B->D will be combined into one edge. To maintain
2173 // correct edge probability of this combined edge, we need to set the edge
2174 // probability of A->B to zero, which is already done above. The edge
2175 // probability on A->D is calculated by scaling the original probability
2176 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00002177 //
2178 // Before ifcvt: After ifcvt (assume B->D is kept):
2179 //
2180 // A A
2181 // /| /|\
2182 // / B / B|
2183 // | /| | ||
2184 // |/ | | |/
2185 // C D C D
2186 //
2187 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00002188 ToBBI.BB->setSuccProbability(
David Majnemer42531262016-08-12 03:55:06 +00002189 find(ToBBI.BB->successors(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00002190 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002191 else
Cong Houd97c1002015-12-01 05:29:22 +00002192 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002193 }
Evan Chengbe9859e2007-06-07 02:12:15 +00002194 }
2195
Mikael Holmen8b106802017-08-11 06:57:08 +00002196 // Move the now empty FromMBB out of the way to the end of the function so
2197 // it doesn't interfere with fallthrough checks done by canFallThroughTo().
2198 MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
2199 if (Last != &FromMBB)
2200 FromMBB.moveAfter(Last);
Evan Cheng288f1542007-06-08 22:01:07 +00002201
Cong Houc1069892015-12-13 09:26:17 +00002202 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2203 // we've done above.
Krzysztof Parzyszek5b8fae52017-03-06 19:12:42 +00002204 if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
2205 ToBBI.BB->normalizeSuccProbs();
Cong Houc1069892015-12-13 09:26:17 +00002206
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002207 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002208 FromBBI.Predicate.clear();
2209
Evan Chengd0e66912007-05-23 07:23:16 +00002210 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002211 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00002212 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00002213 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002214 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00002215 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00002216
Evan Cheng4dd31a72007-06-11 22:26:22 +00002217 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00002218 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00002219 ToBBI.IsAnalyzed = false;
2220 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00002221}
Akira Hatanaka4a616192015-06-08 18:50:43 +00002222
2223FunctionPass *
Matthias Braun8b38ffa2016-10-24 23:23:02 +00002224llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00002225 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00002226}