blob: 8babedbbb67804dba09dcb27cf7ea6f67aa6ded7 [file] [log] [blame]
Chris Lattner25e48dd2004-07-31 10:01:27 +00001//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner25e48dd2004-07-31 10:01:27 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner25e48dd2004-07-31 10:01:27 +00008//===----------------------------------------------------------------------===//
9//
10// This pass forwards branches to unconditional branches to make them branch
11// directly to the target block. This pass often results in dead MBB's, which
12// it then removes.
13//
14// Note that this pass must be run after register allocation, it cannot handle
Jingyue Wu3a04dc62015-07-29 18:59:09 +000015// SSA form. It also must handle virtual registers for targets that emit virtual
16// ISA (e.g. NVPTX).
Chris Lattner25e48dd2004-07-31 10:01:27 +000017//
18//===----------------------------------------------------------------------===//
19
Evan Cheng3d2fce02009-09-04 07:47:40 +000020#include "BranchFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/Statistic.h"
David Majnemer16193552015-10-04 02:22:52 +000024#include "llvm/CodeGen/Analysis.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000025#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
26#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Chris Lattner25e48dd2004-07-31 10:01:27 +000027#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattner56c9d252006-10-17 17:13:52 +000028#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chad Rosier3b67c8d2015-03-10 16:22:52 +000029#include "llvm/CodeGen/MachineMemOperand.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/CodeGen/MachineModuleInfo.h"
Jakob Stoklund Olesend1664a12012-03-27 17:06:09 +000031#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/CodeGen/Passes.h"
Dale Johannesend05a1a22007-03-20 21:35:06 +000033#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Function.h"
Chris Lattner60c9d4d2006-10-21 00:47:49 +000035#include "llvm/Support/CommandLine.h"
Chris Lattner56ec81f2006-11-18 21:56:39 +000036#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000037#include "llvm/Support/ErrorHandling.h"
Bill Wendlingc3f05e82009-08-22 20:03:00 +000038#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000041#include "llvm/Target/TargetSubtargetInfo.h"
Jeff Cohen7d6f3db2006-11-05 19:31:28 +000042#include <algorithm>
Chris Lattner25e48dd2004-07-31 10:01:27 +000043using namespace llvm;
44
Chandler Carruth1b9dde02014-04-22 02:02:50 +000045#define DEBUG_TYPE "branchfolding"
46
Chris Lattneraee775a2006-12-19 22:41:21 +000047STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
48STATISTIC(NumBranchOpts, "Number of branches optimized");
49STATISTIC(NumTailMerge , "Number of block tails merged");
Evan Chengcfdf3392011-05-12 00:56:58 +000050STATISTIC(NumHoist , "Number of times common instructions are hoisted");
Bob Wilson8984e6e2009-11-18 19:29:37 +000051
Dan Gohmanc86b5a12009-11-11 18:38:14 +000052static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
Dale Johannesen82810c82007-05-22 17:14:46 +000053 cl::init(cl::BOU_UNSET), cl::Hidden);
Bob Wilson8984e6e2009-11-18 19:29:37 +000054
Dan Gohmand78c4002008-05-13 00:00:25 +000055// Throttle for huge numbers of predecessors (compile speed problems)
56static cl::opt<unsigned>
Dan Gohmanc86b5a12009-11-11 18:38:14 +000057TailMergeThreshold("tail-merge-threshold",
Dan Gohmand78c4002008-05-13 00:00:25 +000058 cl::desc("Max number of predecessors to consider tail merging"),
Dale Johannesen1d7e42c2008-10-27 02:10:21 +000059 cl::init(150), cl::Hidden);
Dale Johannesen86798e52007-06-08 01:08:52 +000060
Dan Gohman64b5d0f2009-11-11 19:48:59 +000061// Heuristic for tail merging (and, inversely, tail duplication).
62// TODO: This should be replaced with a target query.
63static cl::opt<unsigned>
Bob Wilson699f5b92009-11-16 17:56:13 +000064TailMergeSize("tail-merge-size",
Dan Gohman64b5d0f2009-11-11 19:48:59 +000065 cl::desc("Min number of instructions to consider tail merging"),
66 cl::init(3), cl::Hidden);
Devang Patel09f162c2007-05-01 21:15:47 +000067
Dan Gohmana9b40a6e2009-11-12 01:59:26 +000068namespace {
69 /// BranchFolderPass - Wrap branch folder in a machine function pass.
Andrew Trick58648e42012-02-08 21:22:48 +000070 class BranchFolderPass : public MachineFunctionPass {
Dan Gohmana9b40a6e2009-11-12 01:59:26 +000071 public:
72 static char ID;
Andrew Trick58648e42012-02-08 21:22:48 +000073 explicit BranchFolderPass(): MachineFunctionPass(ID) {}
Dan Gohmana9b40a6e2009-11-12 01:59:26 +000074
Craig Topper4584cd52014-03-07 09:26:03 +000075 bool runOnMachineFunction(MachineFunction &MF) override;
Andrew Trick58648e42012-02-08 21:22:48 +000076
Craig Topper4584cd52014-03-07 09:26:03 +000077 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +000078 AU.addRequired<MachineBlockFrequencyInfo>();
79 AU.addRequired<MachineBranchProbabilityInfo>();
Andrew Trick58648e42012-02-08 21:22:48 +000080 AU.addRequired<TargetPassConfig>();
81 MachineFunctionPass::getAnalysisUsage(AU);
82 }
Dan Gohmana9b40a6e2009-11-12 01:59:26 +000083 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000084}
Dan Gohmana9b40a6e2009-11-12 01:59:26 +000085
Evan Cheng3d2fce02009-09-04 07:47:40 +000086char BranchFolderPass::ID = 0;
Andrew Trick58648e42012-02-08 21:22:48 +000087char &llvm::BranchFolderPassID = BranchFolderPass::ID;
Chris Lattner25e48dd2004-07-31 10:01:27 +000088
Andrew Trick58648e42012-02-08 21:22:48 +000089INITIALIZE_PASS(BranchFolderPass, "branch-folder",
90 "Control Flow Optimizer", false, false)
Evan Cheng3d2fce02009-09-04 07:47:40 +000091
92bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
Paul Robinson7c99ec52014-03-31 17:43:35 +000093 if (skipOptnoneFunction(*MF.getFunction()))
94 return false;
95
Andrew Trick58648e42012-02-08 21:22:48 +000096 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
Vincent Lejeune92b0a642013-12-07 01:49:19 +000097 // TailMerge can create jump into if branches that make CFG irreducible for
David Majnemer16193552015-10-04 02:22:52 +000098 // HW that requires structurized CFG.
Vincent Lejeune92b0a642013-12-07 01:49:19 +000099 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
David Majnemer4600c062015-10-01 21:04:13 +0000100 PassConfig->getEnableTailMerge();
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000101 BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true,
102 getAnalysis<MachineBlockFrequencyInfo>(),
103 getAnalysis<MachineBranchProbabilityInfo>());
Eric Christopherfc6de422014-08-05 02:39:49 +0000104 return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
105 MF.getSubtarget().getRegisterInfo(),
106 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Cheng3d2fce02009-09-04 07:47:40 +0000107}
108
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000109BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist,
110 const MachineBlockFrequencyInfo &FreqInfo,
111 const MachineBranchProbabilityInfo &ProbInfo)
112 : EnableHoistCommonCode(CommonHoist), MBBFreqInfo(FreqInfo),
113 MBPI(ProbInfo) {
Evan Cheng3d2fce02009-09-04 07:47:40 +0000114 switch (FlagEnableTailMerge) {
115 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
116 case cl::BOU_TRUE: EnableTailMerge = true; break;
117 case cl::BOU_FALSE: EnableTailMerge = false; break;
118 }
Evan Cheng1f6e5eb2009-09-03 23:54:22 +0000119}
Chris Lattner25e48dd2004-07-31 10:01:27 +0000120
Chris Lattner56c9d252006-10-17 17:13:52 +0000121/// RemoveDeadBlock - Remove the specified dead machine basic block from the
122/// function, updating the CFG.
Chris Lattner73da3202006-10-17 23:17:27 +0000123void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey9df1a1d2007-02-22 16:39:03 +0000124 assert(MBB->pred_empty() && "MBB must be dead!");
David Greened60abbf2009-12-24 00:34:21 +0000125 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000126
Chris Lattner56c9d252006-10-17 17:13:52 +0000127 MachineFunction *MF = MBB->getParent();
128 // drop all successors.
129 while (!MBB->succ_empty())
130 MBB->removeSuccessor(MBB->succ_end()-1);
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000131
Rafael Espindola3aeaf9e2011-06-14 15:31:54 +0000132 // Avoid matching if this pointer gets reused.
133 TriedMerging.erase(MBB);
134
Chris Lattner56c9d252006-10-17 17:13:52 +0000135 // Remove the block.
Dan Gohman3b460302008-07-07 23:14:23 +0000136 MF->erase(MBB);
David Majnemer16193552015-10-04 02:22:52 +0000137 FuncletMembership.erase(MBB);
Chris Lattner56c9d252006-10-17 17:13:52 +0000138}
139
Evan Cheng9d339842008-04-10 02:32:10 +0000140/// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
141/// followed by terminators, and if the implicitly defined registers are not
142/// used by the terminators, remove those implicit_def's. e.g.
143/// BB1:
144/// r0 = implicit_def
145/// r1 = implicit_def
146/// br
147/// This block can be optimized away later if the implicit instructions are
148/// removed.
149bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
150 SmallSet<unsigned, 4> ImpDefRegs;
151 MachineBasicBlock::iterator I = MBB->begin();
152 while (I != MBB->end()) {
Chris Lattnerb06015a2010-02-09 19:54:29 +0000153 if (!I->isImplicitDef())
Evan Cheng9d339842008-04-10 02:32:10 +0000154 break;
155 unsigned Reg = I->getOperand(0).getReg();
Jingyue Wu3a04dc62015-07-29 18:59:09 +0000156 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
157 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
158 SubRegs.isValid(); ++SubRegs)
159 ImpDefRegs.insert(*SubRegs);
160 } else {
161 ImpDefRegs.insert(Reg);
162 }
Evan Cheng9d339842008-04-10 02:32:10 +0000163 ++I;
164 }
165 if (ImpDefRegs.empty())
166 return false;
167
168 MachineBasicBlock::iterator FirstTerm = I;
169 while (I != MBB->end()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000170 if (!TII->isUnpredicatedTerminator(*I))
Evan Cheng9d339842008-04-10 02:32:10 +0000171 return false;
172 // See if it uses any of the implicitly defined registers.
Craig Topper5db36df2015-09-16 03:52:35 +0000173 for (const MachineOperand &MO : I->operands()) {
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000174 if (!MO.isReg() || !MO.isUse())
Evan Cheng9d339842008-04-10 02:32:10 +0000175 continue;
176 unsigned Reg = MO.getReg();
177 if (ImpDefRegs.count(Reg))
178 return false;
179 }
180 ++I;
181 }
182
183 I = MBB->begin();
184 while (I != FirstTerm) {
185 MachineInstr *ImpDefMI = &*I;
186 ++I;
187 MBB->erase(ImpDefMI);
188 }
189
190 return true;
191}
192
Evan Cheng3d2fce02009-09-04 07:47:40 +0000193/// OptimizeFunction - Perhaps branch folding, tail merging and other
194/// CFG optimizations on the given function.
195bool BranchFolder::OptimizeFunction(MachineFunction &MF,
196 const TargetInstrInfo *tii,
197 const TargetRegisterInfo *tri,
198 MachineModuleInfo *mmi) {
199 if (!tii) return false;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000200
Rafael Espindola3aeaf9e2011-06-14 15:31:54 +0000201 TriedMerging.clear();
202
Evan Cheng3d2fce02009-09-04 07:47:40 +0000203 TII = tii;
204 TRI = tri;
205 MMI = mmi;
Craig Topperc0196b12014-04-14 00:51:57 +0000206 RS = nullptr;
Evan Cheng3d2fce02009-09-04 07:47:40 +0000207
Jakob Stoklund Olesend1664a12012-03-27 17:06:09 +0000208 // Use a RegScavenger to help update liveness when required.
209 MachineRegisterInfo &MRI = MF.getRegInfo();
Preston Gurd9a091472012-04-23 21:39:35 +0000210 if (MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
Jakob Stoklund Olesend1664a12012-03-27 17:06:09 +0000211 RS = new RegScavenger();
212 else
213 MRI.invalidateLiveness();
Evan Cheng9d339842008-04-10 02:32:10 +0000214
Dale Johannesen420a85d2007-05-15 21:19:17 +0000215 // Fix CFG. The later algorithms expect it to be right.
Evan Cheng3d2fce02009-09-04 07:47:40 +0000216 bool MadeChange = false;
Craig Topper5db36df2015-09-16 03:52:35 +0000217 for (MachineBasicBlock &MBB : MF) {
218 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000219 SmallVector<MachineOperand, 4> Cond;
Craig Topper5db36df2015-09-16 03:52:35 +0000220 if (!TII->AnalyzeBranch(MBB, TBB, FBB, Cond, true))
221 MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
222 MadeChange |= OptimizeImpDefsBlock(&MBB);
Dale Johannesen420a85d2007-05-15 21:19:17 +0000223 }
224
David Majnemer16193552015-10-04 02:22:52 +0000225 // Recalculate funclet membership.
226 FuncletMembership = getFuncletMembership(MF);
227
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000228 bool MadeChangeThisIteration = true;
229 while (MadeChangeThisIteration) {
Evan Chengcfdf3392011-05-12 00:56:58 +0000230 MadeChangeThisIteration = TailMergeBlocks(MF);
231 MadeChangeThisIteration |= OptimizeBranches(MF);
232 if (EnableHoistCommonCode)
233 MadeChangeThisIteration |= HoistCommonCode(MF);
Evan Cheng3d2fce02009-09-04 07:47:40 +0000234 MadeChange |= MadeChangeThisIteration;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000235 }
236
Bob Wilsonbc5af982010-03-19 19:05:41 +0000237 // See if any jump tables have become dead as the code generator
Chris Lattnerc07657f2006-10-28 18:34:47 +0000238 // did its thing.
239 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
Craig Topperc0196b12014-04-14 00:51:57 +0000240 if (!JTI) {
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000241 delete RS;
242 return MadeChange;
243 }
Andrew Trick9e761992012-02-08 21:22:43 +0000244
Bob Wilsonbc5af982010-03-19 19:05:41 +0000245 // Walk the function to find jump tables that are live.
246 BitVector JTIsLive(JTI->getJumpTables().size());
Craig Topper5db36df2015-09-16 03:52:35 +0000247 for (const MachineBasicBlock &BB : MF) {
248 for (const MachineInstr &I : BB)
249 for (const MachineOperand &Op : I.operands()) {
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000250 if (!Op.isJTI()) continue;
Chris Lattnerc07657f2006-10-28 18:34:47 +0000251
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000252 // Remember that this JT is live.
Bob Wilsonbc5af982010-03-19 19:05:41 +0000253 JTIsLive.set(Op.getIndex());
Chris Lattnerc07657f2006-10-28 18:34:47 +0000254 }
255 }
Evan Cheng3d2fce02009-09-04 07:47:40 +0000256
Bob Wilsonbc5af982010-03-19 19:05:41 +0000257 // Finally, remove dead jump tables. This happens when the
258 // indirect jump was unreachable (and thus deleted).
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000259 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
260 if (!JTIsLive.test(i)) {
261 JTI->RemoveJumpTable(i);
262 MadeChange = true;
263 }
264
Dale Johannesend05a1a22007-03-20 21:35:06 +0000265 delete RS;
Evan Cheng3d2fce02009-09-04 07:47:40 +0000266 return MadeChange;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000267}
268
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000269//===----------------------------------------------------------------------===//
270// Tail Merging of Blocks
271//===----------------------------------------------------------------------===//
272
NAKAMURA Takumi3746abb2015-06-20 06:21:48 +0000273/// HashMachineInstr - Compute a hash value for MI and its operands.
Duncan P. N. Exon Smithd3a74672016-02-27 19:48:01 +0000274static unsigned HashMachineInstr(const MachineInstr &MI) {
275 unsigned Hash = MI.getOpcode();
276 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
277 const MachineOperand &Op = MI.getOperand(i);
NAKAMURA Takumi3746abb2015-06-20 06:21:48 +0000278
Benjamin Kramer8c57cfd2015-06-23 14:47:36 +0000279 // Merge in bits from the operand if easy. We can't use MachineOperand's
280 // hash_code here because it's not deterministic and we sort by hash value
281 // later.
NAKAMURA Takumi3746abb2015-06-20 06:21:48 +0000282 unsigned OperandHash = 0;
283 switch (Op.getType()) {
NAKAMURA Takumi34d33762015-06-20 06:22:04 +0000284 case MachineOperand::MO_Register:
285 OperandHash = Op.getReg();
286 break;
287 case MachineOperand::MO_Immediate:
288 OperandHash = Op.getImm();
289 break;
NAKAMURA Takumi3746abb2015-06-20 06:21:48 +0000290 case MachineOperand::MO_MachineBasicBlock:
291 OperandHash = Op.getMBB()->getNumber();
292 break;
293 case MachineOperand::MO_FrameIndex:
294 case MachineOperand::MO_ConstantPoolIndex:
295 case MachineOperand::MO_JumpTableIndex:
296 OperandHash = Op.getIndex();
297 break;
298 case MachineOperand::MO_GlobalAddress:
299 case MachineOperand::MO_ExternalSymbol:
300 // Global address / external symbol are too hard, don't bother, but do
301 // pull in the offset.
302 OperandHash = Op.getOffset();
303 break;
NAKAMURA Takumi34d33762015-06-20 06:22:04 +0000304 default:
305 break;
NAKAMURA Takumi3746abb2015-06-20 06:21:48 +0000306 }
307
NAKAMURA Takumi34d33762015-06-20 06:22:04 +0000308 Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
NAKAMURA Takumi3746abb2015-06-20 06:21:48 +0000309 }
310 return Hash;
311}
312
Dan Gohman2ad68de2010-05-03 14:35:47 +0000313/// HashEndOfMBB - Hash the last instruction in the MBB.
Duncan P. N. Exon Smithd3a74672016-02-27 19:48:01 +0000314static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {
315 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
316 if (I == MBB.end())
Benjamin Kramer6b568962015-06-23 14:47:29 +0000317 return 0;
NAKAMURA Takumi3746abb2015-06-20 06:21:48 +0000318
Duncan P. N. Exon Smithd3a74672016-02-27 19:48:01 +0000319 return HashMachineInstr(*I);
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000320}
321
322/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
323/// of instructions they actually have in common together at their end. Return
324/// iterators for the first shared instruction in each block.
325static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
326 MachineBasicBlock *MBB2,
327 MachineBasicBlock::iterator &I1,
328 MachineBasicBlock::iterator &I2) {
329 I1 = MBB1->end();
330 I2 = MBB2->end();
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000331
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000332 unsigned TailLen = 0;
333 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
334 --I1; --I2;
Dale Johannesen0eebdbb2010-03-08 05:38:13 +0000335 // Skip debugging pseudos; necessary to avoid changing the code.
336 while (I1->isDebugValue()) {
Dale Johannesen5ebe0c12010-03-10 05:45:47 +0000337 if (I1==MBB1->begin()) {
338 while (I2->isDebugValue()) {
339 if (I2==MBB2->begin())
340 // I1==DBG at begin; I2==DBG at begin
341 return TailLen;
342 --I2;
343 }
344 ++I2;
345 // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
Dale Johannesen0eebdbb2010-03-08 05:38:13 +0000346 return TailLen;
Dale Johannesen5ebe0c12010-03-10 05:45:47 +0000347 }
Dale Johannesen0eebdbb2010-03-08 05:38:13 +0000348 --I1;
349 }
Dale Johannesen5ebe0c12010-03-10 05:45:47 +0000350 // I1==first (untested) non-DBG preceding known match
Dale Johannesen0eebdbb2010-03-08 05:38:13 +0000351 while (I2->isDebugValue()) {
Dale Johannesen5ebe0c12010-03-10 05:45:47 +0000352 if (I2==MBB2->begin()) {
353 ++I1;
354 // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
Dale Johannesen0eebdbb2010-03-08 05:38:13 +0000355 return TailLen;
Dale Johannesen5ebe0c12010-03-10 05:45:47 +0000356 }
Dale Johannesen0eebdbb2010-03-08 05:38:13 +0000357 --I2;
358 }
Dale Johannesen5ebe0c12010-03-10 05:45:47 +0000359 // I1, I2==first (untested) non-DBGs preceding known match
Dale Johannesen0eebdbb2010-03-08 05:38:13 +0000360 if (!I1->isIdenticalTo(I2) ||
Bill Wendlingf73340e2007-10-25 19:49:32 +0000361 // FIXME: This check is dubious. It's used to get around a problem where
Bill Wendling5f7ed002007-10-25 18:23:45 +0000362 // people incorrectly expect inline asm directives to remain in the same
363 // relative order. This is untenable because normal compiler
364 // optimizations (like this one) may reorder and/or merge these
365 // directives.
Chris Lattnerb06015a2010-02-09 19:54:29 +0000366 I1->isInlineAsm()) {
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000367 ++I1; ++I2;
368 break;
369 }
370 ++TailLen;
371 }
Dale Johannesen5ebe0c12010-03-10 05:45:47 +0000372 // Back past possible debugging pseudos at beginning of block. This matters
373 // when one block differs from the other only by whether debugging pseudos
Junmo Park7cc13f22015-12-04 02:06:59 +0000374 // are present at the beginning. (This way, the various checks later for
Dale Johannesen5ebe0c12010-03-10 05:45:47 +0000375 // I1==MBB1->begin() work as expected.)
376 if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
377 --I2;
378 while (I2->isDebugValue()) {
Craig Topper2f6031c2012-10-07 20:31:05 +0000379 if (I2 == MBB2->begin())
Dale Johannesen5ebe0c12010-03-10 05:45:47 +0000380 return TailLen;
Dale Johannesen5ebe0c12010-03-10 05:45:47 +0000381 --I2;
382 }
383 ++I2;
384 }
385 if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
386 --I1;
387 while (I1->isDebugValue()) {
388 if (I1 == MBB1->begin())
389 return TailLen;
390 --I1;
391 }
392 ++I1;
393 }
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000394 return TailLen;
395}
396
Eli Friedmanbf007362011-07-06 23:41:48 +0000397void BranchFolder::MaintainLiveIns(MachineBasicBlock *CurMBB,
398 MachineBasicBlock *NewMBB) {
Evan Cheng6cc8d492012-01-07 03:35:48 +0000399 if (RS) {
400 RS->enterBasicBlock(CurMBB);
401 if (!CurMBB->empty())
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000402 RS->forward(std::prev(CurMBB->end()));
Pedro Artigasec7cbd72014-08-04 23:07:49 +0000403 for (unsigned int i = 1, e = TRI->getNumRegs(); i != e; i++)
404 if (RS->isRegUsed(i, false))
Evan Cheng6cc8d492012-01-07 03:35:48 +0000405 NewMBB->addLiveIn(i);
406 }
Eli Friedmanbf007362011-07-06 23:41:48 +0000407}
408
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000409/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000410/// after it, replacing it with an unconditional branch to NewDest.
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000411void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
412 MachineBasicBlock *NewDest) {
Eli Friedmanbf007362011-07-06 23:41:48 +0000413 MachineBasicBlock *CurMBB = OldInst->getParent();
414
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000415 TII->ReplaceTailWithBranchTo(OldInst, NewDest);
Eli Friedmanbf007362011-07-06 23:41:48 +0000416
417 // For targets that use the register scavenger, we must maintain LiveIns.
418 MaintainLiveIns(CurMBB, NewDest);
419
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000420 ++NumTailMerge;
421}
422
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000423/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
424/// MBB so that the part before the iterator falls into the part starting at the
425/// iterator. This returns the new MBB.
426MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
Andrew Trick97a1d7c2013-06-24 01:55:01 +0000427 MachineBasicBlock::iterator BBI1,
428 const BasicBlock *BB) {
Evan Cheng37bb6172010-06-22 01:18:16 +0000429 if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
Craig Topperc0196b12014-04-14 00:51:57 +0000430 return nullptr;
Evan Cheng37bb6172010-06-22 01:18:16 +0000431
Dan Gohman3b460302008-07-07 23:14:23 +0000432 MachineFunction &MF = *CurMBB.getParent();
433
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000434 // Create the fall-through block.
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +0000435 MachineFunction::iterator MBBI = CurMBB.getIterator();
Andrew Trick97a1d7c2013-06-24 01:55:01 +0000436 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
Dan Gohman3b460302008-07-07 23:14:23 +0000437 CurMBB.getParent()->insert(++MBBI, NewMBB);
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000438
439 // Move all the successors of this block to the specified block.
Dan Gohman6f880692008-06-19 17:22:29 +0000440 NewMBB->transferSuccessors(&CurMBB);
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000441
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000442 // Add an edge from CurMBB to NewMBB for the fall-through.
443 CurMBB.addSuccessor(NewMBB);
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000444
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000445 // Splice the code over.
446 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesend05a1a22007-03-20 21:35:06 +0000447
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000448 // NewMBB inherits CurMBB's block frequency.
449 MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
450
Dale Johannesend05a1a22007-03-20 21:35:06 +0000451 // For targets that use the register scavenger, we must maintain LiveIns.
Eli Friedmanbf007362011-07-06 23:41:48 +0000452 MaintainLiveIns(&CurMBB, NewMBB);
Dale Johannesend05a1a22007-03-20 21:35:06 +0000453
David Majnemer16193552015-10-04 02:22:52 +0000454 // Add the new block to the funclet.
455 const auto &FuncletI = FuncletMembership.find(&CurMBB);
456 if (FuncletI != FuncletMembership.end())
457 FuncletMembership[NewMBB] = FuncletI->second;
458
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000459 return NewMBB;
460}
461
Chris Lattner7cee6dd2006-11-01 19:36:29 +0000462/// EstimateRuntime - Make a rough estimate for how long it will take to run
463/// the specified code.
464static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
Chris Lattnera98c6792008-01-07 01:56:04 +0000465 MachineBasicBlock::iterator E) {
Chris Lattner7cee6dd2006-11-01 19:36:29 +0000466 unsigned Time = 0;
467 for (; I != E; ++I) {
Dale Johannesen2061c842010-03-05 00:02:59 +0000468 if (I->isDebugValue())
469 continue;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000470 if (I->isCall())
Chris Lattner7cee6dd2006-11-01 19:36:29 +0000471 Time += 10;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000472 else if (I->mayLoad() || I->mayStore())
Chris Lattner7cee6dd2006-11-01 19:36:29 +0000473 Time += 2;
474 else
475 ++Time;
476 }
477 return Time;
478}
479
Dale Johannesen6e16d092007-05-10 01:01:49 +0000480// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
481// branches temporarily for tail merging). In the case where CurMBB ends
482// with a conditional branch to the next block, optimize by reversing the
483// test and conditionally branching to SuccMBB instead.
Bob Wilson3794ec22009-11-16 18:08:46 +0000484static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
Dale Johannesen6e16d092007-05-10 01:01:49 +0000485 const TargetInstrInfo *TII) {
486 MachineFunction *MF = CurMBB->getParent();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000487 MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
Craig Topperc0196b12014-04-14 00:51:57 +0000488 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000489 SmallVector<MachineOperand, 4> Cond;
Stuart Hastings0125b642010-06-17 22:43:56 +0000490 DebugLoc dl; // FIXME: this is nowhere
Dale Johannesen6e16d092007-05-10 01:01:49 +0000491 if (I != MF->end() &&
Evan Cheng64dfcac2009-02-09 07:14:22 +0000492 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +0000493 MachineBasicBlock *NextBB = &*I;
Dale Johannesen66da8b52008-05-09 23:28:24 +0000494 if (TBB == NextBB && !Cond.empty() && !FBB) {
Dale Johannesen6e16d092007-05-10 01:01:49 +0000495 if (!TII->ReverseBranchCondition(Cond)) {
496 TII->RemoveBranch(*CurMBB);
Craig Topperc0196b12014-04-14 00:51:57 +0000497 TII->InsertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
Dale Johannesen6e16d092007-05-10 01:01:49 +0000498 return;
499 }
500 }
501 }
Craig Topperc0196b12014-04-14 00:51:57 +0000502 TII->InsertBranch(*CurMBB, SuccBB, nullptr,
Stuart Hastings0125b642010-06-17 22:43:56 +0000503 SmallVector<MachineOperand, 0>(), dl);
Dale Johannesen6e16d092007-05-10 01:01:49 +0000504}
505
Dan Gohman02b15542009-11-11 21:57:02 +0000506bool
507BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
508 if (getHash() < o.getHash())
509 return true;
Craig Topper2f6031c2012-10-07 20:31:05 +0000510 if (getHash() > o.getHash())
Dan Gohman02b15542009-11-11 21:57:02 +0000511 return false;
Craig Topper2f6031c2012-10-07 20:31:05 +0000512 if (getBlock()->getNumber() < o.getBlock()->getNumber())
Dan Gohman02b15542009-11-11 21:57:02 +0000513 return true;
Craig Topper2f6031c2012-10-07 20:31:05 +0000514 if (getBlock()->getNumber() > o.getBlock()->getNumber())
Dan Gohman02b15542009-11-11 21:57:02 +0000515 return false;
Craig Topper2f6031c2012-10-07 20:31:05 +0000516 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
517 // an object with itself.
Duncan Sandsd5ea1942007-07-11 08:47:55 +0000518#ifndef _GLIBCXX_DEBUG
Craig Topper2f6031c2012-10-07 20:31:05 +0000519 llvm_unreachable("Predecessor appears twice");
David Blaikie46a9f012012-01-20 21:51:11 +0000520#else
Craig Topper2f6031c2012-10-07 20:31:05 +0000521 return false;
David Blaikie46a9f012012-01-20 21:51:11 +0000522#endif
Dale Johannesena69ebdb2007-05-29 23:47:50 +0000523}
524
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000525BlockFrequency
526BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const {
527 auto I = MergedBBFreq.find(MBB);
528
529 if (I != MergedBBFreq.end())
530 return I->second;
531
532 return MBFI.getBlockFreq(MBB);
533}
534
535void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB,
536 BlockFrequency F) {
537 MergedBBFreq[MBB] = F;
538}
539
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000540/// CountTerminators - Count the number of terminators in the given
541/// block and set I to the position of the first non-terminator, if there
542/// is one, or MBB->end() otherwise.
543static unsigned CountTerminators(MachineBasicBlock *MBB,
544 MachineBasicBlock::iterator &I) {
545 I = MBB->end();
546 unsigned NumTerms = 0;
547 for (;;) {
548 if (I == MBB->begin()) {
549 I = MBB->end();
550 break;
551 }
552 --I;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000553 if (!I->isTerminator()) break;
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000554 ++NumTerms;
555 }
556 return NumTerms;
557}
558
Bob Wilson94f8f872009-10-29 18:40:06 +0000559/// ProfitableToMerge - Check if two machine basic blocks have a common tail
560/// and decide if it would be profitable to merge those tails. Return the
561/// length of the common tail and iterators to the first common instruction
562/// in each block.
David Majnemer16193552015-10-04 02:22:52 +0000563static bool
564ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
565 unsigned minCommonTailLength, unsigned &CommonTailLen,
566 MachineBasicBlock::iterator &I1,
567 MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,
568 MachineBasicBlock *PredBB,
569 DenseMap<const MachineBasicBlock *, int> &FuncletMembership) {
570 // It is never profitable to tail-merge blocks from two different funclets.
571 if (!FuncletMembership.empty()) {
572 auto Funclet1 = FuncletMembership.find(MBB1);
573 assert(Funclet1 != FuncletMembership.end());
574 auto Funclet2 = FuncletMembership.find(MBB2);
575 assert(Funclet2 != FuncletMembership.end());
576 if (Funclet1->second != Funclet2->second)
577 return false;
578 }
579
Bob Wilson94f8f872009-10-29 18:40:06 +0000580 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
Bob Wilson94f8f872009-10-29 18:40:06 +0000581 if (CommonTailLen == 0)
582 return false;
Evan Chengb8ed4622011-02-21 23:39:48 +0000583 DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
584 << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
585 << '\n');
Bob Wilson94f8f872009-10-29 18:40:06 +0000586
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000587 // It's almost always profitable to merge any number of non-terminator
588 // instructions with the block that falls through into the common successor.
589 if (MBB1 == PredBB || MBB2 == PredBB) {
590 MachineBasicBlock::iterator I;
591 unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
592 if (CommonTailLen > NumTerms)
593 return true;
594 }
595
Dan Gohman09478e92009-11-12 00:39:10 +0000596 // If one of the blocks can be completely merged and happens to be in
597 // a position where the other could fall through into it, merge any number
598 // of instructions, because it can be done without a branch.
599 // TODO: If the blocks are not adjacent, move one of them so that they are?
600 if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
601 return true;
602 if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
603 return true;
604
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000605 // If both blocks have an unconditional branch temporarily stripped out,
Dan Gohman225fa59c2009-11-13 21:02:15 +0000606 // count that as an additional common instruction for the following
607 // heuristics.
608 unsigned EffectiveTailLen = CommonTailLen;
Bob Wilson699f5b92009-11-16 17:56:13 +0000609 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
Evan Cheng7f8e5632011-12-07 07:15:52 +0000610 !MBB1->back().isBarrier() &&
611 !MBB2->back().isBarrier())
Dan Gohman225fa59c2009-11-13 21:02:15 +0000612 ++EffectiveTailLen;
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000613
614 // Check if the common tail is long enough to be worthwhile.
Dan Gohman225fa59c2009-11-13 21:02:15 +0000615 if (EffectiveTailLen >= minCommonTailLength)
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000616 return true;
617
Dan Gohman225fa59c2009-11-13 21:02:15 +0000618 // If we are optimizing for code size, 2 instructions in common is enough if
619 // we don't have to split a block. At worst we will be introducing 1 new
620 // branch instruction, which is likely to be smaller than the 2
621 // instructions that would be deleted in the merge.
Evan Chengb8ed4622011-02-21 23:39:48 +0000622 MachineFunction *MF = MBB1->getParent();
Rafael Espindola84921b92015-10-24 23:11:13 +0000623 return EffectiveTailLen >= 2 && MF->getFunction()->optForSize() &&
624 (I1 == MBB1->begin() || I2 == MBB2->begin());
Bob Wilson94f8f872009-10-29 18:40:06 +0000625}
626
Dale Johannesen66da8b52008-05-09 23:28:24 +0000627/// ComputeSameTails - Look through all the blocks in MergePotentials that have
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000628/// hash CurHash (guaranteed to match the last element). Build the vector
Dale Johannesen66da8b52008-05-09 23:28:24 +0000629/// SameTails of all those that have the (same) largest number of instructions
630/// in common of any pair of these blocks. SameTails entries contain an
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000631/// iterator into MergePotentials (from which the MachineBasicBlock can be
632/// found) and a MachineBasicBlock::iterator into that MBB indicating the
Dale Johannesen66da8b52008-05-09 23:28:24 +0000633/// instruction where the matching code sequence begins.
634/// Order of elements in SameTails is the reverse of the order in which
635/// those blocks appear in MergePotentials (where they are not necessarily
636/// consecutive).
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000637unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000638 unsigned minCommonTailLength,
639 MachineBasicBlock *SuccBB,
640 MachineBasicBlock *PredBB) {
Dale Johannesen66da8b52008-05-09 23:28:24 +0000641 unsigned maxCommonTailLength = 0U;
642 SameTails.clear();
643 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000644 MPIterator HighestMPIter = std::prev(MergePotentials.end());
645 for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000646 B = MergePotentials.begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000647 CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
648 for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
Bob Wilson94f8f872009-10-29 18:40:06 +0000649 unsigned CommonTailLen;
Dan Gohman02b15542009-11-11 21:57:02 +0000650 if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
651 minCommonTailLength,
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000652 CommonTailLen, TrialBBI1, TrialBBI2,
David Majnemer16193552015-10-04 02:22:52 +0000653 SuccBB, PredBB,
654 FuncletMembership)) {
Dale Johannesen66da8b52008-05-09 23:28:24 +0000655 if (CommonTailLen > maxCommonTailLength) {
656 SameTails.clear();
657 maxCommonTailLength = CommonTailLen;
658 HighestMPIter = CurMPIter;
Dan Gohman02b15542009-11-11 21:57:02 +0000659 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
Dale Johannesen66da8b52008-05-09 23:28:24 +0000660 }
661 if (HighestMPIter == CurMPIter &&
662 CommonTailLen == maxCommonTailLength)
Dan Gohman02b15542009-11-11 21:57:02 +0000663 SameTails.push_back(SameTailElt(I, TrialBBI2));
Dale Johannesen66da8b52008-05-09 23:28:24 +0000664 }
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000665 if (I == B)
Dale Johannesen66da8b52008-05-09 23:28:24 +0000666 break;
667 }
668 }
669 return maxCommonTailLength;
670}
671
672/// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
673/// MergePotentials, restoring branches at ends of blocks as appropriate.
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000674void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
Bob Wilson3794ec22009-11-16 18:08:46 +0000675 MachineBasicBlock *SuccBB,
676 MachineBasicBlock *PredBB) {
Dale Johannesenb28a17c2008-05-23 17:19:02 +0000677 MPIterator CurMPIter, B;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000678 for (CurMPIter = std::prev(MergePotentials.end()),
679 B = MergePotentials.begin();
680 CurMPIter->getHash() == CurHash; --CurMPIter) {
Dale Johannesen66da8b52008-05-09 23:28:24 +0000681 // Put the unconditional branch back, if we need one.
Dan Gohman02b15542009-11-11 21:57:02 +0000682 MachineBasicBlock *CurMBB = CurMPIter->getBlock();
Dale Johannesen66da8b52008-05-09 23:28:24 +0000683 if (SuccBB && CurMBB != PredBB)
684 FixTail(CurMBB, SuccBB, TII);
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000685 if (CurMPIter == B)
Dale Johannesen66da8b52008-05-09 23:28:24 +0000686 break;
687 }
Dan Gohman02b15542009-11-11 21:57:02 +0000688 if (CurMPIter->getHash() != CurHash)
Dale Johannesenb28a17c2008-05-23 17:19:02 +0000689 CurMPIter++;
690 MergePotentials.erase(CurMPIter, MergePotentials.end());
Dale Johannesen66da8b52008-05-09 23:28:24 +0000691}
692
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000693/// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
694/// only of the common tail. Create a block that does by splitting one.
Evan Cheng37bb6172010-06-22 01:18:16 +0000695bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
Andrew Trick97a1d7c2013-06-24 01:55:01 +0000696 MachineBasicBlock *SuccBB,
Evan Cheng37bb6172010-06-22 01:18:16 +0000697 unsigned maxCommonTailLength,
698 unsigned &commonTailIndex) {
699 commonTailIndex = 0;
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000700 unsigned TimeEstimate = ~0U;
Dan Gohmanb3bf49f2009-11-12 01:51:28 +0000701 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000702 // Use PredBB if possible; that doesn't require a new branch.
Dan Gohman02b15542009-11-11 21:57:02 +0000703 if (SameTails[i].getBlock() == PredBB) {
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000704 commonTailIndex = i;
705 break;
706 }
707 // Otherwise, make a (fairly bogus) choice based on estimate of
708 // how long it will take the various blocks to execute.
Dan Gohman02b15542009-11-11 21:57:02 +0000709 unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
710 SameTails[i].getTailStartPos());
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000711 if (t <= TimeEstimate) {
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000712 TimeEstimate = t;
713 commonTailIndex = i;
714 }
715 }
716
Dan Gohman02b15542009-11-11 21:57:02 +0000717 MachineBasicBlock::iterator BBI =
718 SameTails[commonTailIndex].getTailStartPos();
719 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000720
Dale Johannesen0eebdbb2010-03-08 05:38:13 +0000721 // If the common tail includes any debug info we will take it pretty
722 // randomly from one of the inputs. Might be better to remove it?
David Greened60abbf2009-12-24 00:34:21 +0000723 DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
Bill Wendlingc3f05e82009-08-22 20:03:00 +0000724 << maxCommonTailLength);
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000725
Andrew Trick97a1d7c2013-06-24 01:55:01 +0000726 // If the split block unconditionally falls-thru to SuccBB, it will be
727 // merged. In control flow terms it should then take SuccBB's name. e.g. If
728 // SuccBB is an inner loop, the common tail is still part of the inner loop.
729 const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
730 SuccBB->getBasicBlock() : MBB->getBasicBlock();
731 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
Evan Cheng37bb6172010-06-22 01:18:16 +0000732 if (!newMBB) {
733 DEBUG(dbgs() << "... failed!");
734 return false;
735 }
736
Dan Gohman02b15542009-11-11 21:57:02 +0000737 SameTails[commonTailIndex].setBlock(newMBB);
738 SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000739
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000740 // If we split PredBB, newMBB is the new predecessor.
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000741 if (PredBB == MBB)
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000742 PredBB = newMBB;
743
Evan Cheng37bb6172010-06-22 01:18:16 +0000744 return true;
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000745}
746
Chad Rosier3b67c8d2015-03-10 16:22:52 +0000747static void
Rafael Espindola71bd70c2015-12-04 04:15:05 +0000748removeMMOsFromMemoryOperations(MachineBasicBlock::iterator MBBIStartPos,
749 MachineBasicBlock &MBBCommon) {
750 // Remove MMOs from memory operations in the common block
751 // when they do not match the ones from the block being tail-merged.
752 // This ensures later passes conservatively compute dependencies.
Chad Rosier3b67c8d2015-03-10 16:22:52 +0000753 MachineBasicBlock *MBB = MBBIStartPos->getParent();
754 // Note CommonTailLen does not necessarily matches the size of
755 // the common BB nor all its instructions because of debug
756 // instructions differences.
757 unsigned CommonTailLen = 0;
758 for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
759 ++CommonTailLen;
760
761 MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
Chad Rosier99fb8d12015-03-10 20:29:59 +0000762 MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
Chad Rosier3b67c8d2015-03-10 16:22:52 +0000763 MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
764 MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
765
766 while (CommonTailLen--) {
Chad Rosier99fb8d12015-03-10 20:29:59 +0000767 assert(MBBI != MBBIE && "Reached BB end within common tail length!");
768 (void)MBBIE;
Chad Rosier3b67c8d2015-03-10 16:22:52 +0000769
770 if (MBBI->isDebugValue()) {
771 ++MBBI;
772 continue;
773 }
774
775 while ((MBBICommon != MBBIECommon) && MBBICommon->isDebugValue())
776 ++MBBICommon;
777
778 assert(MBBICommon != MBBIECommon &&
779 "Reached BB end within common tail length!");
780 assert(MBBICommon->isIdenticalTo(&*MBBI) && "Expected matching MIIs!");
781
782 if (MBBICommon->mayLoad() || MBBICommon->mayStore())
Junmo Park7ceec0b2016-01-11 07:15:38 +0000783 MBBICommon->setMemRefs(MBBICommon->mergeMemRefsWith(*MBBI));
Chad Rosier3b67c8d2015-03-10 16:22:52 +0000784
785 ++MBBI;
786 ++MBBICommon;
787 }
788}
789
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000790// See if any of the blocks in MergePotentials (which all have a common single
791// successor, or all have no successor) can be tail-merged. If there is a
792// successor, any blocks in MergePotentials that are not tail-merged and
793// are not immediately before Succ must have an unconditional branch to
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000794// Succ added (but the predecessor/successor lists need no adjustment).
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000795// The lone predecessor of Succ that falls through into Succ,
796// if any, is given in PredBB.
797
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000798bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
Bob Wilson3794ec22009-11-16 18:08:46 +0000799 MachineBasicBlock *PredBB) {
Evan Cheng3d2fce02009-09-04 07:47:40 +0000800 bool MadeChange = false;
801
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000802 // Except for the special cases below, tail-merge if there are at least
803 // this many instructions in common.
804 unsigned minCommonTailLength = TailMergeSize;
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000805
David Greened60abbf2009-12-24 00:34:21 +0000806 DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000807 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
David Greened60abbf2009-12-24 00:34:21 +0000808 dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000809 << (i == e-1 ? "" : ", ");
David Greened60abbf2009-12-24 00:34:21 +0000810 dbgs() << "\n";
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000811 if (SuccBB) {
David Greened60abbf2009-12-24 00:34:21 +0000812 dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n';
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000813 if (PredBB)
David Greened60abbf2009-12-24 00:34:21 +0000814 dbgs() << " which has fall-through from BB#"
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000815 << PredBB->getNumber() << "\n";
816 }
David Greened60abbf2009-12-24 00:34:21 +0000817 dbgs() << "Looking for common tails of at least "
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000818 << minCommonTailLength << " instruction"
819 << (minCommonTailLength == 1 ? "" : "s") << '\n';
820 );
Dale Johannesen66da8b52008-05-09 23:28:24 +0000821
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000822 // Sort by hash value so that blocks with identical end sequences sort
823 // together.
Benjamin Kramer848c9fa2015-03-13 21:17:02 +0000824 array_pod_sort(MergePotentials.begin(), MergePotentials.end());
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000825
826 // Walk through equivalence sets looking for actual exact matches.
827 while (MergePotentials.size() > 1) {
Dan Gohman02b15542009-11-11 21:57:02 +0000828 unsigned CurHash = MergePotentials.back().getHash();
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000829
Dale Johannesen66da8b52008-05-09 23:28:24 +0000830 // Build SameTails, identifying the set of blocks with this hash code
831 // and with the maximum number of instructions in common.
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000832 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000833 minCommonTailLength,
834 SuccBB, PredBB);
Dale Johannesenf4a77d22007-05-23 21:07:20 +0000835
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000836 // If we didn't find any pair that has at least minCommonTailLength
Dale Johannesencff7df22008-05-09 21:24:35 +0000837 // instructions in common, remove all blocks with this hash code and retry.
838 if (SameTails.empty()) {
Dale Johannesen66da8b52008-05-09 23:28:24 +0000839 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
Dale Johannesenf4a77d22007-05-23 21:07:20 +0000840 continue;
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000841 }
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000842
Dale Johannesencff7df22008-05-09 21:24:35 +0000843 // If one of the blocks is the entire common tail (and not the entry
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000844 // block, which we can't jump to), we can treat all blocks with this same
845 // tail at once. Use PredBB if that is one of the possibilities, as that
846 // will not introduce any extra branches.
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +0000847 MachineBasicBlock *EntryBB =
848 &MergePotentials.front().getBlock()->getParent()->front();
Dan Gohman02b15542009-11-11 21:57:02 +0000849 unsigned commonTailIndex = SameTails.size();
Dan Gohman09478e92009-11-12 00:39:10 +0000850 // If there are two blocks, check to see if one can be made to fall through
851 // into the other.
852 if (SameTails.size() == 2 &&
853 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
854 SameTails[1].tailIsWholeBlock())
855 commonTailIndex = 1;
856 else if (SameTails.size() == 2 &&
857 SameTails[1].getBlock()->isLayoutSuccessor(
858 SameTails[0].getBlock()) &&
859 SameTails[0].tailIsWholeBlock())
860 commonTailIndex = 0;
861 else {
862 // Otherwise just pick one, favoring the fall-through predecessor if
863 // there is one.
864 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
865 MachineBasicBlock *MBB = SameTails[i].getBlock();
866 if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
867 continue;
868 if (MBB == PredBB) {
869 commonTailIndex = i;
870 break;
871 }
872 if (SameTails[i].tailIsWholeBlock())
873 commonTailIndex = i;
Dale Johannesencff7df22008-05-09 21:24:35 +0000874 }
Dale Johannesencff7df22008-05-09 21:24:35 +0000875 }
Dale Johannesen3c0a1372007-06-01 23:02:45 +0000876
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000877 if (commonTailIndex == SameTails.size() ||
Dan Gohman02b15542009-11-11 21:57:02 +0000878 (SameTails[commonTailIndex].getBlock() == PredBB &&
879 !SameTails[commonTailIndex].tailIsWholeBlock())) {
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000880 // None of the blocks consist entirely of the common tail.
881 // Split a block so that one does.
Andrew Trick97a1d7c2013-06-24 01:55:01 +0000882 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
Evan Cheng37bb6172010-06-22 01:18:16 +0000883 maxCommonTailLength, commonTailIndex)) {
884 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
885 continue;
886 }
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000887 }
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000888
Dan Gohman02b15542009-11-11 21:57:02 +0000889 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000890
891 // Recompute commont tail MBB's edge weights and block frequency.
892 setCommonTailEdgeWeights(*MBB);
893
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000894 // MBB is common tail. Adjust all other BB's to jump to this one.
895 // Traversal must be forwards so erases work.
David Greened60abbf2009-12-24 00:34:21 +0000896 DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000897 << " for ");
898 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000899 if (commonTailIndex == i)
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000900 continue;
David Greened60abbf2009-12-24 00:34:21 +0000901 DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000902 << (i == e-1 ? "" : ", "));
Rafael Espindola71bd70c2015-12-04 04:15:05 +0000903 // Remove MMOs from memory operations as needed.
904 removeMMOsFromMemoryOperations(SameTails[i].getTailStartPos(), *MBB);
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000905 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
Dan Gohman02b15542009-11-11 21:57:02 +0000906 ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000907 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
Dan Gohman02b15542009-11-11 21:57:02 +0000908 MergePotentials.erase(SameTails[i].getMPIter());
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000909 }
David Greened60abbf2009-12-24 00:34:21 +0000910 DEBUG(dbgs() << "\n");
Dale Johannesenc4c4d8e2008-05-12 20:33:57 +0000911 // We leave commonTailIndex in the worklist in case there are other blocks
912 // that match it with a smaller number of instructions.
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000913 MadeChange = true;
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000914 }
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000915 return MadeChange;
916}
917
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000918bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
Evan Cheng3d2fce02009-09-04 07:47:40 +0000919 bool MadeChange = false;
Bill Wendling041793c2012-05-23 22:09:50 +0000920 if (!EnableTailMerge) return MadeChange;
Dale Johannesen6e16d092007-05-10 01:01:49 +0000921
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000922 // First find blocks with no successors.
Dale Johannesen6e16d092007-05-10 01:01:49 +0000923 MergePotentials.clear();
Craig Topper5db36df2015-09-16 03:52:35 +0000924 for (MachineBasicBlock &MBB : MF) {
925 if (MergePotentials.size() == TailMergeThreshold)
926 break;
927 if (!TriedMerging.count(&MBB) && MBB.succ_empty())
Duncan P. N. Exon Smithd3a74672016-02-27 19:48:01 +0000928 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB));
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000929 }
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000930
Rafael Espindola3aeaf9e2011-06-14 15:31:54 +0000931 // If this is a large problem, avoid visiting the same basic blocks
932 // multiple times.
933 if (MergePotentials.size() == TailMergeThreshold)
934 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
935 TriedMerging.insert(MergePotentials[i].getBlock());
Bill Wendling041793c2012-05-23 22:09:50 +0000936
Dale Johannesen6e16d092007-05-10 01:01:49 +0000937 // See if we can do any tail merging on those.
Rafael Espindola3aeaf9e2011-06-14 15:31:54 +0000938 if (MergePotentials.size() >= 2)
Craig Topperc0196b12014-04-14 00:51:57 +0000939 MadeChange |= TryTailMergeBlocks(nullptr, nullptr);
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000940
Dale Johannesen6e16d092007-05-10 01:01:49 +0000941 // Look at blocks (IBB) with multiple predecessors (PBB).
942 // We change each predecessor to a canonical form, by
943 // (1) temporarily removing any unconditional branch from the predecessor
944 // to IBB, and
945 // (2) alter conditional branches so they branch to the other block
Dan Gohmanc86b5a12009-11-11 18:38:14 +0000946 // not IBB; this may require adding back an unconditional branch to IBB
Dale Johannesen6e16d092007-05-10 01:01:49 +0000947 // later, where there wasn't one coming in. E.g.
948 // Bcc IBB
949 // fallthrough to QBB
950 // here becomes
951 // Bncc QBB
952 // with a conceptual B to IBB after that, which never actually exists.
953 // With those changes, we see whether the predecessors' tails match,
954 // and merge them if so. We change things out of canonical form and
955 // back to the way they were later in the process. (OptimizeBranches
956 // would undo some of this, but we can't use it, because we'd get into
957 // a compile-time infinite loop repeatedly doing and undoing the same
958 // transformations.)
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000959
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000960 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
Dan Gohman64b5d0f2009-11-11 19:48:59 +0000961 I != E; ++I) {
Bill Wendlinge351e8c2012-05-23 22:12:50 +0000962 if (I->pred_size() < 2) continue;
Bill Wendling041793c2012-05-23 22:09:50 +0000963 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +0000964 MachineBasicBlock *IBB = &*I;
965 MachineBasicBlock *PredBB = &*std::prev(I);
Bill Wendling041793c2012-05-23 22:09:50 +0000966 MergePotentials.clear();
Craig Topper5db36df2015-09-16 03:52:35 +0000967 for (MachineBasicBlock *PBB : I->predecessors()) {
968 if (MergePotentials.size() == TailMergeThreshold)
969 break;
970
Bill Wendling041793c2012-05-23 22:09:50 +0000971 if (TriedMerging.count(PBB))
972 continue;
973
974 // Skip blocks that loop to themselves, can't tail merge these.
975 if (PBB == IBB)
976 continue;
977
978 // Visit each predecessor only once.
David Blaikie70573dc2014-11-19 07:49:26 +0000979 if (!UniquePreds.insert(PBB).second)
Bill Wendling041793c2012-05-23 22:09:50 +0000980 continue;
981
982 // Skip blocks which may jump to a landing pad. Can't tail merge these.
Reid Klecknered170792015-09-17 17:19:40 +0000983 if (PBB->hasEHPadSuccessor())
Bill Wendling041793c2012-05-23 22:09:50 +0000984 continue;
985
Craig Topperc0196b12014-04-14 00:51:57 +0000986 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Bill Wendling041793c2012-05-23 22:09:50 +0000987 SmallVector<MachineOperand, 4> Cond;
988 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
989 // Failing case: IBB is the target of a cbr, and we cannot reverse the
990 // branch.
991 SmallVector<MachineOperand, 4> NewCond(Cond);
992 if (!Cond.empty() && TBB == IBB) {
993 if (TII->ReverseBranchCondition(NewCond))
994 continue;
995 // This is the QBB case described above
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +0000996 if (!FBB) {
997 auto Next = ++PBB->getIterator();
998 if (Next != MF.end())
999 FBB = &*Next;
1000 }
Dale Johannesen9a25b3a2007-05-07 20:57:21 +00001001 }
Bill Wendling041793c2012-05-23 22:09:50 +00001002
1003 // Failing case: the only way IBB can be reached from PBB is via
1004 // exception handling. Happens for landing pads. Would be nice to have
1005 // a bit in the edge so we didn't have to do all this.
Reid Kleckner0e288232015-08-27 23:27:47 +00001006 if (IBB->isEHPad()) {
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001007 MachineFunction::iterator IP = ++PBB->getIterator();
Craig Topperc0196b12014-04-14 00:51:57 +00001008 MachineBasicBlock *PredNextBB = nullptr;
Bill Wendling041793c2012-05-23 22:09:50 +00001009 if (IP != MF.end())
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001010 PredNextBB = &*IP;
Craig Topperc0196b12014-04-14 00:51:57 +00001011 if (!TBB) {
Bill Wendling041793c2012-05-23 22:09:50 +00001012 if (IBB != PredNextBB) // fallthrough
1013 continue;
1014 } else if (FBB) {
1015 if (TBB != IBB && FBB != IBB) // cbr then ubr
1016 continue;
1017 } else if (Cond.empty()) {
1018 if (TBB != IBB) // ubr
1019 continue;
1020 } else {
1021 if (TBB != IBB && IBB != PredNextBB) // cbr
1022 continue;
1023 }
1024 }
1025
1026 // Remove the unconditional branch at the end, if any.
1027 if (TBB && (Cond.empty() || FBB)) {
1028 DebugLoc dl; // FIXME: this is nowhere
1029 TII->RemoveBranch(*PBB);
1030 if (!Cond.empty())
1031 // reinsert conditional branch only, for now
Craig Topperc0196b12014-04-14 00:51:57 +00001032 TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
1033 NewCond, dl);
Bill Wendling041793c2012-05-23 22:09:50 +00001034 }
1035
Duncan P. N. Exon Smithd3a74672016-02-27 19:48:01 +00001036 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(*PBB), PBB));
Dale Johannesen9a25b3a2007-05-07 20:57:21 +00001037 }
Dale Johannesen9a25b3a2007-05-07 20:57:21 +00001038 }
Bill Wendling041793c2012-05-23 22:09:50 +00001039
1040 // If this is a large problem, avoid visiting the same basic blocks multiple
1041 // times.
1042 if (MergePotentials.size() == TailMergeThreshold)
1043 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
1044 TriedMerging.insert(MergePotentials[i].getBlock());
1045
1046 if (MergePotentials.size() >= 2)
1047 MadeChange |= TryTailMergeBlocks(IBB, PredBB);
1048
1049 // Reinsert an unconditional branch if needed. The 1 below can occur as a
1050 // result of removing blocks in TryTailMergeBlocks.
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001051 PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks
Bill Wendling041793c2012-05-23 22:09:50 +00001052 if (MergePotentials.size() == 1 &&
1053 MergePotentials.begin()->getBlock() != PredBB)
1054 FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
Dale Johannesen9a25b3a2007-05-07 20:57:21 +00001055 }
Bill Wendling041793c2012-05-23 22:09:50 +00001056
Dale Johannesen9a25b3a2007-05-07 20:57:21 +00001057 return MadeChange;
1058}
Chris Lattner60c9d4d2006-10-21 00:47:49 +00001059
Akira Hatanakabbd33f62014-08-07 19:30:13 +00001060void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
1061 SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
1062 BlockFrequency AccumulatedMBBFreq;
1063
1064 // Aggregate edge frequency of successor edge j:
1065 // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1066 // where bb is a basic block that is in SameTails.
1067 for (const auto &Src : SameTails) {
1068 const MachineBasicBlock *SrcMBB = Src.getBlock();
1069 BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
1070 AccumulatedMBBFreq += BlockFreq;
1071
1072 // It is not necessary to recompute edge weights if TailBB has less than two
1073 // successors.
1074 if (TailMBB.succ_size() <= 1)
1075 continue;
1076
1077 auto EdgeFreq = EdgeFreqLs.begin();
1078
1079 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1080 SuccI != SuccE; ++SuccI, ++EdgeFreq)
1081 *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
1082 }
1083
1084 MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1085
1086 if (TailMBB.succ_size() <= 1)
1087 return;
1088
Cong Houd97c1002015-12-01 05:29:22 +00001089 auto SumEdgeFreq =
1090 std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0))
1091 .getFrequency();
Akira Hatanakabbd33f62014-08-07 19:30:13 +00001092 auto EdgeFreq = EdgeFreqLs.begin();
1093
Cong Houd97c1002015-12-01 05:29:22 +00001094 if (SumEdgeFreq > 0) {
1095 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1096 SuccI != SuccE; ++SuccI, ++EdgeFreq) {
1097 auto Prob = BranchProbability::getBranchProbability(
1098 EdgeFreq->getFrequency(), SumEdgeFreq);
1099 TailMBB.setSuccProbability(SuccI, Prob);
1100 }
1101 }
Akira Hatanakabbd33f62014-08-07 19:30:13 +00001102}
1103
Chris Lattner60c9d4d2006-10-21 00:47:49 +00001104//===----------------------------------------------------------------------===//
1105// Branch Optimization
1106//===----------------------------------------------------------------------===//
1107
1108bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
Evan Cheng3d2fce02009-09-04 07:47:40 +00001109 bool MadeChange = false;
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001110
Dale Johannesen12920dd2007-02-17 00:44:34 +00001111 // Make sure blocks are numbered in order
1112 MF.RenumberBlocks();
David Majnemer16193552015-10-04 02:22:52 +00001113 // Renumbering blocks alters funclet membership, recalculate it.
1114 FuncletMembership = getFuncletMembership(MF);
Dale Johannesen12920dd2007-02-17 00:44:34 +00001115
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001116 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
Evan Chengcfdf3392011-05-12 00:56:58 +00001117 I != E; ) {
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001118 MachineBasicBlock *MBB = &*I++;
Evan Cheng3d2fce02009-09-04 07:47:40 +00001119 MadeChange |= OptimizeBlock(MBB);
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001120
Chris Lattner60c9d4d2006-10-21 00:47:49 +00001121 // If it is dead, remove it.
Jim Laskey9df1a1d2007-02-22 16:39:03 +00001122 if (MBB->pred_empty()) {
Chris Lattner60c9d4d2006-10-21 00:47:49 +00001123 RemoveDeadBlock(MBB);
1124 MadeChange = true;
1125 ++NumDeadBlocks;
1126 }
1127 }
David Majnemer16193552015-10-04 02:22:52 +00001128
Chris Lattner60c9d4d2006-10-21 00:47:49 +00001129 return MadeChange;
1130}
1131
Dale Johannesen5ebe0c12010-03-10 05:45:47 +00001132// Blocks should be considered empty if they contain only debug info;
1133// else the debug info would affect codegen.
1134static bool IsEmptyBlock(MachineBasicBlock *MBB) {
Benjamin Kramer6b568962015-06-23 14:47:29 +00001135 return MBB->getFirstNonDebugInstr() == MBB->end();
Dale Johannesen5ebe0c12010-03-10 05:45:47 +00001136}
Chris Lattner60c9d4d2006-10-21 00:47:49 +00001137
Dale Johannesene9b361b2010-03-10 19:57:56 +00001138// Blocks with only debug info and branches should be considered the same
1139// as blocks with only branches.
1140static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
Benjamin Kramer6b568962015-06-23 14:47:29 +00001141 MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
1142 assert(I != MBB->end() && "empty block!");
1143 return I->isBranch();
Dale Johannesene9b361b2010-03-10 19:57:56 +00001144}
1145
Chris Lattner47ce2612006-11-18 20:47:54 +00001146/// IsBetterFallthrough - Return true if it would be clearly better to
1147/// fall-through to MBB1 than to fall through into MBB2. This has to return
1148/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1149/// result in infinite loops.
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001150static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
Chris Lattnera98c6792008-01-07 01:56:04 +00001151 MachineBasicBlock *MBB2) {
Chris Lattner7acdc17f2006-11-18 21:30:35 +00001152 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
1153 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattner47ce2612006-11-18 20:47:54 +00001154 // optimize branches that branch to either a return block or an assert block
1155 // into a fallthrough to the return.
Benjamin Kramer6b568962015-06-23 14:47:29 +00001156 MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();
1157 MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();
1158 if (MBB1I == MBB1->end() || MBB2I == MBB2->end())
1159 return false;
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001160
Christopher Lambd202e032007-12-10 07:24:06 +00001161 // If there is a clear successor ordering we make sure that one block
1162 // will fall through to the next
1163 if (MBB1->isSuccessor(MBB2)) return true;
1164 if (MBB2->isSuccessor(MBB1)) return false;
Chris Lattner47ce2612006-11-18 20:47:54 +00001165
Evan Cheng7f8e5632011-12-07 07:15:52 +00001166 return MBB2I->isCall() && !MBB1I->isCall();
Chris Lattner47ce2612006-11-18 20:47:54 +00001167}
1168
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001169/// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
Benjamin Kramer6b568962015-06-23 14:47:29 +00001170/// instructions on the block.
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001171static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
Benjamin Kramer6b568962015-06-23 14:47:29 +00001172 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1173 if (I != MBB.end() && I->isBranch())
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001174 return I->getDebugLoc();
1175 return DebugLoc();
1176}
1177
Chris Lattner3218e0e2006-10-14 00:21:48 +00001178/// OptimizeBlock - Analyze and optimize control flow related to the specified
1179/// block. This is never called on the entry block.
Evan Cheng3d2fce02009-09-04 07:47:40 +00001180bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1181 bool MadeChange = false;
Dan Gohmanf4141f12009-11-11 18:18:34 +00001182 MachineFunction &MF = *MBB->getParent();
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001183ReoptimizeBlock:
Evan Cheng3d2fce02009-09-04 07:47:40 +00001184
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001185 MachineFunction::iterator FallThrough = MBB->getIterator();
Chris Lattnerceb51d82006-10-24 01:12:32 +00001186 ++FallThrough;
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001187
David Majnemer16193552015-10-04 02:22:52 +00001188 // Make sure MBB and FallThrough belong to the same funclet.
1189 bool SameFunclet = true;
1190 if (!FuncletMembership.empty() && FallThrough != MF.end()) {
1191 auto MBBFunclet = FuncletMembership.find(MBB);
1192 assert(MBBFunclet != FuncletMembership.end());
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001193 auto FallThroughFunclet = FuncletMembership.find(&*FallThrough);
David Majnemer16193552015-10-04 02:22:52 +00001194 assert(FallThroughFunclet != FuncletMembership.end());
1195 SameFunclet = MBBFunclet->second == FallThroughFunclet->second;
1196 }
1197
Chris Lattner3e8e57c2006-10-13 20:43:10 +00001198 // If this block is empty, make everyone use its fall-through, not the block
Dale Johannesen1a401e62007-05-31 21:54:00 +00001199 // explicitly. Landing pads should not do this since the landing-pad table
Dan Gohman64997902009-10-30 02:13:27 +00001200 // points to this block. Blocks with their addresses taken shouldn't be
1201 // optimized away.
David Majnemer16193552015-10-04 02:22:52 +00001202 if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&
1203 SameFunclet) {
Chris Lattner4fe01c42006-10-21 05:08:28 +00001204 // Dead block? Leave for cleanup later.
Evan Cheng3d2fce02009-09-04 07:47:40 +00001205 if (MBB->pred_empty()) return MadeChange;
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001206
Dan Gohmanf4141f12009-11-11 18:18:34 +00001207 if (FallThrough == MF.end()) {
Chris Lattner56c9d252006-10-17 17:13:52 +00001208 // TODO: Simplify preds to not branch here if possible!
Reid Kleckner0e288232015-08-27 23:27:47 +00001209 } else if (FallThrough->isEHPad()) {
Pete Cooper4d8d2ec2015-04-30 18:58:23 +00001210 // Don't rewrite to a landing pad fallthough. That could lead to the case
1211 // where a BB jumps to more than one landing pad.
1212 // TODO: Is it ever worth rewriting predecessors which don't already
1213 // jump to a landing pad, and so can safely jump to the fallthrough?
Chris Lattner56c9d252006-10-17 17:13:52 +00001214 } else {
1215 // Rewrite all predecessors of the old block to go to the fallthrough
1216 // instead.
Jim Laskey9df1a1d2007-02-22 16:39:03 +00001217 while (!MBB->pred_empty()) {
Chris Lattner3218e0e2006-10-14 00:21:48 +00001218 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001219 Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
Chris Lattner3218e0e2006-10-14 00:21:48 +00001220 }
Chris Lattner56c9d252006-10-17 17:13:52 +00001221 // If MBB was the target of a jump table, update jump tables to go to the
1222 // fallthrough instead.
Chris Lattnerb6db2c62010-01-25 23:26:13 +00001223 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001224 MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
Chris Lattner3218e0e2006-10-14 00:21:48 +00001225 MadeChange = true;
Chris Lattner25e48dd2004-07-31 10:01:27 +00001226 }
Evan Cheng3d2fce02009-09-04 07:47:40 +00001227 return MadeChange;
Chris Lattner25e48dd2004-07-31 10:01:27 +00001228 }
1229
Chris Lattner3218e0e2006-10-14 00:21:48 +00001230 // Check to see if we can simplify the terminator of the block before this
1231 // one.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001232 MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
Chris Lattnerbca3e292006-10-17 18:16:40 +00001233
Craig Topperc0196b12014-04-14 00:51:57 +00001234 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001235 SmallVector<MachineOperand, 4> PriorCond;
Chris Lattner504eeda2006-10-29 21:05:41 +00001236 bool PriorUnAnalyzable =
Evan Cheng64dfcac2009-02-09 07:14:22 +00001237 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
Chris Lattner4fe01c42006-10-21 05:08:28 +00001238 if (!PriorUnAnalyzable) {
1239 // If the CFG for the prior block has extra edges, remove them.
Evan Cheng2afd7022007-06-18 22:43:58 +00001240 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1241 !PriorCond.empty());
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001242
Chris Lattner3218e0e2006-10-14 00:21:48 +00001243 // If the previous branch is conditional and both conditions go to the same
Chris Lattner3ca52182006-10-21 05:43:30 +00001244 // destination, remove the branch, replacing it with an unconditional one or
1245 // a fall-through.
Chris Lattner3218e0e2006-10-14 00:21:48 +00001246 if (PriorTBB && PriorTBB == PriorFBB) {
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001247 DebugLoc dl = getBranchDebugLoc(PrevBB);
Chris Lattner4fe01c42006-10-21 05:08:28 +00001248 TII->RemoveBranch(PrevBB);
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001249 PriorCond.clear();
Chris Lattnerceb51d82006-10-24 01:12:32 +00001250 if (PriorTBB != MBB)
Craig Topperc0196b12014-04-14 00:51:57 +00001251 TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
Chris Lattner3218e0e2006-10-14 00:21:48 +00001252 MadeChange = true;
Chris Lattner60c9d4d2006-10-21 00:47:49 +00001253 ++NumBranchOpts;
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001254 goto ReoptimizeBlock;
Chris Lattner3218e0e2006-10-14 00:21:48 +00001255 }
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001256
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001257 // If the previous block unconditionally falls through to this block and
1258 // this block has no other predecessors, move the contents of this block
1259 // into the prior block. This doesn't usually happen when SimplifyCFG
Bob Wilson724d8a42009-11-17 17:40:31 +00001260 // has been used, but it can happen if tail merging splits a fall-through
1261 // predecessor of a block.
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001262 // This has to check PrevBB->succ_size() because EH edges are ignored by
1263 // AnalyzeBranch.
1264 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1265 PrevBB.succ_size() == 1 &&
Reid Kleckner0e288232015-08-27 23:27:47 +00001266 !MBB->hasAddressTaken() && !MBB->isEHPad()) {
David Greened60abbf2009-12-24 00:34:21 +00001267 DEBUG(dbgs() << "\nMerging into block: " << PrevBB
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001268 << "From MBB: " << *MBB);
Devang Patelcdec1142011-05-26 21:49:28 +00001269 // Remove redundant DBG_VALUEs first.
Devang Patel42ddaa12011-05-26 21:47:59 +00001270 if (PrevBB.begin() != PrevBB.end()) {
1271 MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1272 --PrevBBIter;
1273 MachineBasicBlock::iterator MBBIter = MBB->begin();
Andrew Trick9e761992012-02-08 21:22:43 +00001274 // Check if DBG_VALUE at the end of PrevBB is identical to the
Devang Patelcdec1142011-05-26 21:49:28 +00001275 // DBG_VALUE at the beginning of MBB.
Devang Patel42ddaa12011-05-26 21:47:59 +00001276 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1277 && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1278 if (!MBBIter->isIdenticalTo(PrevBBIter))
1279 break;
1280 MachineInstr *DuplicateDbg = MBBIter;
1281 ++MBBIter; -- PrevBBIter;
1282 DuplicateDbg->eraseFromParent();
1283 }
1284 }
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001285 PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
Chad Rosier5dfe6da2012-02-22 17:25:00 +00001286 PrevBB.removeSuccessor(PrevBB.succ_begin());
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001287 assert(PrevBB.succ_empty());
1288 PrevBB.transferSuccessors(MBB);
1289 MadeChange = true;
1290 return MadeChange;
1291 }
Bob Wilson699f5b92009-11-16 17:56:13 +00001292
Chris Lattner3218e0e2006-10-14 00:21:48 +00001293 // If the previous branch *only* branches to *this* block (conditional or
1294 // not) remove the branch.
Craig Topperc0196b12014-04-14 00:51:57 +00001295 if (PriorTBB == MBB && !PriorFBB) {
Chris Lattner4fe01c42006-10-21 05:08:28 +00001296 TII->RemoveBranch(PrevBB);
Chris Lattner3218e0e2006-10-14 00:21:48 +00001297 MadeChange = true;
Chris Lattner60c9d4d2006-10-21 00:47:49 +00001298 ++NumBranchOpts;
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001299 goto ReoptimizeBlock;
Chris Lattner3218e0e2006-10-14 00:21:48 +00001300 }
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001301
Chris Lattner3ca52182006-10-21 05:43:30 +00001302 // If the prior block branches somewhere else on the condition and here if
1303 // the condition is false, remove the uncond second branch.
Chris Lattnerceb51d82006-10-24 01:12:32 +00001304 if (PriorFBB == MBB) {
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001305 DebugLoc dl = getBranchDebugLoc(PrevBB);
Chris Lattner3ca52182006-10-21 05:43:30 +00001306 TII->RemoveBranch(PrevBB);
Craig Topperc0196b12014-04-14 00:51:57 +00001307 TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
Chris Lattner3ca52182006-10-21 05:43:30 +00001308 MadeChange = true;
1309 ++NumBranchOpts;
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001310 goto ReoptimizeBlock;
Chris Lattner3ca52182006-10-21 05:43:30 +00001311 }
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001312
Chris Lattner28f17f42006-10-21 05:54:00 +00001313 // If the prior block branches here on true and somewhere else on false, and
1314 // if the branch condition is reversible, reverse the branch to create a
1315 // fall-through.
Chris Lattnerceb51d82006-10-24 01:12:32 +00001316 if (PriorTBB == MBB) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001317 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Chris Lattner28f17f42006-10-21 05:54:00 +00001318 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001319 DebugLoc dl = getBranchDebugLoc(PrevBB);
Chris Lattner28f17f42006-10-21 05:54:00 +00001320 TII->RemoveBranch(PrevBB);
Craig Topperc0196b12014-04-14 00:51:57 +00001321 TII->InsertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
Chris Lattner28f17f42006-10-21 05:54:00 +00001322 MadeChange = true;
1323 ++NumBranchOpts;
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001324 goto ReoptimizeBlock;
Chris Lattner28f17f42006-10-21 05:54:00 +00001325 }
1326 }
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001327
Dan Gohmanff97acd2009-10-22 00:03:58 +00001328 // If this block has no successors (e.g. it is a return block or ends with
1329 // a call to a no-return function like abort or __cxa_throw) and if the pred
1330 // falls through into this block, and if it would otherwise fall through
1331 // into the block after this, move this block to the end of the function.
Chris Lattner7acdc17f2006-11-18 21:30:35 +00001332 //
Chris Lattner47ce2612006-11-18 20:47:54 +00001333 // We consider it more likely that execution will stay in the function (e.g.
1334 // due to loops) than it is to exit it. This asserts in loops etc, moving
1335 // the assert condition out of the loop body.
Craig Topperc0196b12014-04-14 00:51:57 +00001336 if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
Chris Lattner7acdc17f2006-11-18 21:30:35 +00001337 MachineFunction::iterator(PriorTBB) == FallThrough &&
Bob Wilson2d4ff122009-11-26 00:32:21 +00001338 !MBB->canFallThrough()) {
Chris Lattner56ec81f2006-11-18 21:56:39 +00001339 bool DoTransform = true;
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001340
Chris Lattner47ce2612006-11-18 20:47:54 +00001341 // We have to be careful that the succs of PredBB aren't both no-successor
1342 // blocks. If neither have successors and if PredBB is the second from
1343 // last block in the function, we'd just keep swapping the two blocks for
1344 // last. Only do the swap if one is clearly better to fall through than
1345 // the other.
Dan Gohmanf4141f12009-11-11 18:18:34 +00001346 if (FallThrough == --MF.end() &&
Chris Lattnera98c6792008-01-07 01:56:04 +00001347 !IsBetterFallthrough(PriorTBB, MBB))
Chris Lattner56ec81f2006-11-18 21:56:39 +00001348 DoTransform = false;
1349
Chris Lattner56ec81f2006-11-18 21:56:39 +00001350 if (DoTransform) {
Chris Lattner47ce2612006-11-18 20:47:54 +00001351 // Reverse the branch so we will fall through on the previous true cond.
Owen Anderson4f6bf042008-08-14 22:49:33 +00001352 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Chris Lattner47ce2612006-11-18 20:47:54 +00001353 if (!TII->ReverseBranchCondition(NewPriorCond)) {
David Greened60abbf2009-12-24 00:34:21 +00001354 DEBUG(dbgs() << "\nMoving MBB: " << *MBB
Bill Wendlingc3f05e82009-08-22 20:03:00 +00001355 << "To make fallthrough to: " << *PriorTBB << "\n");
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001356
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001357 DebugLoc dl = getBranchDebugLoc(PrevBB);
Chris Lattner47ce2612006-11-18 20:47:54 +00001358 TII->RemoveBranch(PrevBB);
Craig Topperc0196b12014-04-14 00:51:57 +00001359 TII->InsertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
Chris Lattner47ce2612006-11-18 20:47:54 +00001360
1361 // Move this block to the end of the function.
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001362 MBB->moveAfter(&MF.back());
Chris Lattner47ce2612006-11-18 20:47:54 +00001363 MadeChange = true;
1364 ++NumBranchOpts;
Evan Cheng3d2fce02009-09-04 07:47:40 +00001365 return MadeChange;
Chris Lattner47ce2612006-11-18 20:47:54 +00001366 }
1367 }
1368 }
Chris Lattner3218e0e2006-10-14 00:21:48 +00001369 }
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001370
Chris Lattner4fe01c42006-10-21 05:08:28 +00001371 // Analyze the branch in the current block.
Craig Topperc0196b12014-04-14 00:51:57 +00001372 MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001373 SmallVector<MachineOperand, 4> CurCond;
Evan Cheng64dfcac2009-02-09 07:14:22 +00001374 bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
Chris Lattner504eeda2006-10-29 21:05:41 +00001375 if (!CurUnAnalyzable) {
Chris Lattner4fe01c42006-10-21 05:08:28 +00001376 // If the CFG for the prior block has extra edges, remove them.
Evan Cheng2afd7022007-06-18 22:43:58 +00001377 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
Chris Lattner3e8e57c2006-10-13 20:43:10 +00001378
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001379 // If this is a two-way branch, and the FBB branches to this block, reverse
Chris Lattnerbf3b57f2006-11-08 01:03:21 +00001380 // the condition so the single-basic-block loop is faster. Instead of:
1381 // Loop: xxx; jcc Out; jmp Loop
1382 // we want:
1383 // Loop: xxx; jncc Loop; jmp Out
1384 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001385 SmallVector<MachineOperand, 4> NewCond(CurCond);
Chris Lattnerbf3b57f2006-11-08 01:03:21 +00001386 if (!TII->ReverseBranchCondition(NewCond)) {
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001387 DebugLoc dl = getBranchDebugLoc(*MBB);
Chris Lattnerbf3b57f2006-11-08 01:03:21 +00001388 TII->RemoveBranch(*MBB);
Stuart Hastings0125b642010-06-17 22:43:56 +00001389 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
Chris Lattnerbf3b57f2006-11-08 01:03:21 +00001390 MadeChange = true;
1391 ++NumBranchOpts;
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001392 goto ReoptimizeBlock;
Chris Lattnerbf3b57f2006-11-08 01:03:21 +00001393 }
1394 }
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001395
Chris Lattner4fe01c42006-10-21 05:08:28 +00001396 // If this branch is the only thing in its block, see if we can forward
1397 // other blocks across it.
Craig Topperc0196b12014-04-14 00:51:57 +00001398 if (CurTBB && CurCond.empty() && !CurFBB &&
Dale Johannesene9b361b2010-03-10 19:57:56 +00001399 IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
Reid Klecknerb9204a52015-11-11 23:09:31 +00001400 !MBB->hasAddressTaken() && !MBB->isEHPad()) {
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001401 DebugLoc dl = getBranchDebugLoc(*MBB);
Chris Lattner4fe01c42006-10-21 05:08:28 +00001402 // This block may contain just an unconditional branch. Because there can
1403 // be 'non-branch terminators' in the block, try removing the branch and
1404 // then seeing if the block is empty.
1405 TII->RemoveBranch(*MBB);
Dale Johannesen5ebe0c12010-03-10 05:45:47 +00001406 // If the only things remaining in the block are debug info, remove these
1407 // as well, so this will behave the same as an empty block in non-debug
1408 // mode.
Benjamin Kramer6b568962015-06-23 14:47:29 +00001409 if (IsEmptyBlock(MBB)) {
1410 // Make the block empty, losing the debug info (we could probably
1411 // improve this in some cases.)
1412 MBB->erase(MBB->begin(), MBB->end());
Dale Johannesen5ebe0c12010-03-10 05:45:47 +00001413 }
Chris Lattner4fe01c42006-10-21 05:08:28 +00001414 // If this block is just an unconditional branch to CurTBB, we can
1415 // usually completely eliminate the block. The only case we cannot
1416 // completely eliminate the block is when the block before this one
1417 // falls through into MBB and we can't understand the prior block's branch
1418 // condition.
Chris Lattneraf838382006-10-28 17:32:47 +00001419 if (MBB->empty()) {
Dan Gohman047a7672009-12-05 00:44:40 +00001420 bool PredHasNoFallThrough = !PrevBB.canFallThrough();
Chris Lattneraf838382006-10-28 17:32:47 +00001421 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1422 !PrevBB.isSuccessor(MBB)) {
1423 // If the prior block falls through into us, turn it into an
1424 // explicit branch to us to make updates simpler.
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001425 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
Chris Lattneraf838382006-10-28 17:32:47 +00001426 PriorTBB != MBB && PriorFBB != MBB) {
Craig Topperc0196b12014-04-14 00:51:57 +00001427 if (!PriorTBB) {
1428 assert(PriorCond.empty() && !PriorFBB &&
Chris Lattnerc07657f2006-10-28 18:34:47 +00001429 "Bad branch analysis");
Chris Lattneraf838382006-10-28 17:32:47 +00001430 PriorTBB = MBB;
1431 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001432 assert(!PriorFBB && "Machine CFG out of date!");
Chris Lattneraf838382006-10-28 17:32:47 +00001433 PriorFBB = MBB;
1434 }
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001435 DebugLoc pdl = getBranchDebugLoc(PrevBB);
Chris Lattneraf838382006-10-28 17:32:47 +00001436 TII->RemoveBranch(PrevBB);
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001437 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
Chris Lattner4fe01c42006-10-21 05:08:28 +00001438 }
Chris Lattner4fe01c42006-10-21 05:08:28 +00001439
Chris Lattneraf838382006-10-28 17:32:47 +00001440 // Iterate through all the predecessors, revectoring each in-turn.
David Greene451d1a62007-06-29 02:45:24 +00001441 size_t PI = 0;
Chris Lattneraf838382006-10-28 17:32:47 +00001442 bool DidChange = false;
1443 bool HasBranchToSelf = false;
David Greene451d1a62007-06-29 02:45:24 +00001444 while(PI != MBB->pred_size()) {
1445 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1446 if (PMBB == MBB) {
Chris Lattneraf838382006-10-28 17:32:47 +00001447 // If this block has an uncond branch to itself, leave it.
1448 ++PI;
1449 HasBranchToSelf = true;
1450 } else {
1451 DidChange = true;
David Greene451d1a62007-06-29 02:45:24 +00001452 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
Dale Johannesenb5714632009-05-11 21:54:13 +00001453 // If this change resulted in PMBB ending in a conditional
1454 // branch where both conditions go to the same destination,
1455 // change this to an unconditional branch (and fix the CFG).
Craig Topperc0196b12014-04-14 00:51:57 +00001456 MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
Dale Johannesenb5714632009-05-11 21:54:13 +00001457 SmallVector<MachineOperand, 4> NewCurCond;
1458 bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1459 NewCurFBB, NewCurCond, true);
1460 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
Bill Wendling7c5dcb62012-03-07 08:49:42 +00001461 DebugLoc pdl = getBranchDebugLoc(*PMBB);
Dale Johannesenb5714632009-05-11 21:54:13 +00001462 TII->RemoveBranch(*PMBB);
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001463 NewCurCond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001464 TII->InsertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
Dale Johannesenb5714632009-05-11 21:54:13 +00001465 MadeChange = true;
1466 ++NumBranchOpts;
Craig Topperc0196b12014-04-14 00:51:57 +00001467 PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false);
Dale Johannesenb5714632009-05-11 21:54:13 +00001468 }
Chris Lattneraf838382006-10-28 17:32:47 +00001469 }
Chris Lattner9f5a1292006-10-21 06:11:43 +00001470 }
Chris Lattner4fe01c42006-10-21 05:08:28 +00001471
Chris Lattneraf838382006-10-28 17:32:47 +00001472 // Change any jumptables to go to the new MBB.
Chris Lattnerb6db2c62010-01-25 23:26:13 +00001473 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1474 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattneraf838382006-10-28 17:32:47 +00001475 if (DidChange) {
1476 ++NumBranchOpts;
1477 MadeChange = true;
Evan Cheng3d2fce02009-09-04 07:47:40 +00001478 if (!HasBranchToSelf) return MadeChange;
Chris Lattneraf838382006-10-28 17:32:47 +00001479 }
Chris Lattner9f5a1292006-10-21 06:11:43 +00001480 }
Chris Lattner3e8e57c2006-10-13 20:43:10 +00001481 }
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001482
Chris Lattner4fe01c42006-10-21 05:08:28 +00001483 // Add the branch back if the block is more than just an uncond branch.
Craig Topperc0196b12014-04-14 00:51:57 +00001484 TII->InsertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
Chris Lattner25e48dd2004-07-31 10:01:27 +00001485 }
Chris Lattner504eeda2006-10-29 21:05:41 +00001486 }
1487
Bill Wendlinge8a525a2009-12-15 00:39:24 +00001488 // If the prior block doesn't fall through into this block, and if this
1489 // block doesn't fall through into some other block, see if we can find a
1490 // place to move this block where a fall-through will happen.
1491 if (!PrevBB.canFallThrough()) {
1492
Bob Wilsonbd22f192009-11-17 17:06:18 +00001493 // Now we know that there was no fall-through into this block, check to
1494 // see if it has a fall-through into its successor.
Bob Wilson2d4ff122009-11-26 00:32:21 +00001495 bool CurFallsThru = MBB->canFallThrough();
Bob Wilsonbd22f192009-11-17 17:06:18 +00001496
Reid Kleckner0e288232015-08-27 23:27:47 +00001497 if (!MBB->isEHPad()) {
Jim Laskey2dc52452007-02-21 22:42:20 +00001498 // Check all the predecessors of this block. If one of them has no fall
1499 // throughs, move this block right after it.
Craig Topper5db36df2015-09-16 03:52:35 +00001500 for (MachineBasicBlock *PredBB : MBB->predecessors()) {
Jim Laskey2dc52452007-02-21 22:42:20 +00001501 // Analyze the branch at the end of the pred.
Craig Topperc0196b12014-04-14 00:51:57 +00001502 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001503 SmallVector<MachineOperand, 4> PredCond;
Bill Wendlinge8a525a2009-12-15 00:39:24 +00001504 if (PredBB != MBB && !PredBB->canFallThrough() &&
1505 !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
Dale Johannesen6e16d092007-05-10 01:01:49 +00001506 && (!CurFallsThru || !CurTBB || !CurFBB)
Jim Laskey2dc52452007-02-21 22:42:20 +00001507 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
Bill Wendlinge8a525a2009-12-15 00:39:24 +00001508 // If the current block doesn't fall through, just move it.
1509 // If the current block can fall through and does not end with a
1510 // conditional branch, we need to append an unconditional jump to
1511 // the (current) next block. To avoid a possible compile-time
1512 // infinite loop, move blocks only backward in this case.
1513 // Also, if there are already 2 branches here, we cannot add a third;
1514 // this means we have the case
1515 // Bcc next
1516 // B elsewhere
1517 // next:
Jim Laskey2dc52452007-02-21 22:42:20 +00001518 if (CurFallsThru) {
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001519 MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
Jim Laskey2dc52452007-02-21 22:42:20 +00001520 CurCond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001521 TII->InsertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
Jim Laskey2dc52452007-02-21 22:42:20 +00001522 }
1523 MBB->moveAfter(PredBB);
1524 MadeChange = true;
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001525 goto ReoptimizeBlock;
Chris Lattnerceb51d82006-10-24 01:12:32 +00001526 }
1527 }
Dale Johannesen12920dd2007-02-17 00:44:34 +00001528 }
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001529
Dale Johannesen12920dd2007-02-17 00:44:34 +00001530 if (!CurFallsThru) {
Chris Lattner504eeda2006-10-29 21:05:41 +00001531 // Check all successors to see if we can move this block before it.
Craig Topper5db36df2015-09-16 03:52:35 +00001532 for (MachineBasicBlock *SuccBB : MBB->successors()) {
Chris Lattner504eeda2006-10-29 21:05:41 +00001533 // Analyze the branch at the end of the block before the succ.
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001534 MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001535
Chris Lattner4dbbace2007-04-30 23:35:00 +00001536 // If this block doesn't already fall-through to that successor, and if
1537 // the succ doesn't already have a block that can fall through into it,
1538 // and if the successor isn't an EH destination, we can arrange for the
1539 // fallthrough to happen.
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001540 if (SuccBB != MBB && &*SuccPrev != MBB &&
Bob Wilson2d4ff122009-11-26 00:32:21 +00001541 !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
Reid Kleckner0e288232015-08-27 23:27:47 +00001542 !SuccBB->isEHPad()) {
Chris Lattner504eeda2006-10-29 21:05:41 +00001543 MBB->moveBefore(SuccBB);
1544 MadeChange = true;
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001545 goto ReoptimizeBlock;
Chris Lattner504eeda2006-10-29 21:05:41 +00001546 }
1547 }
Dan Gohmanc86b5a12009-11-11 18:38:14 +00001548
Chris Lattner504eeda2006-10-29 21:05:41 +00001549 // Okay, there is no really great place to put this block. If, however,
1550 // the block before this one would be a fall-through if this block were
1551 // removed, move this block to the end of the function.
Craig Topperc0196b12014-04-14 00:51:57 +00001552 MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001553 SmallVector<MachineOperand, 4> PrevCond;
Andrew Kaylor9efb2332015-12-03 18:55:28 +00001554 // We're looking for cases where PrevBB could possibly fall through to
1555 // FallThrough, but if FallThrough is an EH pad that wouldn't be useful
1556 // so here we skip over any EH pads so we might have a chance to find
1557 // a branch target from PrevBB.
1558 while (FallThrough != MF.end() && FallThrough->isEHPad())
1559 ++FallThrough;
1560 // Now check to see if the current block is sitting between PrevBB and
1561 // a block to which it could fall through.
Dan Gohmanf4141f12009-11-11 18:18:34 +00001562 if (FallThrough != MF.end() &&
Dan Gohman64b5d0f2009-11-11 19:48:59 +00001563 !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001564 PrevBB.isSuccessor(&*FallThrough)) {
1565 MBB->moveAfter(&MF.back());
Chris Lattner504eeda2006-10-29 21:05:41 +00001566 MadeChange = true;
Evan Cheng3d2fce02009-09-04 07:47:40 +00001567 return MadeChange;
Chris Lattner504eeda2006-10-29 21:05:41 +00001568 }
Chris Lattnerceb51d82006-10-24 01:12:32 +00001569 }
Chris Lattner25e48dd2004-07-31 10:01:27 +00001570 }
Evan Cheng3d2fce02009-09-04 07:47:40 +00001571
1572 return MadeChange;
Chris Lattner25e48dd2004-07-31 10:01:27 +00001573}
Evan Chengcfdf3392011-05-12 00:56:58 +00001574
1575//===----------------------------------------------------------------------===//
1576// Hoist Common Code
1577//===----------------------------------------------------------------------===//
1578
1579/// HoistCommonCode - Hoist common instruction sequences at the start of basic
1580/// blocks to their common predecessor.
Evan Chengcfdf3392011-05-12 00:56:58 +00001581bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1582 bool MadeChange = false;
1583 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
Duncan P. N. Exon Smith980f8f22015-10-09 18:23:49 +00001584 MachineBasicBlock *MBB = &*I++;
Evan Chengcfdf3392011-05-12 00:56:58 +00001585 MadeChange |= HoistCommonCodeInSuccs(MBB);
1586 }
1587
1588 return MadeChange;
1589}
1590
1591/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1592/// its 'true' successor.
1593static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1594 MachineBasicBlock *TrueBB) {
Craig Topper5db36df2015-09-16 03:52:35 +00001595 for (MachineBasicBlock *SuccBB : BB->successors())
Evan Chengcfdf3392011-05-12 00:56:58 +00001596 if (SuccBB != TrueBB)
1597 return SuccBB;
Craig Topperc0196b12014-04-14 00:51:57 +00001598 return nullptr;
Evan Chengcfdf3392011-05-12 00:56:58 +00001599}
1600
Jingyue Wu3a04dc62015-07-29 18:59:09 +00001601template <class Container>
1602static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI,
1603 Container &Set) {
1604 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1605 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1606 Set.insert(*AI);
1607 } else {
1608 Set.insert(Reg);
1609 }
1610}
1611
Evan Chengcfdf3392011-05-12 00:56:58 +00001612/// findHoistingInsertPosAndDeps - Find the location to move common instructions
Benjamin Kramerbde91762012-06-02 10:20:22 +00001613/// in successors to. The location is usually just before the terminator,
Evan Chengcfdf3392011-05-12 00:56:58 +00001614/// however if the terminator is a conditional branch and its previous
1615/// instruction is the flag setting instruction, the previous instruction is
1616/// the preferred location. This function also gathers uses and defs of the
1617/// instructions from the insertion point to the end of the block. The data is
1618/// used by HoistCommonCodeInSuccs to ensure safety.
1619static
1620MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1621 const TargetInstrInfo *TII,
1622 const TargetRegisterInfo *TRI,
1623 SmallSet<unsigned,4> &Uses,
1624 SmallSet<unsigned,4> &Defs) {
1625 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001626 if (!TII->isUnpredicatedTerminator(*Loc))
Evan Chengcfdf3392011-05-12 00:56:58 +00001627 return MBB->end();
1628
Craig Topper5db36df2015-09-16 03:52:35 +00001629 for (const MachineOperand &MO : Loc->operands()) {
Evan Chengcfdf3392011-05-12 00:56:58 +00001630 if (!MO.isReg())
1631 continue;
1632 unsigned Reg = MO.getReg();
1633 if (!Reg)
1634 continue;
1635 if (MO.isUse()) {
Jingyue Wu3a04dc62015-07-29 18:59:09 +00001636 addRegAndItsAliases(Reg, TRI, Uses);
Sasa Stankovic56c12e62014-06-05 13:42:48 +00001637 } else {
1638 if (!MO.isDead())
1639 // Don't try to hoist code in the rare case the terminator defines a
1640 // register that is later used.
1641 return MBB->end();
1642
1643 // If the terminator defines a register, make sure we don't hoist
1644 // the instruction whose def might be clobbered by the terminator.
Jingyue Wu3a04dc62015-07-29 18:59:09 +00001645 addRegAndItsAliases(Reg, TRI, Defs);
Sasa Stankovic56c12e62014-06-05 13:42:48 +00001646 }
Evan Chengcfdf3392011-05-12 00:56:58 +00001647 }
1648
1649 if (Uses.empty())
1650 return Loc;
1651 if (Loc == MBB->begin())
1652 return MBB->end();
1653
1654 // The terminator is probably a conditional branch, try not to separate the
1655 // branch from condition setting instruction.
1656 MachineBasicBlock::iterator PI = Loc;
1657 --PI;
Ekaterina Romanovab9aea932014-03-26 22:15:28 +00001658 while (PI != MBB->begin() && PI->isDebugValue())
Evan Chengcfdf3392011-05-12 00:56:58 +00001659 --PI;
1660
1661 bool IsDef = false;
Craig Topper5db36df2015-09-16 03:52:35 +00001662 for (const MachineOperand &MO : PI->operands()) {
Jakob Stoklund Olesene9e30d02012-02-15 23:42:54 +00001663 // If PI has a regmask operand, it is probably a call. Separate away.
1664 if (MO.isRegMask())
1665 return Loc;
Evan Chengcfdf3392011-05-12 00:56:58 +00001666 if (!MO.isReg() || MO.isUse())
1667 continue;
1668 unsigned Reg = MO.getReg();
1669 if (!Reg)
1670 continue;
Craig Topper5db36df2015-09-16 03:52:35 +00001671 if (Uses.count(Reg)) {
Evan Chengcfdf3392011-05-12 00:56:58 +00001672 IsDef = true;
Craig Topper5db36df2015-09-16 03:52:35 +00001673 break;
1674 }
Evan Chengcfdf3392011-05-12 00:56:58 +00001675 }
1676 if (!IsDef)
1677 // The condition setting instruction is not just before the conditional
1678 // branch.
1679 return Loc;
1680
1681 // Be conservative, don't insert instruction above something that may have
1682 // side-effects. And since it's potentially bad to separate flag setting
1683 // instruction from the conditional branch, just abort the optimization
1684 // completely.
1685 // Also avoid moving code above predicated instruction since it's hard to
1686 // reason about register liveness with predicated instruction.
1687 bool DontMoveAcrossStore = true;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001688 if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(*PI))
Evan Chengcfdf3392011-05-12 00:56:58 +00001689 return MBB->end();
1690
1691
1692 // Find out what registers are live. Note this routine is ignoring other live
1693 // registers which are only used by instructions in successor blocks.
Craig Topper5db36df2015-09-16 03:52:35 +00001694 for (const MachineOperand &MO : PI->operands()) {
Evan Chengcfdf3392011-05-12 00:56:58 +00001695 if (!MO.isReg())
1696 continue;
1697 unsigned Reg = MO.getReg();
1698 if (!Reg)
1699 continue;
1700 if (MO.isUse()) {
Jingyue Wu3a04dc62015-07-29 18:59:09 +00001701 addRegAndItsAliases(Reg, TRI, Uses);
Evan Chengcfdf3392011-05-12 00:56:58 +00001702 } else {
Benjamin Kramerf29db272012-08-22 15:37:57 +00001703 if (Uses.erase(Reg)) {
Jingyue Wu3a04dc62015-07-29 18:59:09 +00001704 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1705 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1706 Uses.erase(*SubRegs); // Use sub-registers to be conservative
1707 }
Evan Chengcfdf3392011-05-12 00:56:58 +00001708 }
Jingyue Wu3a04dc62015-07-29 18:59:09 +00001709 addRegAndItsAliases(Reg, TRI, Defs);
Evan Chengcfdf3392011-05-12 00:56:58 +00001710 }
1711 }
1712
1713 return PI;
1714}
1715
1716/// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
1717/// sequence at the start of the function, move the instructions before MBB
1718/// terminator if it's legal.
1719bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
Craig Topperc0196b12014-04-14 00:51:57 +00001720 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Chengcfdf3392011-05-12 00:56:58 +00001721 SmallVector<MachineOperand, 4> Cond;
1722 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1723 return false;
1724
1725 if (!FBB) FBB = findFalseBlock(MBB, TBB);
1726 if (!FBB)
1727 // Malformed bcc? True and false blocks are the same?
1728 return false;
1729
1730 // Restrict the optimization to cases where MBB is the only predecessor,
1731 // it is an obvious win.
1732 if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1733 return false;
1734
1735 // Find a suitable position to hoist the common instructions to. Also figure
1736 // out which registers are used or defined by instructions from the insertion
1737 // point to the end of the block.
1738 SmallSet<unsigned, 4> Uses, Defs;
1739 MachineBasicBlock::iterator Loc =
1740 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1741 if (Loc == MBB->end())
1742 return false;
1743
1744 bool HasDups = false;
Evan Cheng43054e62011-05-12 20:30:01 +00001745 SmallVector<unsigned, 4> LocalDefs;
1746 SmallSet<unsigned, 4> LocalDefsSet;
Evan Chengcfdf3392011-05-12 00:56:58 +00001747 MachineBasicBlock::iterator TIB = TBB->begin();
1748 MachineBasicBlock::iterator FIB = FBB->begin();
1749 MachineBasicBlock::iterator TIE = TBB->end();
1750 MachineBasicBlock::iterator FIE = FBB->end();
1751 while (TIB != TIE && FIB != FIE) {
1752 // Skip dbg_value instructions. These do not count.
1753 if (TIB->isDebugValue()) {
1754 while (TIB != TIE && TIB->isDebugValue())
1755 ++TIB;
1756 if (TIB == TIE)
1757 break;
1758 }
1759 if (FIB->isDebugValue()) {
1760 while (FIB != FIE && FIB->isDebugValue())
1761 ++FIB;
1762 if (FIB == FIE)
1763 break;
1764 }
1765 if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead))
1766 break;
1767
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001768 if (TII->isPredicated(*TIB))
Evan Chengcfdf3392011-05-12 00:56:58 +00001769 // Hard to reason about register liveness with predicated instruction.
1770 break;
1771
1772 bool IsSafe = true;
Craig Topper5db36df2015-09-16 03:52:35 +00001773 for (MachineOperand &MO : TIB->operands()) {
Jakob Stoklund Olesene9e30d02012-02-15 23:42:54 +00001774 // Don't attempt to hoist instructions with register masks.
1775 if (MO.isRegMask()) {
1776 IsSafe = false;
1777 break;
1778 }
Evan Chengcfdf3392011-05-12 00:56:58 +00001779 if (!MO.isReg())
1780 continue;
1781 unsigned Reg = MO.getReg();
1782 if (!Reg)
1783 continue;
1784 if (MO.isDef()) {
1785 if (Uses.count(Reg)) {
1786 // Avoid clobbering a register that's used by the instruction at
1787 // the point of insertion.
1788 IsSafe = false;
1789 break;
1790 }
1791
1792 if (Defs.count(Reg) && !MO.isDead()) {
1793 // Don't hoist the instruction if the def would be clobber by the
1794 // instruction at the point insertion. FIXME: This is overly
1795 // conservative. It should be possible to hoist the instructions
1796 // in BB2 in the following example:
1797 // BB1:
1798 // r1, eflag = op1 r2, r3
1799 // brcc eflag
1800 //
1801 // BB2:
1802 // r1 = op2, ...
1803 // = op3, r1<kill>
1804 IsSafe = false;
1805 break;
1806 }
Evan Cheng43054e62011-05-12 20:30:01 +00001807 } else if (!LocalDefsSet.count(Reg)) {
Evan Chengcfdf3392011-05-12 00:56:58 +00001808 if (Defs.count(Reg)) {
1809 // Use is defined by the instruction at the point of insertion.
1810 IsSafe = false;
1811 break;
1812 }
Evan Cheng5c03a6b2012-01-12 20:31:24 +00001813
1814 if (MO.isKill() && Uses.count(Reg))
1815 // Kills a register that's read by the instruction at the point of
1816 // insertion. Remove the kill marker.
1817 MO.setIsKill(false);
Evan Chengcfdf3392011-05-12 00:56:58 +00001818 }
1819 }
1820 if (!IsSafe)
1821 break;
1822
1823 bool DontMoveAcrossStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001824 if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore))
Evan Chengcfdf3392011-05-12 00:56:58 +00001825 break;
1826
Jakob Stoklund Olesend633abe2011-08-05 18:47:07 +00001827 // Remove kills from LocalDefsSet, these registers had short live ranges.
Craig Topper5db36df2015-09-16 03:52:35 +00001828 for (const MachineOperand &MO : TIB->operands()) {
Jakob Stoklund Olesend633abe2011-08-05 18:47:07 +00001829 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1830 continue;
1831 unsigned Reg = MO.getReg();
1832 if (!Reg || !LocalDefsSet.count(Reg))
1833 continue;
Jingyue Wu3a04dc62015-07-29 18:59:09 +00001834 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1835 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1836 LocalDefsSet.erase(*AI);
1837 } else {
1838 LocalDefsSet.erase(Reg);
1839 }
Jakob Stoklund Olesend633abe2011-08-05 18:47:07 +00001840 }
1841
Evan Cheng43054e62011-05-12 20:30:01 +00001842 // Track local defs so we can update liveins.
Craig Topper5db36df2015-09-16 03:52:35 +00001843 for (const MachineOperand &MO : TIB->operands()) {
Jakob Stoklund Olesend633abe2011-08-05 18:47:07 +00001844 if (!MO.isReg() || !MO.isDef() || MO.isDead())
Evan Cheng43054e62011-05-12 20:30:01 +00001845 continue;
1846 unsigned Reg = MO.getReg();
1847 if (!Reg)
1848 continue;
Jakob Stoklund Olesend633abe2011-08-05 18:47:07 +00001849 LocalDefs.push_back(Reg);
Jingyue Wu3a04dc62015-07-29 18:59:09 +00001850 addRegAndItsAliases(Reg, TRI, LocalDefsSet);
Evan Cheng43054e62011-05-12 20:30:01 +00001851 }
1852
Chad Rosier5dfe6da2012-02-22 17:25:00 +00001853 HasDups = true;
Evan Chengcfdf3392011-05-12 00:56:58 +00001854 ++TIB;
1855 ++FIB;
1856 }
1857
1858 if (!HasDups)
1859 return false;
1860
1861 MBB->splice(Loc, TBB, TBB->begin(), TIB);
1862 FBB->erase(FBB->begin(), FIB);
Evan Cheng43054e62011-05-12 20:30:01 +00001863
1864 // Update livein's.
1865 for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1866 unsigned Def = LocalDefs[i];
1867 if (LocalDefsSet.count(Def)) {
1868 TBB->addLiveIn(Def);
1869 FBB->addLiveIn(Def);
1870 }
1871 }
1872
Evan Chengcfdf3392011-05-12 00:56:58 +00001873 ++NumHoist;
1874 return true;
1875}