1//===- BranchFolding.cpp - Fold machine code branch instructions ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass forwards branches to unconditional branches to make them branch
10// directly to the target block. This pass often results in dead MBB's, which
11// it then removes.
12//
13// Note that this pass must be run after register allocation, it cannot handle
14// SSA form. It also must handle virtual registers for targets that emit virtual
15// ISA (e.g. NVPTX).
16//
17//===----------------------------------------------------------------------===//
18
19#include "BranchFolding.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Analysis/ProfileSummaryInfo.h"
26#include "llvm/CodeGen/Analysis.h"
27#include "llvm/CodeGen/BranchFoldingPass.h"
28#include "llvm/CodeGen/MBFIWrapper.h"
29#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
30#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineFunctionPass.h"
33#include "llvm/CodeGen/MachineInstr.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineLoopInfo.h"
37#include "llvm/CodeGen/MachineOperand.h"
38#include "llvm/CodeGen/MachineRegisterInfo.h"
39#include "llvm/CodeGen/MachineSizeOpts.h"
40#include "llvm/CodeGen/TargetInstrInfo.h"
41#include "llvm/CodeGen/TargetOpcodes.h"
42#include "llvm/CodeGen/TargetPassConfig.h"
43#include "llvm/CodeGen/TargetRegisterInfo.h"
44#include "llvm/CodeGen/TargetSubtargetInfo.h"
45#include "llvm/IR/DebugInfoMetadata.h"
46#include "llvm/IR/DebugLoc.h"
47#include "llvm/IR/Function.h"
48#include "llvm/InitializePasses.h"
49#include "llvm/MC/LaneBitmask.h"
50#include "llvm/MC/MCRegisterInfo.h"
51#include "llvm/Pass.h"
52#include "llvm/Support/BlockFrequency.h"
53#include "llvm/Support/BranchProbability.h"
54#include "llvm/Support/CommandLine.h"
55#include "llvm/Support/Debug.h"
56#include "llvm/Support/ErrorHandling.h"
57#include "llvm/Support/raw_ostream.h"
58#include "llvm/Target/TargetMachine.h"
59#include <cassert>
60#include <cstddef>
61#include <iterator>
62#include <numeric>
63
64using namespace llvm;
65
66#define DEBUG_TYPE "branch-folder"
67
68STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
69STATISTIC(NumBranchOpts, "Number of branches optimized");
70STATISTIC(NumTailMerge , "Number of block tails merged");
71STATISTIC(NumHoist , "Number of times common instructions are hoisted");
72STATISTIC(NumTailCalls, "Number of tail calls optimized");
73
74static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
75 cl::init(Val: cl::BOU_UNSET), cl::Hidden);
76
77// Throttle for huge numbers of predecessors (compile speed problems)
78static cl::opt<unsigned>
79TailMergeThreshold("tail-merge-threshold",
80 cl::desc("Max number of predecessors to consider tail merging"),
81 cl::init(Val: 150), cl::Hidden);
82
83// Heuristic for tail merging (and, inversely, tail duplication).
84static cl::opt<unsigned>
85TailMergeSize("tail-merge-size",
86 cl::desc("Min number of instructions to consider tail merging"),
87 cl::init(Val: 3), cl::Hidden);
88
89namespace {
90
91 /// BranchFolderPass - Wrap branch folder in a machine function pass.
92class BranchFolderLegacy : public MachineFunctionPass {
93public:
94 static char ID;
95
96 explicit BranchFolderLegacy() : MachineFunctionPass(ID) {}
97
98 bool runOnMachineFunction(MachineFunction &MF) override;
99
100 void getAnalysisUsage(AnalysisUsage &AU) const override {
101 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
102 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
103 AU.addRequired<ProfileSummaryInfoWrapperPass>();
104 AU.addRequired<TargetPassConfig>();
105 MachineFunctionPass::getAnalysisUsage(AU);
106 }
107
108 MachineFunctionProperties getRequiredProperties() const override {
109 return MachineFunctionProperties().setNoPHIs();
110 }
111};
112
113} // end anonymous namespace
114
115char BranchFolderLegacy::ID = 0;
116
117char &llvm::BranchFolderPassID = BranchFolderLegacy::ID;
118
119INITIALIZE_PASS(BranchFolderLegacy, DEBUG_TYPE, "Control Flow Optimizer", false,
120 false)
121
122PreservedAnalyses BranchFolderPass::run(MachineFunction &MF,
123 MachineFunctionAnalysisManager &MFAM) {
124 MFPropsModifier _(*this, MF);
125 bool EnableTailMerge =
126 !MF.getTarget().requiresStructuredCFG() && this->EnableTailMerge;
127
128 auto &MBPI = MFAM.getResult<MachineBranchProbabilityAnalysis>(IR&: MF);
129 auto *PSI = MFAM.getResult<ModuleAnalysisManagerMachineFunctionProxy>(IR&: MF)
130 .getCachedResult<ProfileSummaryAnalysis>(
131 IR&: *MF.getFunction().getParent());
132 if (!PSI)
133 report_fatal_error(
134 reason: "ProfileSummaryAnalysis is required for BranchFoldingPass", gen_crash_diag: false);
135
136 auto &MBFI = MFAM.getResult<MachineBlockFrequencyAnalysis>(IR&: MF);
137 MBFIWrapper MBBFreqInfo(MBFI);
138 BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo, MBPI,
139 PSI);
140 if (!Folder.OptimizeFunction(MF, tii: MF.getSubtarget().getInstrInfo(),
141 tri: MF.getSubtarget().getRegisterInfo()))
142 return PreservedAnalyses::all();
143 return getMachineFunctionPassPreservedAnalyses();
144}
145
146bool BranchFolderLegacy::runOnMachineFunction(MachineFunction &MF) {
147 if (skipFunction(F: MF.getFunction()))
148 return false;
149
150 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
151 // TailMerge can create jump into if branches that make CFG irreducible for
152 // HW that requires structurized CFG.
153 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
154 PassConfig->getEnableTailMerge();
155 MBFIWrapper MBBFreqInfo(
156 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI());
157 BranchFolder Folder(
158 EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo,
159 getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI(),
160 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
161 return Folder.OptimizeFunction(MF, tii: MF.getSubtarget().getInstrInfo(),
162 tri: MF.getSubtarget().getRegisterInfo());
163}
164
165BranchFolder::BranchFolder(bool DefaultEnableTailMerge, bool CommonHoist,
166 MBFIWrapper &FreqInfo,
167 const MachineBranchProbabilityInfo &ProbInfo,
168 ProfileSummaryInfo *PSI, unsigned MinTailLength)
169 : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),
170 MBBFreqInfo(FreqInfo), MBPI(ProbInfo), PSI(PSI) {
171 switch (FlagEnableTailMerge) {
172 case cl::BOU_UNSET:
173 EnableTailMerge = DefaultEnableTailMerge;
174 break;
175 case cl::BOU_TRUE: EnableTailMerge = true; break;
176 case cl::BOU_FALSE: EnableTailMerge = false; break;
177 }
178}
179
180void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
181 assert(MBB->pred_empty() && "MBB must be dead!");
182 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
183
184 MachineFunction *MF = MBB->getParent();
185 // drop all successors.
186 while (!MBB->succ_empty())
187 MBB->removeSuccessor(I: MBB->succ_end()-1);
188
189 // Avoid matching if this pointer gets reused.
190 TriedMerging.erase(Ptr: MBB);
191
192 // Update call info.
193 for (const MachineInstr &MI : *MBB)
194 if (MI.shouldUpdateAdditionalCallInfo())
195 MF->eraseAdditionalCallInfo(MI: &MI);
196
197 // Remove the block.
198 MF->erase(MBBI: MBB);
199 EHScopeMembership.erase(Val: MBB);
200 if (MLI)
201 MLI->removeBlock(BB: MBB);
202}
203
204bool BranchFolder::OptimizeFunction(MachineFunction &MF,
205 const TargetInstrInfo *tii,
206 const TargetRegisterInfo *tri,
207 MachineLoopInfo *mli, bool AfterPlacement) {
208 if (!tii) return false;
209
210 TriedMerging.clear();
211
212 MachineRegisterInfo &MRI = MF.getRegInfo();
213 AfterBlockPlacement = AfterPlacement;
214 TII = tii;
215 TRI = tri;
216 MLI = mli;
217 this->MRI = &MRI;
218
219 if (MinCommonTailLength == 0) {
220 MinCommonTailLength = TailMergeSize.getNumOccurrences() > 0
221 ? TailMergeSize
222 : TII->getTailMergeSize(MF);
223 }
224
225 UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF);
226 if (!UpdateLiveIns)
227 MRI.invalidateLiveness();
228
229 bool MadeChange = false;
230
231 // Recalculate EH scope membership.
232 EHScopeMembership = getEHScopeMembership(MF);
233
234 bool MadeChangeThisIteration = true;
235 while (MadeChangeThisIteration) {
236 MadeChangeThisIteration = TailMergeBlocks(MF);
237 // No need to clean up if tail merging does not change anything after the
238 // block placement.
239 if (!AfterBlockPlacement || MadeChangeThisIteration)
240 MadeChangeThisIteration |= OptimizeBranches(MF);
241 if (EnableHoistCommonCode)
242 MadeChangeThisIteration |= HoistCommonCode(MF);
243 MadeChange |= MadeChangeThisIteration;
244 }
245
246 // See if any jump tables have become dead as the code generator
247 // did its thing.
248 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
249 if (!JTI)
250 return MadeChange;
251
252 // Walk the function to find jump tables that are live.
253 BitVector JTIsLive(JTI->getJumpTables().size());
254 for (const MachineBasicBlock &BB : MF) {
255 for (const MachineInstr &I : BB)
256 for (const MachineOperand &Op : I.operands()) {
257 if (!Op.isJTI()) continue;
258
259 // Remember that this JT is live.
260 JTIsLive.set(Op.getIndex());
261 }
262 }
263
264 // Finally, remove dead jump tables. This happens when the
265 // indirect jump was unreachable (and thus deleted).
266 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
267 if (!JTIsLive.test(Idx: i)) {
268 JTI->RemoveJumpTable(Idx: i);
269 MadeChange = true;
270 }
271
272 return MadeChange;
273}
274
275//===----------------------------------------------------------------------===//
276// Tail Merging of Blocks
277//===----------------------------------------------------------------------===//
278
279/// HashMachineInstr - Compute a hash value for MI and its operands.
280static unsigned HashMachineInstr(const MachineInstr &MI) {
281 unsigned Hash = MI.getOpcode();
282 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
283 const MachineOperand &Op = MI.getOperand(i);
284
285 // Merge in bits from the operand if easy. We can't use MachineOperand's
286 // hash_code here because it's not deterministic and we sort by hash value
287 // later.
288 unsigned OperandHash = 0;
289 switch (Op.getType()) {
290 case MachineOperand::MO_Register:
291 OperandHash = Op.getReg().id();
292 break;
293 case MachineOperand::MO_Immediate:
294 OperandHash = Op.getImm();
295 break;
296 case MachineOperand::MO_MachineBasicBlock:
297 OperandHash = Op.getMBB()->getNumber();
298 break;
299 case MachineOperand::MO_FrameIndex:
300 case MachineOperand::MO_ConstantPoolIndex:
301 case MachineOperand::MO_JumpTableIndex:
302 OperandHash = Op.getIndex();
303 break;
304 case MachineOperand::MO_GlobalAddress:
305 case MachineOperand::MO_ExternalSymbol:
306 // Global address / external symbol are too hard, don't bother, but do
307 // pull in the offset.
308 OperandHash = Op.getOffset();
309 break;
310 default:
311 break;
312 }
313
314 Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
315 }
316 return Hash;
317}
318
319/// HashEndOfMBB - Hash the last instruction in the MBB.
320static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {
321 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr(SkipPseudoOp: false);
322 if (I == MBB.end())
323 return 0;
324
325 return HashMachineInstr(MI: *I);
326}
327
328/// Whether MI should be counted as an instruction when calculating common tail.
329static bool countsAsInstruction(const MachineInstr &MI) {
330 return !(MI.isDebugInstr() || MI.isCFIInstruction());
331}
332
333/// Iterate backwards from the given iterator \p I, towards the beginning of the
334/// block. If a MI satisfying 'countsAsInstruction' is found, return an iterator
335/// pointing to that MI. If no such MI is found, return the end iterator.
336static MachineBasicBlock::iterator
337skipBackwardPastNonInstructions(MachineBasicBlock::iterator I,
338 MachineBasicBlock *MBB) {
339 while (I != MBB->begin()) {
340 --I;
341 if (countsAsInstruction(MI: *I))
342 return I;
343 }
344 return MBB->end();
345}
346
347/// Given two machine basic blocks, return the number of instructions they
348/// actually have in common together at their end. If a common tail is found (at
349/// least by one instruction), then iterators for the first shared instruction
350/// in each block are returned as well.
351///
352/// Non-instructions according to countsAsInstruction are ignored.
353static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
354 MachineBasicBlock *MBB2,
355 MachineBasicBlock::iterator &I1,
356 MachineBasicBlock::iterator &I2) {
357 MachineBasicBlock::iterator MBBI1 = MBB1->end();
358 MachineBasicBlock::iterator MBBI2 = MBB2->end();
359
360 unsigned TailLen = 0;
361 while (true) {
362 MBBI1 = skipBackwardPastNonInstructions(I: MBBI1, MBB: MBB1);
363 MBBI2 = skipBackwardPastNonInstructions(I: MBBI2, MBB: MBB2);
364 if (MBBI1 == MBB1->end() || MBBI2 == MBB2->end())
365 break;
366 if (!MBBI1->isIdenticalTo(Other: *MBBI2) ||
367 // FIXME: This check is dubious. It's used to get around a problem where
368 // people incorrectly expect inline asm directives to remain in the same
369 // relative order. This is untenable because normal compiler
370 // optimizations (like this one) may reorder and/or merge these
371 // directives.
372 MBBI1->isInlineAsm()) {
373 break;
374 }
375 if (MBBI1->getFlag(Flag: MachineInstr::NoMerge) ||
376 MBBI2->getFlag(Flag: MachineInstr::NoMerge))
377 break;
378 ++TailLen;
379 I1 = MBBI1;
380 I2 = MBBI2;
381 }
382
383 return TailLen;
384}
385
386void BranchFolder::replaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
387 MachineBasicBlock &NewDest) {
388 if (UpdateLiveIns) {
389 // OldInst should always point to an instruction.
390 MachineBasicBlock &OldMBB = *OldInst->getParent();
391 LiveRegs.clear();
392 LiveRegs.addLiveOuts(MBB: OldMBB);
393 // Move backward to the place where will insert the jump.
394 MachineBasicBlock::iterator I = OldMBB.end();
395 do {
396 --I;
397 LiveRegs.stepBackward(MI: *I);
398 } while (I != OldInst);
399
400 // Merging the tails may have switched some undef operand to non-undef ones.
401 // Add IMPLICIT_DEFS into OldMBB as necessary to have a definition of the
402 // register.
403 for (MachineBasicBlock::RegisterMaskPair P : NewDest.liveins()) {
404 // We computed the liveins with computeLiveIn earlier and should only see
405 // full registers:
406 assert(P.LaneMask == LaneBitmask::getAll() &&
407 "Can only handle full register.");
408 MCRegister Reg = P.PhysReg;
409 if (!LiveRegs.available(MRI: *MRI, Reg))
410 continue;
411 DebugLoc DL;
412 BuildMI(BB&: OldMBB, I: OldInst, MIMD: DL, MCID: TII->get(Opcode: TargetOpcode::IMPLICIT_DEF), DestReg: Reg);
413 }
414 }
415
416 TII->ReplaceTailWithBranchTo(Tail: OldInst, NewDest: &NewDest);
417 ++NumTailMerge;
418}
419
420MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
421 MachineBasicBlock::iterator BBI1,
422 const BasicBlock *BB) {
423 if (!TII->isLegalToSplitMBBAt(MBB&: CurMBB, MBBI: BBI1))
424 return nullptr;
425
426 MachineFunction &MF = *CurMBB.getParent();
427
428 // Create the fall-through block.
429 MachineFunction::iterator MBBI = CurMBB.getIterator();
430 MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(BB);
431 CurMBB.getParent()->insert(MBBI: ++MBBI, MBB: NewMBB);
432
433 // Move all the successors of this block to the specified block.
434 NewMBB->transferSuccessors(FromMBB: &CurMBB);
435
436 // Add an edge from CurMBB to NewMBB for the fall-through.
437 CurMBB.addSuccessor(Succ: NewMBB);
438
439 // Splice the code over.
440 NewMBB->splice(Where: NewMBB->end(), Other: &CurMBB, From: BBI1, To: CurMBB.end());
441
442 // NewMBB belongs to the same loop as CurMBB.
443 if (MLI)
444 if (MachineLoop *ML = MLI->getLoopFor(BB: &CurMBB))
445 ML->addBasicBlockToLoop(NewBB: NewMBB, LI&: *MLI);
446
447 // NewMBB inherits CurMBB's block frequency.
448 MBBFreqInfo.setBlockFreq(MBB: NewMBB, F: MBBFreqInfo.getBlockFreq(MBB: &CurMBB));
449
450 if (UpdateLiveIns)
451 computeAndAddLiveIns(LiveRegs, MBB&: *NewMBB);
452
453 // Add the new block to the EH scope.
454 const auto &EHScopeI = EHScopeMembership.find(Val: &CurMBB);
455 if (EHScopeI != EHScopeMembership.end()) {
456 auto n = EHScopeI->second;
457 EHScopeMembership[NewMBB] = n;
458 }
459
460 return NewMBB;
461}
462
463/// EstimateRuntime - Make a rough estimate for how long it will take to run
464/// the specified code.
465static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
466 MachineBasicBlock::iterator E) {
467 unsigned Time = 0;
468 for (; I != E; ++I) {
469 if (!countsAsInstruction(MI: *I))
470 continue;
471 if (I->isCall())
472 Time += 10;
473 else if (I->mayLoadOrStore())
474 Time += 2;
475 else
476 ++Time;
477 }
478 return Time;
479}
480
481// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
482// branches temporarily for tail merging). In the case where CurMBB ends
483// with a conditional branch to the next block, optimize by reversing the
484// test and conditionally branching to SuccMBB instead.
485static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
486 const TargetInstrInfo *TII, const DebugLoc &BranchDL) {
487 MachineFunction *MF = CurMBB->getParent();
488 MachineFunction::iterator I = std::next(x: MachineFunction::iterator(CurMBB));
489 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
490 SmallVector<MachineOperand, 4> Cond;
491 DebugLoc dl = CurMBB->findBranchDebugLoc();
492 if (!dl)
493 dl = BranchDL;
494 if (I != MF->end() && !TII->analyzeBranch(MBB&: *CurMBB, TBB, FBB, Cond, AllowModify: true)) {
495 MachineBasicBlock *NextBB = &*I;
496 if (TBB == NextBB && !Cond.empty() && !FBB) {
497 if (!TII->reverseBranchCondition(Cond)) {
498 TII->removeBranch(MBB&: *CurMBB);
499 TII->insertBranch(MBB&: *CurMBB, TBB: SuccBB, FBB: nullptr, Cond, DL: dl);
500 return;
501 }
502 }
503 }
504 TII->insertBranch(MBB&: *CurMBB, TBB: SuccBB, FBB: nullptr,
505 Cond: SmallVector<MachineOperand, 0>(), DL: dl);
506}
507
508bool
509BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
510 if (getHash() < o.getHash())
511 return true;
512 if (getHash() > o.getHash())
513 return false;
514 if (getBlock()->getNumber() < o.getBlock()->getNumber())
515 return true;
516 if (getBlock()->getNumber() > o.getBlock()->getNumber())
517 return false;
518 return false;
519}
520
521/// CountTerminators - Count the number of terminators in the given
522/// block and set I to the position of the first non-terminator, if there
523/// is one, or MBB->end() otherwise.
524static unsigned CountTerminators(MachineBasicBlock *MBB,
525 MachineBasicBlock::iterator &I) {
526 I = MBB->end();
527 unsigned NumTerms = 0;
528 while (true) {
529 if (I == MBB->begin()) {
530 I = MBB->end();
531 break;
532 }
533 --I;
534 if (!I->isTerminator()) break;
535 ++NumTerms;
536 }
537 return NumTerms;
538}
539
540/// A no successor, non-return block probably ends in unreachable and is cold.
541/// Also consider a block that ends in an indirect branch to be a return block,
542/// since many targets use plain indirect branches to return.
543static bool blockEndsInUnreachable(const MachineBasicBlock *MBB) {
544 if (!MBB->succ_empty())
545 return false;
546 if (MBB->empty())
547 return true;
548 return !(MBB->back().isReturn() || MBB->back().isIndirectBranch());
549}
550
551/// ProfitableToMerge - Check if two machine basic blocks have a common tail
552/// and decide if it would be profitable to merge those tails. Return the
553/// length of the common tail and iterators to the first common instruction
554/// in each block.
555/// MBB1, MBB2 The blocks to check
556/// MinCommonTailLength Minimum size of tail block to be merged.
557/// CommonTailLen Out parameter to record the size of the shared tail between
558/// MBB1 and MBB2
559/// I1, I2 Iterator references that will be changed to point to the first
560/// instruction in the common tail shared by MBB1,MBB2
561/// SuccBB A common successor of MBB1, MBB2 which are in a canonical form
562/// relative to SuccBB
563/// PredBB The layout predecessor of SuccBB, if any.
564/// EHScopeMembership map from block to EH scope #.
565/// AfterPlacement True if we are merging blocks after layout. Stricter
566/// thresholds apply to prevent undoing tail-duplication.
567static bool
568ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
569 unsigned MinCommonTailLength, unsigned &CommonTailLen,
570 MachineBasicBlock::iterator &I1,
571 MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,
572 MachineBasicBlock *PredBB,
573 DenseMap<const MachineBasicBlock *, int> &EHScopeMembership,
574 bool AfterPlacement,
575 MBFIWrapper &MBBFreqInfo,
576 ProfileSummaryInfo *PSI) {
577 // It is never profitable to tail-merge blocks from two different EH scopes.
578 if (!EHScopeMembership.empty()) {
579 auto EHScope1 = EHScopeMembership.find(Val: MBB1);
580 assert(EHScope1 != EHScopeMembership.end());
581 auto EHScope2 = EHScopeMembership.find(Val: MBB2);
582 assert(EHScope2 != EHScopeMembership.end());
583 if (EHScope1->second != EHScope2->second)
584 return false;
585 }
586
587 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
588 if (CommonTailLen == 0)
589 return false;
590 LLVM_DEBUG(dbgs() << "Common tail length of " << printMBBReference(*MBB1)
591 << " and " << printMBBReference(*MBB2) << " is "
592 << CommonTailLen << '\n');
593
594 // Move the iterators to the beginning of the MBB if we only got debug
595 // instructions before the tail. This is to avoid splitting a block when we
596 // only got debug instructions before the tail (to be invariant on -g).
597 if (skipDebugInstructionsForward(It: MBB1->begin(), End: MBB1->end(), SkipPseudoOp: false) == I1)
598 I1 = MBB1->begin();
599 if (skipDebugInstructionsForward(It: MBB2->begin(), End: MBB2->end(), SkipPseudoOp: false) == I2)
600 I2 = MBB2->begin();
601
602 bool FullBlockTail1 = I1 == MBB1->begin();
603 bool FullBlockTail2 = I2 == MBB2->begin();
604
605 // It's almost always profitable to merge any number of non-terminator
606 // instructions with the block that falls through into the common successor.
607 // This is true only for a single successor. For multiple successors, we are
608 // trading a conditional branch for an unconditional one.
609 // TODO: Re-visit successor size for non-layout tail merging.
610 if ((MBB1 == PredBB || MBB2 == PredBB) &&
611 (!AfterPlacement || MBB1->succ_size() == 1)) {
612 MachineBasicBlock::iterator I;
613 unsigned NumTerms = CountTerminators(MBB: MBB1 == PredBB ? MBB2 : MBB1, I);
614 if (CommonTailLen > NumTerms)
615 return true;
616 }
617
618 // If these are identical non-return blocks with no successors, merge them.
619 // Such blocks are typically cold calls to noreturn functions like abort, and
620 // are unlikely to become a fallthrough target after machine block placement.
621 // Tail merging these blocks is unlikely to create additional unconditional
622 // branches, and will reduce the size of this cold code.
623 if (FullBlockTail1 && FullBlockTail2 &&
624 blockEndsInUnreachable(MBB: MBB1) && blockEndsInUnreachable(MBB: MBB2))
625 return true;
626
627 // If one of the blocks can be completely merged and happens to be in
628 // a position where the other could fall through into it, merge any number
629 // of instructions, because it can be done without a branch.
630 // TODO: If the blocks are not adjacent, move one of them so that they are?
631 if (MBB1->isLayoutSuccessor(MBB: MBB2) && FullBlockTail2)
632 return true;
633 if (MBB2->isLayoutSuccessor(MBB: MBB1) && FullBlockTail1)
634 return true;
635
636 // If both blocks are identical and end in a branch, merge them unless they
637 // both have a fallthrough predecessor and successor.
638 // We can only do this after block placement because it depends on whether
639 // there are fallthroughs, and we don't know until after layout.
640 if (AfterPlacement && FullBlockTail1 && FullBlockTail2) {
641 auto BothFallThrough = [](MachineBasicBlock *MBB) {
642 if (!MBB->succ_empty() && !MBB->canFallThrough())
643 return false;
644 MachineFunction::iterator I(MBB);
645 MachineFunction *MF = MBB->getParent();
646 return (MBB != &*MF->begin()) && std::prev(x: I)->canFallThrough();
647 };
648 if (!BothFallThrough(MBB1) || !BothFallThrough(MBB2))
649 return true;
650 }
651
652 // If both blocks have an unconditional branch temporarily stripped out,
653 // count that as an additional common instruction for the following
654 // heuristics. This heuristic is only accurate for single-succ blocks, so to
655 // make sure that during layout merging and duplicating don't crash, we check
656 // for that when merging during layout.
657 unsigned EffectiveTailLen = CommonTailLen;
658 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
659 (MBB1->succ_size() == 1 || !AfterPlacement) &&
660 !MBB1->back().isBarrier() &&
661 !MBB2->back().isBarrier())
662 ++EffectiveTailLen;
663
664 // Check if the common tail is long enough to be worthwhile.
665 if (EffectiveTailLen >= MinCommonTailLength)
666 return true;
667
668 // If we are optimizing for code size, 2 instructions in common is enough if
669 // we don't have to split a block. At worst we will be introducing 1 new
670 // branch instruction, which is likely to be smaller than the 2
671 // instructions that would be deleted in the merge.
672 bool OptForSize = llvm::shouldOptimizeForSize(MBB: MBB1, PSI, MBFIWrapper: &MBBFreqInfo) &&
673 llvm::shouldOptimizeForSize(MBB: MBB2, PSI, MBFIWrapper: &MBBFreqInfo);
674 return EffectiveTailLen >= 2 && OptForSize &&
675 (FullBlockTail1 || FullBlockTail2);
676}
677
678unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
679 unsigned MinCommonTailLength,
680 MachineBasicBlock *SuccBB,
681 MachineBasicBlock *PredBB) {
682 unsigned maxCommonTailLength = 0U;
683 SameTails.clear();
684 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
685 MPIterator HighestMPIter = std::prev(x: MergePotentials.end());
686 for (MPIterator CurMPIter = std::prev(x: MergePotentials.end()),
687 B = MergePotentials.begin();
688 CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
689 for (MPIterator I = std::prev(x: CurMPIter); I->getHash() == CurHash; --I) {
690 unsigned CommonTailLen;
691 if (ProfitableToMerge(MBB1: CurMPIter->getBlock(), MBB2: I->getBlock(),
692 MinCommonTailLength,
693 CommonTailLen, I1&: TrialBBI1, I2&: TrialBBI2,
694 SuccBB, PredBB,
695 EHScopeMembership,
696 AfterPlacement: AfterBlockPlacement, MBBFreqInfo, PSI)) {
697 if (CommonTailLen > maxCommonTailLength) {
698 SameTails.clear();
699 maxCommonTailLength = CommonTailLen;
700 HighestMPIter = CurMPIter;
701 SameTails.push_back(x: SameTailElt(CurMPIter, TrialBBI1));
702 }
703 if (HighestMPIter == CurMPIter &&
704 CommonTailLen == maxCommonTailLength)
705 SameTails.push_back(x: SameTailElt(I, TrialBBI2));
706 }
707 if (I == B)
708 break;
709 }
710 }
711 return maxCommonTailLength;
712}
713
714void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
715 MachineBasicBlock *SuccBB,
716 MachineBasicBlock *PredBB,
717 const DebugLoc &BranchDL) {
718 MPIterator CurMPIter, B;
719 for (CurMPIter = std::prev(x: MergePotentials.end()),
720 B = MergePotentials.begin();
721 CurMPIter->getHash() == CurHash; --CurMPIter) {
722 // Put the unconditional branch back, if we need one.
723 MachineBasicBlock *CurMBB = CurMPIter->getBlock();
724 if (SuccBB && CurMBB != PredBB)
725 FixTail(CurMBB, SuccBB, TII, BranchDL);
726 if (CurMPIter == B)
727 break;
728 }
729 if (CurMPIter->getHash() != CurHash)
730 CurMPIter++;
731 MergePotentials.erase(first: CurMPIter, last: MergePotentials.end());
732}
733
734bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
735 MachineBasicBlock *SuccBB,
736 unsigned maxCommonTailLength,
737 unsigned &commonTailIndex) {
738 commonTailIndex = 0;
739 unsigned TimeEstimate = ~0U;
740 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
741 // Use PredBB if possible; that doesn't require a new branch.
742 if (SameTails[i].getBlock() == PredBB) {
743 commonTailIndex = i;
744 break;
745 }
746 // Otherwise, make a (fairly bogus) choice based on estimate of
747 // how long it will take the various blocks to execute.
748 unsigned t = EstimateRuntime(I: SameTails[i].getBlock()->begin(),
749 E: SameTails[i].getTailStartPos());
750 if (t <= TimeEstimate) {
751 TimeEstimate = t;
752 commonTailIndex = i;
753 }
754 }
755
756 MachineBasicBlock::iterator BBI =
757 SameTails[commonTailIndex].getTailStartPos();
758 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
759
760 LLVM_DEBUG(dbgs() << "\nSplitting " << printMBBReference(*MBB) << ", size "
761 << maxCommonTailLength);
762
763 // If the split block unconditionally falls-thru to SuccBB, it will be
764 // merged. In control flow terms it should then take SuccBB's name. e.g. If
765 // SuccBB is an inner loop, the common tail is still part of the inner loop.
766 const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
767 SuccBB->getBasicBlock() : MBB->getBasicBlock();
768 MachineBasicBlock *newMBB = SplitMBBAt(CurMBB&: *MBB, BBI1: BBI, BB);
769 if (!newMBB) {
770 LLVM_DEBUG(dbgs() << "... failed!");
771 return false;
772 }
773
774 SameTails[commonTailIndex].setBlock(newMBB);
775 SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
776
777 // If we split PredBB, newMBB is the new predecessor.
778 if (PredBB == MBB)
779 PredBB = newMBB;
780
781 return true;
782}
783
784static void
785mergeOperations(MachineBasicBlock::iterator MBBIStartPos,
786 MachineBasicBlock &MBBCommon) {
787 MachineBasicBlock *MBB = MBBIStartPos->getParent();
788 // Note CommonTailLen does not necessarily matches the size of
789 // the common BB nor all its instructions because of debug
790 // instructions differences.
791 unsigned CommonTailLen = 0;
792 for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
793 ++CommonTailLen;
794
795 MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
796 MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
797 MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
798 MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
799
800 while (CommonTailLen--) {
801 assert(MBBI != MBBIE && "Reached BB end within common tail length!");
802 (void)MBBIE;
803
804 if (!countsAsInstruction(MI: *MBBI)) {
805 ++MBBI;
806 continue;
807 }
808
809 while ((MBBICommon != MBBIECommon) && !countsAsInstruction(MI: *MBBICommon))
810 ++MBBICommon;
811
812 assert(MBBICommon != MBBIECommon &&
813 "Reached BB end within common tail length!");
814 assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!");
815
816 // Merge MMOs from memory operations in the common block.
817 if (MBBICommon->mayLoadOrStore())
818 MBBICommon->cloneMergedMemRefs(MF&: *MBB->getParent(), MIs: {&*MBBICommon, &*MBBI});
819 // Drop undef flags if they aren't present in all merged instructions.
820 for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; ++I) {
821 MachineOperand &MO = MBBICommon->getOperand(i: I);
822 if (MO.isReg() && MO.isUndef()) {
823 const MachineOperand &OtherMO = MBBI->getOperand(i: I);
824 if (!OtherMO.isUndef())
825 MO.setIsUndef(false);
826 }
827 }
828
829 ++MBBI;
830 ++MBBICommon;
831 }
832}
833
834void BranchFolder::mergeCommonTails(unsigned commonTailIndex) {
835 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
836
837 std::vector<MachineBasicBlock::iterator> NextCommonInsts(SameTails.size());
838 for (unsigned int i = 0 ; i != SameTails.size() ; ++i) {
839 if (i != commonTailIndex) {
840 NextCommonInsts[i] = SameTails[i].getTailStartPos();
841 mergeOperations(MBBIStartPos: SameTails[i].getTailStartPos(), MBBCommon&: *MBB);
842 } else {
843 assert(SameTails[i].getTailStartPos() == MBB->begin() &&
844 "MBB is not a common tail only block");
845 }
846 }
847
848 for (auto &MI : *MBB) {
849 if (!countsAsInstruction(MI))
850 continue;
851 DebugLoc DL = MI.getDebugLoc();
852 for (unsigned int i = 0 ; i < NextCommonInsts.size() ; i++) {
853 if (i == commonTailIndex)
854 continue;
855
856 auto &Pos = NextCommonInsts[i];
857 assert(Pos != SameTails[i].getBlock()->end() &&
858 "Reached BB end within common tail");
859 while (!countsAsInstruction(MI: *Pos)) {
860 ++Pos;
861 assert(Pos != SameTails[i].getBlock()->end() &&
862 "Reached BB end within common tail");
863 }
864 assert(MI.isIdenticalTo(*Pos) && "Expected matching MIIs!");
865 DL = DILocation::getMergedLocation(LocA: DL, LocB: Pos->getDebugLoc());
866 NextCommonInsts[i] = ++Pos;
867 }
868 MI.setDebugLoc(DL);
869 }
870
871 if (UpdateLiveIns) {
872 LivePhysRegs NewLiveIns(*TRI);
873 computeLiveIns(LiveRegs&: NewLiveIns, MBB: *MBB);
874 LiveRegs.init(TRI: *TRI);
875
876 // The flag merging may lead to some register uses no longer using the
877 // <undef> flag, add IMPLICIT_DEFs in the predecessors as necessary.
878 for (MachineBasicBlock *Pred : MBB->predecessors()) {
879 LiveRegs.clear();
880 LiveRegs.addLiveOuts(MBB: *Pred);
881 MachineBasicBlock::iterator InsertBefore = Pred->getFirstTerminator();
882 for (Register Reg : NewLiveIns) {
883 if (!LiveRegs.available(MRI: *MRI, Reg))
884 continue;
885
886 // Skip the register if we are about to add one of its super registers.
887 // TODO: Common this up with the same logic in addLineIns().
888 if (any_of(Range: TRI->superregs(Reg), P: [&](MCPhysReg SReg) {
889 return NewLiveIns.contains(Reg: SReg) && !MRI->isReserved(PhysReg: SReg);
890 }))
891 continue;
892
893 DebugLoc DL;
894 BuildMI(BB&: *Pred, I: InsertBefore, MIMD: DL, MCID: TII->get(Opcode: TargetOpcode::IMPLICIT_DEF),
895 DestReg: Reg);
896 }
897 }
898
899 MBB->clearLiveIns();
900 addLiveIns(MBB&: *MBB, LiveRegs: NewLiveIns);
901 }
902}
903
904// See if any of the blocks in MergePotentials (which all have SuccBB as a
905// successor, or all have no successor if it is null) can be tail-merged.
906// If there is a successor, any blocks in MergePotentials that are not
907// tail-merged and are not immediately before Succ must have an unconditional
908// branch to Succ added (but the predecessor/successor lists need no
909// adjustment). The lone predecessor of Succ that falls through into Succ,
910// if any, is given in PredBB.
911// MinCommonTailLength - Except for the special cases below, tail-merge if
912// there are at least this many instructions in common.
913bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
914 MachineBasicBlock *PredBB,
915 unsigned MinCommonTailLength) {
916 bool MadeChange = false;
917
918 LLVM_DEBUG({
919 dbgs() << "\nTryTailMergeBlocks: ";
920 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
921 dbgs() << printMBBReference(*MergePotentials[i].getBlock())
922 << (i == e - 1 ? "" : ", ");
923 dbgs() << "\n";
924 if (SuccBB) {
925 dbgs() << " with successor " << printMBBReference(*SuccBB) << '\n';
926 if (PredBB)
927 dbgs() << " which has fall-through from " << printMBBReference(*PredBB)
928 << "\n";
929 }
930 dbgs() << "Looking for common tails of at least " << MinCommonTailLength
931 << " instruction" << (MinCommonTailLength == 1 ? "" : "s") << '\n';
932 });
933
934 // Sort by hash value so that blocks with identical end sequences sort
935 // together.
936 array_pod_sort(Start: MergePotentials.begin(), End: MergePotentials.end());
937
938 // Walk through equivalence sets looking for actual exact matches.
939 while (MergePotentials.size() > 1) {
940 unsigned CurHash = MergePotentials.back().getHash();
941 const DebugLoc &BranchDL = MergePotentials.back().getBranchDebugLoc();
942
943 // Build SameTails, identifying the set of blocks with this hash code
944 // and with the maximum number of instructions in common.
945 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
946 MinCommonTailLength,
947 SuccBB, PredBB);
948
949 // If we didn't find any pair that has at least MinCommonTailLength
950 // instructions in common, remove all blocks with this hash code and retry.
951 if (SameTails.empty()) {
952 RemoveBlocksWithHash(CurHash, SuccBB, PredBB, BranchDL);
953 continue;
954 }
955
956 // If one of the blocks is the entire common tail (and is not the entry
957 // block/an EH pad, which we can't jump to), we can treat all blocks with
958 // this same tail at once. Use PredBB if that is one of the possibilities,
959 // as that will not introduce any extra branches.
960 MachineBasicBlock *EntryBB =
961 &MergePotentials.front().getBlock()->getParent()->front();
962 unsigned commonTailIndex = SameTails.size();
963 // If there are two blocks, check to see if one can be made to fall through
964 // into the other.
965 if (SameTails.size() == 2 &&
966 SameTails[0].getBlock()->isLayoutSuccessor(MBB: SameTails[1].getBlock()) &&
967 SameTails[1].tailIsWholeBlock() && !SameTails[1].getBlock()->isEHPad())
968 commonTailIndex = 1;
969 else if (SameTails.size() == 2 &&
970 SameTails[1].getBlock()->isLayoutSuccessor(
971 MBB: SameTails[0].getBlock()) &&
972 SameTails[0].tailIsWholeBlock() &&
973 !SameTails[0].getBlock()->isEHPad())
974 commonTailIndex = 0;
975 else {
976 // Otherwise just pick one, favoring the fall-through predecessor if
977 // there is one.
978 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
979 MachineBasicBlock *MBB = SameTails[i].getBlock();
980 if ((MBB == EntryBB || MBB->isEHPad()) &&
981 SameTails[i].tailIsWholeBlock())
982 continue;
983 if (MBB == PredBB) {
984 commonTailIndex = i;
985 break;
986 }
987 if (SameTails[i].tailIsWholeBlock())
988 commonTailIndex = i;
989 }
990 }
991
992 if (commonTailIndex == SameTails.size() ||
993 (SameTails[commonTailIndex].getBlock() == PredBB &&
994 !SameTails[commonTailIndex].tailIsWholeBlock())) {
995 // None of the blocks consist entirely of the common tail.
996 // Split a block so that one does.
997 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
998 maxCommonTailLength, commonTailIndex)) {
999 RemoveBlocksWithHash(CurHash, SuccBB, PredBB, BranchDL);
1000 continue;
1001 }
1002 }
1003
1004 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
1005
1006 // Recompute common tail MBB's edge weights and block frequency.
1007 setCommonTailEdgeWeights(*MBB);
1008
1009 // Merge debug locations, MMOs and undef flags across identical instructions
1010 // for common tail.
1011 mergeCommonTails(commonTailIndex);
1012
1013 // MBB is common tail. Adjust all other BB's to jump to this one.
1014 // Traversal must be forwards so erases work.
1015 LLVM_DEBUG(dbgs() << "\nUsing common tail in " << printMBBReference(*MBB)
1016 << " for ");
1017 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
1018 if (commonTailIndex == i)
1019 continue;
1020 LLVM_DEBUG(dbgs() << printMBBReference(*SameTails[i].getBlock())
1021 << (i == e - 1 ? "" : ", "));
1022 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
1023 replaceTailWithBranchTo(OldInst: SameTails[i].getTailStartPos(), NewDest&: *MBB);
1024 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
1025 MergePotentials.erase(position: SameTails[i].getMPIter());
1026 }
1027 LLVM_DEBUG(dbgs() << "\n");
1028 // We leave commonTailIndex in the worklist in case there are other blocks
1029 // that match it with a smaller number of instructions.
1030 MadeChange = true;
1031 }
1032 return MadeChange;
1033}
1034
1035bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
1036 bool MadeChange = false;
1037 if (!EnableTailMerge)
1038 return MadeChange;
1039
1040 // First find blocks with no successors.
1041 // Block placement may create new tail merging opportunities for these blocks.
1042 MergePotentials.clear();
1043 for (MachineBasicBlock &MBB : MF) {
1044 if (MergePotentials.size() == TailMergeThreshold)
1045 break;
1046 if (!TriedMerging.count(Ptr: &MBB) && MBB.succ_empty())
1047 MergePotentials.push_back(x: MergePotentialsElt(HashEndOfMBB(MBB), &MBB,
1048 MBB.findBranchDebugLoc()));
1049 }
1050
1051 // If this is a large problem, avoid visiting the same basic blocks
1052 // multiple times.
1053 if (MergePotentials.size() == TailMergeThreshold)
1054 for (const MergePotentialsElt &Elt : MergePotentials)
1055 TriedMerging.insert(Ptr: Elt.getBlock());
1056
1057 // See if we can do any tail merging on those.
1058 if (MergePotentials.size() >= 2)
1059 MadeChange |= TryTailMergeBlocks(SuccBB: nullptr, PredBB: nullptr, MinCommonTailLength);
1060
1061 // Look at blocks (IBB) with multiple predecessors (PBB).
1062 // We change each predecessor to a canonical form, by
1063 // (1) temporarily removing any unconditional branch from the predecessor
1064 // to IBB, and
1065 // (2) alter conditional branches so they branch to the other block
1066 // not IBB; this may require adding back an unconditional branch to IBB
1067 // later, where there wasn't one coming in. E.g.
1068 // Bcc IBB
1069 // fallthrough to QBB
1070 // here becomes
1071 // Bncc QBB
1072 // with a conceptual B to IBB after that, which never actually exists.
1073 // With those changes, we see whether the predecessors' tails match,
1074 // and merge them if so. We change things out of canonical form and
1075 // back to the way they were later in the process. (OptimizeBranches
1076 // would undo some of this, but we can't use it, because we'd get into
1077 // a compile-time infinite loop repeatedly doing and undoing the same
1078 // transformations.)
1079
1080 for (MachineFunction::iterator I = std::next(x: MF.begin()), E = MF.end();
1081 I != E; ++I) {
1082 if (I->pred_size() < 2) continue;
1083 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
1084 MachineBasicBlock *IBB = &*I;
1085 MachineBasicBlock *PredBB = &*std::prev(x: I);
1086 MergePotentials.clear();
1087 MachineLoop *ML;
1088
1089 // Bail if merging after placement and IBB is the loop header because
1090 // -- If merging predecessors that belong to the same loop as IBB, the
1091 // common tail of merged predecessors may become the loop top if block
1092 // placement is called again and the predecessors may branch to this common
1093 // tail and require more branches. This can be relaxed if
1094 // MachineBlockPlacement::findBestLoopTop is more flexible.
1095 // --If merging predecessors that do not belong to the same loop as IBB, the
1096 // loop info of IBB's loop and the other loops may be affected. Calling the
1097 // block placement again may make big change to the layout and eliminate the
1098 // reason to do tail merging here.
1099 if (AfterBlockPlacement && MLI) {
1100 ML = MLI->getLoopFor(BB: IBB);
1101 if (ML && IBB == ML->getHeader())
1102 continue;
1103 }
1104
1105 for (MachineBasicBlock *PBB : I->predecessors()) {
1106 if (MergePotentials.size() == TailMergeThreshold)
1107 break;
1108
1109 if (TriedMerging.count(Ptr: PBB))
1110 continue;
1111
1112 // Skip blocks that loop to themselves, can't tail merge these.
1113 if (PBB == IBB)
1114 continue;
1115
1116 // Visit each predecessor only once.
1117 if (!UniquePreds.insert(Ptr: PBB).second)
1118 continue;
1119
1120 // Skip blocks which may jump to a landing pad or jump from an asm blob.
1121 // Can't tail merge these.
1122 if (PBB->hasEHPadSuccessor() || PBB->mayHaveInlineAsmBr())
1123 continue;
1124
1125 // After block placement, only consider predecessors that belong to the
1126 // same loop as IBB. The reason is the same as above when skipping loop
1127 // header.
1128 if (AfterBlockPlacement && MLI)
1129 if (ML != MLI->getLoopFor(BB: PBB))
1130 continue;
1131
1132 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1133 SmallVector<MachineOperand, 4> Cond;
1134 if (!TII->analyzeBranch(MBB&: *PBB, TBB, FBB, Cond, AllowModify: true)) {
1135 // Failing case: IBB is the target of a cbr, and we cannot reverse the
1136 // branch.
1137 SmallVector<MachineOperand, 4> NewCond(Cond);
1138 if (!Cond.empty() && TBB == IBB) {
1139 if (TII->reverseBranchCondition(Cond&: NewCond))
1140 continue;
1141 // This is the QBB case described above
1142 if (!FBB) {
1143 auto Next = ++PBB->getIterator();
1144 if (Next != MF.end())
1145 FBB = &*Next;
1146 }
1147 }
1148
1149 // Remove the unconditional branch at the end, if any.
1150 DebugLoc dl = PBB->findBranchDebugLoc();
1151 if (TBB && (Cond.empty() || FBB)) {
1152 TII->removeBranch(MBB&: *PBB);
1153 if (!Cond.empty())
1154 // reinsert conditional branch only, for now
1155 TII->insertBranch(MBB&: *PBB, TBB: (TBB == IBB) ? FBB : TBB, FBB: nullptr,
1156 Cond: NewCond, DL: dl);
1157 }
1158
1159 MergePotentials.push_back(
1160 x: MergePotentialsElt(HashEndOfMBB(MBB: *PBB), PBB, dl));
1161 }
1162 }
1163
1164 // If this is a large problem, avoid visiting the same basic blocks multiple
1165 // times.
1166 if (MergePotentials.size() == TailMergeThreshold)
1167 for (MergePotentialsElt &Elt : MergePotentials)
1168 TriedMerging.insert(Ptr: Elt.getBlock());
1169
1170 if (MergePotentials.size() >= 2)
1171 MadeChange |= TryTailMergeBlocks(SuccBB: IBB, PredBB, MinCommonTailLength);
1172
1173 // Reinsert an unconditional branch if needed. The 1 below can occur as a
1174 // result of removing blocks in TryTailMergeBlocks.
1175 PredBB = &*std::prev(x: I); // this may have been changed in TryTailMergeBlocks
1176 if (MergePotentials.size() == 1 &&
1177 MergePotentials.begin()->getBlock() != PredBB)
1178 FixTail(CurMBB: MergePotentials.begin()->getBlock(), SuccBB: IBB, TII,
1179 BranchDL: MergePotentials.begin()->getBranchDebugLoc());
1180 }
1181
1182 return MadeChange;
1183}
1184
1185void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
1186 SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
1187 BlockFrequency AccumulatedMBBFreq;
1188
1189 // Aggregate edge frequency of successor edge j:
1190 // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1191 // where bb is a basic block that is in SameTails.
1192 for (const auto &Src : SameTails) {
1193 const MachineBasicBlock *SrcMBB = Src.getBlock();
1194 BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(MBB: SrcMBB);
1195 AccumulatedMBBFreq += BlockFreq;
1196
1197 // It is not necessary to recompute edge weights if TailBB has less than two
1198 // successors.
1199 if (TailMBB.succ_size() <= 1)
1200 continue;
1201
1202 auto EdgeFreq = EdgeFreqLs.begin();
1203
1204 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1205 SuccI != SuccE; ++SuccI, ++EdgeFreq)
1206 *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(Src: SrcMBB, Dst: *SuccI);
1207 }
1208
1209 MBBFreqInfo.setBlockFreq(MBB: &TailMBB, F: AccumulatedMBBFreq);
1210
1211 if (TailMBB.succ_size() <= 1)
1212 return;
1213
1214 auto SumEdgeFreq =
1215 std::accumulate(first: EdgeFreqLs.begin(), last: EdgeFreqLs.end(), init: BlockFrequency(0))
1216 .getFrequency();
1217 auto EdgeFreq = EdgeFreqLs.begin();
1218
1219 if (SumEdgeFreq > 0) {
1220 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1221 SuccI != SuccE; ++SuccI, ++EdgeFreq) {
1222 auto Prob = BranchProbability::getBranchProbability(
1223 Numerator: EdgeFreq->getFrequency(), Denominator: SumEdgeFreq);
1224 TailMBB.setSuccProbability(I: SuccI, Prob);
1225 }
1226 }
1227}
1228
1229//===----------------------------------------------------------------------===//
1230// Branch Optimization
1231//===----------------------------------------------------------------------===//
1232
1233bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
1234 bool MadeChange = false;
1235
1236 // Make sure blocks are numbered in order
1237 MF.RenumberBlocks();
1238 // Renumbering blocks alters EH scope membership, recalculate it.
1239 EHScopeMembership = getEHScopeMembership(MF);
1240
1241 for (MachineBasicBlock &MBB :
1242 llvm::make_early_inc_range(Range: llvm::drop_begin(RangeOrContainer&: MF))) {
1243 MadeChange |= OptimizeBlock(MBB: &MBB);
1244
1245 // If it is dead, remove it.
1246 if (MBB.pred_empty() && !MBB.isMachineBlockAddressTaken()) {
1247 RemoveDeadBlock(MBB: &MBB);
1248 MadeChange = true;
1249 ++NumDeadBlocks;
1250 }
1251 }
1252
1253 return MadeChange;
1254}
1255
1256// Blocks should be considered empty if they contain only debug info;
1257// else the debug info would affect codegen.
1258static bool IsEmptyBlock(MachineBasicBlock *MBB) {
1259 return MBB->getFirstNonDebugInstr(SkipPseudoOp: true) == MBB->end();
1260}
1261
1262// Blocks with only debug info and branches should be considered the same
1263// as blocks with only branches.
1264static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
1265 MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
1266 assert(I != MBB->end() && "empty block!");
1267 return I->isBranch();
1268}
1269
1270/// IsBetterFallthrough - Return true if it would be clearly better to
1271/// fall-through to MBB1 than to fall through into MBB2. This has to return
1272/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1273/// result in infinite loops.
1274static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
1275 MachineBasicBlock *MBB2) {
1276 assert(MBB1 && MBB2 && "Unknown MachineBasicBlock");
1277
1278 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
1279 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
1280 // optimize branches that branch to either a return block or an assert block
1281 // into a fallthrough to the return.
1282 MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();
1283 MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();
1284 if (MBB1I == MBB1->end() || MBB2I == MBB2->end())
1285 return false;
1286
1287 // If there is a clear successor ordering we make sure that one block
1288 // will fall through to the next
1289 if (MBB1->isSuccessor(MBB: MBB2)) return true;
1290 if (MBB2->isSuccessor(MBB: MBB1)) return false;
1291
1292 return MBB2I->isCall() && !MBB1I->isCall();
1293}
1294
1295static void copyDebugInfoToPredecessor(const TargetInstrInfo *TII,
1296 MachineBasicBlock &MBB,
1297 MachineBasicBlock &PredMBB) {
1298 auto InsertBefore = PredMBB.getFirstTerminator();
1299 for (MachineInstr &MI : MBB.instrs())
1300 if (MI.isDebugInstr()) {
1301 TII->duplicate(MBB&: PredMBB, InsertBefore, Orig: MI);
1302 LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to pred: "
1303 << MI);
1304 }
1305}
1306
1307static void copyDebugInfoToSuccessor(const TargetInstrInfo *TII,
1308 MachineBasicBlock &MBB,
1309 MachineBasicBlock &SuccMBB) {
1310 auto InsertBefore = SuccMBB.SkipPHIsAndLabels(I: SuccMBB.begin());
1311 for (MachineInstr &MI : MBB.instrs())
1312 if (MI.isDebugInstr()) {
1313 TII->duplicate(MBB&: SuccMBB, InsertBefore, Orig: MI);
1314 LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to succ: "
1315 << MI);
1316 }
1317}
1318
1319// Try to salvage DBG_VALUE instructions from an otherwise empty block. If such
1320// a basic block is removed we would lose the debug information unless we have
1321// copied the information to a predecessor/successor.
1322//
1323// TODO: This function only handles some simple cases. An alternative would be
1324// to run a heavier analysis, such as the LiveDebugValues pass, before we do
1325// branch folding.
1326static void salvageDebugInfoFromEmptyBlock(const TargetInstrInfo *TII,
1327 MachineBasicBlock &MBB) {
1328 assert(IsEmptyBlock(&MBB) && "Expected an empty block (except debug info).");
1329 // If this MBB is the only predecessor of a successor it is legal to copy
1330 // DBG_VALUE instructions to the beginning of the successor.
1331 for (MachineBasicBlock *SuccBB : MBB.successors())
1332 if (SuccBB->pred_size() == 1)
1333 copyDebugInfoToSuccessor(TII, MBB, SuccMBB&: *SuccBB);
1334 // If this MBB is the only successor of a predecessor it is legal to copy the
1335 // DBG_VALUE instructions to the end of the predecessor (just before the
1336 // terminators, assuming that the terminator isn't affecting the DBG_VALUE).
1337 for (MachineBasicBlock *PredBB : MBB.predecessors())
1338 if (PredBB->succ_size() == 1)
1339 copyDebugInfoToPredecessor(TII, MBB, PredMBB&: *PredBB);
1340}
1341
1342bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1343 bool MadeChange = false;
1344 MachineFunction &MF = *MBB->getParent();
1345ReoptimizeBlock:
1346
1347 MachineFunction::iterator FallThrough = MBB->getIterator();
1348 ++FallThrough;
1349
1350 // Make sure MBB and FallThrough belong to the same EH scope.
1351 bool SameEHScope = true;
1352 if (!EHScopeMembership.empty() && FallThrough != MF.end()) {
1353 auto MBBEHScope = EHScopeMembership.find(Val: MBB);
1354 assert(MBBEHScope != EHScopeMembership.end());
1355 auto FallThroughEHScope = EHScopeMembership.find(Val: &*FallThrough);
1356 assert(FallThroughEHScope != EHScopeMembership.end());
1357 SameEHScope = MBBEHScope->second == FallThroughEHScope->second;
1358 }
1359
1360 // Analyze the branch in the current block. As a side-effect, this may cause
1361 // the block to become empty.
1362 MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
1363 SmallVector<MachineOperand, 4> CurCond;
1364 bool CurUnAnalyzable =
1365 TII->analyzeBranch(MBB&: *MBB, TBB&: CurTBB, FBB&: CurFBB, Cond&: CurCond, AllowModify: true);
1366
1367 // If this block is empty, make everyone use its fall-through, not the block
1368 // explicitly. Landing pads should not do this since the landing-pad table
1369 // points to this block. Blocks with their addresses taken shouldn't be
1370 // optimized away.
1371 if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&
1372 SameEHScope) {
1373 salvageDebugInfoFromEmptyBlock(TII, MBB&: *MBB);
1374 // Dead block? Leave for cleanup later.
1375 if (MBB->pred_empty()) return MadeChange;
1376
1377 if (FallThrough == MF.end()) {
1378 // TODO: Simplify preds to not branch here if possible!
1379 } else if (FallThrough->isEHPad()) {
1380 // Don't rewrite to a landing pad fallthough. That could lead to the case
1381 // where a BB jumps to more than one landing pad.
1382 // TODO: Is it ever worth rewriting predecessors which don't already
1383 // jump to a landing pad, and so can safely jump to the fallthrough?
1384 } else if (MBB->isSuccessor(MBB: &*FallThrough)) {
1385 // Rewrite all predecessors of the old block to go to the fallthrough
1386 // instead.
1387 while (!MBB->pred_empty()) {
1388 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1389 Pred->ReplaceUsesOfBlockWith(Old: MBB, New: &*FallThrough);
1390 }
1391 // Add rest successors of MBB to successors of FallThrough. Those
1392 // successors are not directly reachable via MBB, so it should be
1393 // landing-pad.
1394 for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI)
1395 if (*SI != &*FallThrough && !FallThrough->isSuccessor(MBB: *SI)) {
1396 assert((*SI)->isEHPad() && "Bad CFG");
1397 FallThrough->copySuccessor(Orig: MBB, I: SI);
1398 }
1399 // If MBB was the target of a jump table, update jump tables to go to the
1400 // fallthrough instead.
1401 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1402 MJTI->ReplaceMBBInJumpTables(Old: MBB, New: &*FallThrough);
1403 MadeChange = true;
1404 }
1405 return MadeChange;
1406 }
1407
1408 // Check to see if we can simplify the terminator of the block before this
1409 // one.
1410 MachineBasicBlock &PrevBB = *std::prev(x: MachineFunction::iterator(MBB));
1411
1412 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
1413 SmallVector<MachineOperand, 4> PriorCond;
1414 bool PriorUnAnalyzable =
1415 TII->analyzeBranch(MBB&: PrevBB, TBB&: PriorTBB, FBB&: PriorFBB, Cond&: PriorCond, AllowModify: true);
1416 if (!PriorUnAnalyzable) {
1417 // If the previous branch is conditional and both conditions go to the same
1418 // destination, remove the branch, replacing it with an unconditional one or
1419 // a fall-through.
1420 if (PriorTBB && PriorTBB == PriorFBB) {
1421 DebugLoc Dl = PrevBB.findBranchDebugLoc();
1422 TII->removeBranch(MBB&: PrevBB);
1423 PriorCond.clear();
1424 if (PriorTBB != MBB)
1425 TII->insertBranch(MBB&: PrevBB, TBB: PriorTBB, FBB: nullptr, Cond: PriorCond, DL: Dl);
1426 MadeChange = true;
1427 ++NumBranchOpts;
1428 goto ReoptimizeBlock;
1429 }
1430
1431 // If the previous block unconditionally falls through to this block and
1432 // this block has no other predecessors, move the contents of this block
1433 // into the prior block. This doesn't usually happen when SimplifyCFG
1434 // has been used, but it can happen if tail merging splits a fall-through
1435 // predecessor of a block.
1436 // This has to check PrevBB->succ_size() because EH edges are ignored by
1437 // analyzeBranch.
1438 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1439 PrevBB.succ_size() == 1 && PrevBB.isSuccessor(MBB) &&
1440 !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1441 LLVM_DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1442 << "From MBB: " << *MBB);
1443 // Remove redundant DBG_VALUEs first.
1444 if (!PrevBB.empty()) {
1445 MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1446 --PrevBBIter;
1447 MachineBasicBlock::iterator MBBIter = MBB->begin();
1448 // Check if DBG_VALUE at the end of PrevBB is identical to the
1449 // DBG_VALUE at the beginning of MBB.
1450 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1451 && PrevBBIter->isDebugInstr() && MBBIter->isDebugInstr()) {
1452 if (!MBBIter->isIdenticalTo(Other: *PrevBBIter))
1453 break;
1454 MachineInstr &DuplicateDbg = *MBBIter;
1455 ++MBBIter; -- PrevBBIter;
1456 DuplicateDbg.eraseFromParent();
1457 }
1458 }
1459 PrevBB.splice(Where: PrevBB.end(), Other: MBB, From: MBB->begin(), To: MBB->end());
1460 PrevBB.removeSuccessor(I: PrevBB.succ_begin());
1461 assert(PrevBB.succ_empty());
1462 PrevBB.transferSuccessors(FromMBB: MBB);
1463 MadeChange = true;
1464 return MadeChange;
1465 }
1466
1467 // If the previous branch *only* branches to *this* block (conditional or
1468 // not) remove the branch.
1469 if (PriorTBB == MBB && !PriorFBB) {
1470 TII->removeBranch(MBB&: PrevBB);
1471 MadeChange = true;
1472 ++NumBranchOpts;
1473 goto ReoptimizeBlock;
1474 }
1475
1476 // If the prior block branches somewhere else on the condition and here if
1477 // the condition is false, remove the uncond second branch.
1478 if (PriorFBB == MBB) {
1479 DebugLoc Dl = PrevBB.findBranchDebugLoc();
1480 TII->removeBranch(MBB&: PrevBB);
1481 TII->insertBranch(MBB&: PrevBB, TBB: PriorTBB, FBB: nullptr, Cond: PriorCond, DL: Dl);
1482 MadeChange = true;
1483 ++NumBranchOpts;
1484 goto ReoptimizeBlock;
1485 }
1486
1487 // If the prior block branches here on true and somewhere else on false, and
1488 // if the branch condition is reversible, reverse the branch to create a
1489 // fall-through.
1490 if (PriorTBB == MBB) {
1491 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1492 if (!TII->reverseBranchCondition(Cond&: NewPriorCond)) {
1493 DebugLoc Dl = PrevBB.findBranchDebugLoc();
1494 TII->removeBranch(MBB&: PrevBB);
1495 TII->insertBranch(MBB&: PrevBB, TBB: PriorFBB, FBB: nullptr, Cond: NewPriorCond, DL: Dl);
1496 MadeChange = true;
1497 ++NumBranchOpts;
1498 goto ReoptimizeBlock;
1499 }
1500 }
1501
1502 // If this block has no successors (e.g. it is a return block or ends with
1503 // a call to a no-return function like abort or __cxa_throw) and if the pred
1504 // falls through into this block, and if it would otherwise fall through
1505 // into the block after this, move this block to the end of the function.
1506 //
1507 // We consider it more likely that execution will stay in the function (e.g.
1508 // due to loops) than it is to exit it. This asserts in loops etc, moving
1509 // the assert condition out of the loop body.
1510 if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
1511 MachineFunction::iterator(PriorTBB) == FallThrough &&
1512 !MBB->canFallThrough()) {
1513 bool DoTransform = true;
1514
1515 // We have to be careful that the succs of PredBB aren't both no-successor
1516 // blocks. If neither have successors and if PredBB is the second from
1517 // last block in the function, we'd just keep swapping the two blocks for
1518 // last. Only do the swap if one is clearly better to fall through than
1519 // the other.
1520 if (FallThrough == --MF.end() &&
1521 !IsBetterFallthrough(MBB1: PriorTBB, MBB2: MBB))
1522 DoTransform = false;
1523
1524 if (DoTransform) {
1525 // Reverse the branch so we will fall through on the previous true cond.
1526 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1527 if (!TII->reverseBranchCondition(Cond&: NewPriorCond)) {
1528 LLVM_DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1529 << "To make fallthrough to: " << *PriorTBB << "\n");
1530
1531 DebugLoc Dl = PrevBB.findBranchDebugLoc();
1532 TII->removeBranch(MBB&: PrevBB);
1533 TII->insertBranch(MBB&: PrevBB, TBB: MBB, FBB: nullptr, Cond: NewPriorCond, DL: Dl);
1534
1535 // Move this block to the end of the function.
1536 MBB->moveAfter(NewBefore: &MF.back());
1537 MadeChange = true;
1538 ++NumBranchOpts;
1539 return MadeChange;
1540 }
1541 }
1542 }
1543 }
1544
1545 if (!IsEmptyBlock(MBB)) {
1546 MachineInstr &TailCall = *MBB->getFirstNonDebugInstr();
1547 if (TII->isUnconditionalTailCall(MI: TailCall)) {
1548 SmallVector<MachineBasicBlock *> PredsChanged;
1549 for (auto &Pred : MBB->predecessors()) {
1550 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1551 SmallVector<MachineOperand, 4> PredCond;
1552 bool PredAnalyzable =
1553 !TII->analyzeBranch(MBB&: *Pred, TBB&: PredTBB, FBB&: PredFBB, Cond&: PredCond, AllowModify: true);
1554
1555 // Only eliminate if MBB == TBB (Taken Basic Block)
1556 if (PredAnalyzable && !PredCond.empty() && PredTBB == MBB &&
1557 PredTBB != PredFBB) {
1558 // The predecessor has a conditional branch to this block which
1559 // consists of only a tail call. Try to fold the tail call into the
1560 // conditional branch.
1561 if (TII->canMakeTailCallConditional(Cond&: PredCond, TailCall)) {
1562 // TODO: It would be nice if analyzeBranch() could provide a pointer
1563 // to the branch instruction so replaceBranchWithTailCall() doesn't
1564 // have to search for it.
1565 TII->replaceBranchWithTailCall(MBB&: *Pred, Cond&: PredCond, TailCall);
1566 PredsChanged.push_back(Elt: Pred);
1567 }
1568 }
1569 // If the predecessor is falling through to this block, we could reverse
1570 // the branch condition and fold the tail call into that. However, after
1571 // that we might have to re-arrange the CFG to fall through to the other
1572 // block and there is a high risk of regressing code size rather than
1573 // improving it.
1574 }
1575 if (!PredsChanged.empty()) {
1576 NumTailCalls += PredsChanged.size();
1577 for (auto &Pred : PredsChanged)
1578 Pred->removeSuccessor(Succ: MBB);
1579
1580 return true;
1581 }
1582 }
1583 }
1584
1585 if (!CurUnAnalyzable) {
1586 // If this is a two-way branch, and the FBB branches to this block, reverse
1587 // the condition so the single-basic-block loop is faster. Instead of:
1588 // Loop: xxx; jcc Out; jmp Loop
1589 // we want:
1590 // Loop: xxx; jncc Loop; jmp Out
1591 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1592 SmallVector<MachineOperand, 4> NewCond(CurCond);
1593 if (!TII->reverseBranchCondition(Cond&: NewCond)) {
1594 DebugLoc Dl = MBB->findBranchDebugLoc();
1595 TII->removeBranch(MBB&: *MBB);
1596 TII->insertBranch(MBB&: *MBB, TBB: CurFBB, FBB: CurTBB, Cond: NewCond, DL: Dl);
1597 MadeChange = true;
1598 ++NumBranchOpts;
1599 goto ReoptimizeBlock;
1600 }
1601 }
1602
1603 // If this branch is the only thing in its block, see if we can forward
1604 // other blocks across it.
1605 if (CurTBB && CurCond.empty() && !CurFBB &&
1606 IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1607 !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1608 DebugLoc Dl = MBB->findBranchDebugLoc();
1609 // This block may contain just an unconditional branch. Because there can
1610 // be 'non-branch terminators' in the block, try removing the branch and
1611 // then seeing if the block is empty.
1612 TII->removeBranch(MBB&: *MBB);
1613 // If the only things remaining in the block are debug info, remove these
1614 // as well, so this will behave the same as an empty block in non-debug
1615 // mode.
1616 if (IsEmptyBlock(MBB)) {
1617 // Make the block empty, losing the debug info (we could probably
1618 // improve this in some cases.)
1619 MBB->erase(I: MBB->begin(), E: MBB->end());
1620 }
1621 // If this block is just an unconditional branch to CurTBB, we can
1622 // usually completely eliminate the block. The only case we cannot
1623 // completely eliminate the block is when the block before this one
1624 // falls through into MBB and we can't understand the prior block's branch
1625 // condition.
1626 if (MBB->empty()) {
1627 bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1628 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1629 !PrevBB.isSuccessor(MBB)) {
1630 // If the prior block falls through into us, turn it into an
1631 // explicit branch to us to make updates simpler.
1632 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1633 PriorTBB != MBB && PriorFBB != MBB) {
1634 if (!PriorTBB) {
1635 assert(PriorCond.empty() && !PriorFBB &&
1636 "Bad branch analysis");
1637 PriorTBB = MBB;
1638 } else {
1639 assert(!PriorFBB && "Machine CFG out of date!");
1640 PriorFBB = MBB;
1641 }
1642 DebugLoc PrevDl = PrevBB.findBranchDebugLoc();
1643 TII->removeBranch(MBB&: PrevBB);
1644 TII->insertBranch(MBB&: PrevBB, TBB: PriorTBB, FBB: PriorFBB, Cond: PriorCond, DL: PrevDl);
1645 }
1646
1647 // Iterate through all the predecessors, revectoring each in-turn.
1648 size_t PI = 0;
1649 bool DidChange = false;
1650 bool HasBranchToSelf = false;
1651 while(PI != MBB->pred_size()) {
1652 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1653 if (PMBB == MBB) {
1654 // If this block has an uncond branch to itself, leave it.
1655 ++PI;
1656 HasBranchToSelf = true;
1657 } else {
1658 DidChange = true;
1659 PMBB->ReplaceUsesOfBlockWith(Old: MBB, New: CurTBB);
1660 // Add rest successors of MBB to successors of CurTBB. Those
1661 // successors are not directly reachable via MBB, so it should be
1662 // landing-pad.
1663 for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE;
1664 ++SI)
1665 if (*SI != CurTBB && !CurTBB->isSuccessor(MBB: *SI)) {
1666 assert((*SI)->isEHPad() && "Bad CFG");
1667 CurTBB->copySuccessor(Orig: MBB, I: SI);
1668 }
1669 // If this change resulted in PMBB ending in a conditional
1670 // branch where both conditions go to the same destination,
1671 // change this to an unconditional branch.
1672 MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
1673 SmallVector<MachineOperand, 4> NewCurCond;
1674 bool NewCurUnAnalyzable = TII->analyzeBranch(
1675 MBB&: *PMBB, TBB&: NewCurTBB, FBB&: NewCurFBB, Cond&: NewCurCond, AllowModify: true);
1676 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1677 DebugLoc PrevDl = PMBB->findBranchDebugLoc();
1678 TII->removeBranch(MBB&: *PMBB);
1679 NewCurCond.clear();
1680 TII->insertBranch(MBB&: *PMBB, TBB: NewCurTBB, FBB: nullptr, Cond: NewCurCond,
1681 DL: PrevDl);
1682 MadeChange = true;
1683 ++NumBranchOpts;
1684 }
1685 }
1686 }
1687
1688 // Change any jumptables to go to the new MBB.
1689 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1690 MJTI->ReplaceMBBInJumpTables(Old: MBB, New: CurTBB);
1691 if (DidChange) {
1692 ++NumBranchOpts;
1693 MadeChange = true;
1694 if (!HasBranchToSelf) return MadeChange;
1695 }
1696 }
1697 }
1698
1699 // Add the branch back if the block is more than just an uncond branch.
1700 TII->insertBranch(MBB&: *MBB, TBB: CurTBB, FBB: nullptr, Cond: CurCond, DL: Dl);
1701 }
1702 }
1703
1704 // If the prior block doesn't fall through into this block, and if this
1705 // block doesn't fall through into some other block, see if we can find a
1706 // place to move this block where a fall-through will happen.
1707 if (!PrevBB.canFallThrough()) {
1708 // Now we know that there was no fall-through into this block, check to
1709 // see if it has a fall-through into its successor.
1710 bool CurFallsThru = MBB->canFallThrough();
1711
1712 if (!MBB->isEHPad()) {
1713 // Check all the predecessors of this block. If one of them has no fall
1714 // throughs, and analyzeBranch thinks it _could_ fallthrough to this
1715 // block, move this block right after it.
1716 for (MachineBasicBlock *PredBB : MBB->predecessors()) {
1717 // Analyze the branch at the end of the pred.
1718 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1719 SmallVector<MachineOperand, 4> PredCond;
1720 if (PredBB != MBB && !PredBB->canFallThrough() &&
1721 !TII->analyzeBranch(MBB&: *PredBB, TBB&: PredTBB, FBB&: PredFBB, Cond&: PredCond, AllowModify: true) &&
1722 (PredTBB == MBB || PredFBB == MBB) &&
1723 (!CurFallsThru || !CurTBB || !CurFBB) &&
1724 (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1725 // If the current block doesn't fall through, just move it.
1726 // If the current block can fall through and does not end with a
1727 // conditional branch, we need to append an unconditional jump to
1728 // the (current) next block. To avoid a possible compile-time
1729 // infinite loop, move blocks only backward in this case.
1730 // Also, if there are already 2 branches here, we cannot add a third;
1731 // this means we have the case
1732 // Bcc next
1733 // B elsewhere
1734 // next:
1735 if (CurFallsThru) {
1736 MachineBasicBlock *NextBB = &*std::next(x: MBB->getIterator());
1737 CurCond.clear();
1738 TII->insertBranch(MBB&: *MBB, TBB: NextBB, FBB: nullptr, Cond: CurCond, DL: DebugLoc());
1739 }
1740 MBB->moveAfter(NewBefore: PredBB);
1741 MadeChange = true;
1742 goto ReoptimizeBlock;
1743 }
1744 }
1745 }
1746
1747 if (!CurFallsThru) {
1748 // Check analyzable branch-successors to see if we can move this block
1749 // before one.
1750 if (!CurUnAnalyzable) {
1751 for (MachineBasicBlock *SuccBB : {CurFBB, CurTBB}) {
1752 if (!SuccBB)
1753 continue;
1754 // Analyze the branch at the end of the block before the succ.
1755 MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
1756
1757 // If this block doesn't already fall-through to that successor, and
1758 // if the succ doesn't already have a block that can fall through into
1759 // it, we can arrange for the fallthrough to happen.
1760 if (SuccBB != MBB && &*SuccPrev != MBB &&
1761 !SuccPrev->canFallThrough()) {
1762 MBB->moveBefore(NewAfter: SuccBB);
1763 MadeChange = true;
1764 goto ReoptimizeBlock;
1765 }
1766 }
1767 }
1768
1769 // Okay, there is no really great place to put this block. If, however,
1770 // the block before this one would be a fall-through if this block were
1771 // removed, move this block to the end of the function. There is no real
1772 // advantage in "falling through" to an EH block, so we don't want to
1773 // perform this transformation for that case.
1774 //
1775 // Also, Windows EH introduced the possibility of an arbitrary number of
1776 // successors to a given block. The analyzeBranch call does not consider
1777 // exception handling and so we can get in a state where a block
1778 // containing a call is followed by multiple EH blocks that would be
1779 // rotated infinitely at the end of the function if the transformation
1780 // below were performed for EH "FallThrough" blocks. Therefore, even if
1781 // that appears not to be happening anymore, we should assume that it is
1782 // possible and not remove the "!FallThrough()->isEHPad" condition below.
1783 MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
1784 SmallVector<MachineOperand, 4> PrevCond;
1785 if (FallThrough != MF.end() &&
1786 !FallThrough->isEHPad() &&
1787 !TII->analyzeBranch(MBB&: PrevBB, TBB&: PrevTBB, FBB&: PrevFBB, Cond&: PrevCond, AllowModify: true) &&
1788 PrevBB.isSuccessor(MBB: &*FallThrough)) {
1789 MBB->moveAfter(NewBefore: &MF.back());
1790 MadeChange = true;
1791 return MadeChange;
1792 }
1793 }
1794 }
1795
1796 return MadeChange;
1797}
1798
1799//===----------------------------------------------------------------------===//
1800// Hoist Common Code
1801//===----------------------------------------------------------------------===//
1802
1803bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1804 bool MadeChange = false;
1805 for (MachineBasicBlock &MBB : llvm::make_early_inc_range(Range&: MF))
1806 MadeChange |= HoistCommonCodeInSuccs(MBB: &MBB);
1807
1808 return MadeChange;
1809}
1810
1811/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1812/// its 'true' successor.
1813static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1814 MachineBasicBlock *TrueBB) {
1815 for (MachineBasicBlock *SuccBB : BB->successors())
1816 if (SuccBB != TrueBB)
1817 return SuccBB;
1818 return nullptr;
1819}
1820
1821template <class Container>
1822static void addRegAndItsAliases(Register Reg, const TargetRegisterInfo *TRI,
1823 Container &Set) {
1824 if (Reg.isPhysical()) {
1825 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1826 Set.insert(*AI);
1827 } else {
1828 Set.insert(Reg);
1829 }
1830}
1831
1832/// findHoistingInsertPosAndDeps - Find the location to move common instructions
1833/// in successors to. The location is usually just before the terminator,
1834/// however if the terminator is a conditional branch and its previous
1835/// instruction is the flag setting instruction, the previous instruction is
1836/// the preferred location. This function also gathers uses and defs of the
1837/// instructions from the insertion point to the end of the block. The data is
1838/// used by HoistCommonCodeInSuccs to ensure safety.
1839static
1840MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1841 const TargetInstrInfo *TII,
1842 const TargetRegisterInfo *TRI,
1843 SmallSet<Register, 4> &Uses,
1844 SmallSet<Register, 4> &Defs) {
1845 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1846 if (!TII->isUnpredicatedTerminator(MI: *Loc))
1847 return MBB->end();
1848
1849 for (const MachineOperand &MO : Loc->operands()) {
1850 if (!MO.isReg())
1851 continue;
1852 Register Reg = MO.getReg();
1853 if (!Reg)
1854 continue;
1855 if (MO.isUse()) {
1856 addRegAndItsAliases(Reg, TRI, Set&: Uses);
1857 } else {
1858 if (!MO.isDead())
1859 // Don't try to hoist code in the rare case the terminator defines a
1860 // register that is later used.
1861 return MBB->end();
1862
1863 // If the terminator defines a register, make sure we don't hoist
1864 // the instruction whose def might be clobbered by the terminator.
1865 addRegAndItsAliases(Reg, TRI, Set&: Defs);
1866 }
1867 }
1868
1869 if (Uses.empty())
1870 return Loc;
1871 // If the terminator is the only instruction in the block and Uses is not
1872 // empty (or we would have returned above), we can still safely hoist
1873 // instructions just before the terminator as long as the Defs/Uses are not
1874 // violated (which is checked in HoistCommonCodeInSuccs).
1875 if (Loc == MBB->begin())
1876 return Loc;
1877
1878 // The terminator is probably a conditional branch, try not to separate the
1879 // branch from condition setting instruction.
1880 MachineBasicBlock::iterator PI = prev_nodbg(It: Loc, Begin: MBB->begin());
1881
1882 bool IsDef = false;
1883 for (const MachineOperand &MO : PI->operands()) {
1884 // If PI has a regmask operand, it is probably a call. Separate away.
1885 if (MO.isRegMask())
1886 return Loc;
1887 if (!MO.isReg() || MO.isUse())
1888 continue;
1889 Register Reg = MO.getReg();
1890 if (!Reg)
1891 continue;
1892 if (Uses.count(V: Reg)) {
1893 IsDef = true;
1894 break;
1895 }
1896 }
1897 if (!IsDef)
1898 // The condition setting instruction is not just before the conditional
1899 // branch.
1900 return Loc;
1901
1902 // Be conservative, don't insert instruction above something that may have
1903 // side-effects. And since it's potentially bad to separate flag setting
1904 // instruction from the conditional branch, just abort the optimization
1905 // completely.
1906 // Also avoid moving code above predicated instruction since it's hard to
1907 // reason about register liveness with predicated instruction.
1908 bool DontMoveAcrossStore = true;
1909 if (!PI->isSafeToMove(SawStore&: DontMoveAcrossStore) || TII->isPredicated(MI: *PI))
1910 return MBB->end();
1911
1912 // Find out what registers are live. Note this routine is ignoring other live
1913 // registers which are only used by instructions in successor blocks.
1914 for (const MachineOperand &MO : PI->operands()) {
1915 if (!MO.isReg())
1916 continue;
1917 Register Reg = MO.getReg();
1918 if (!Reg)
1919 continue;
1920 if (MO.isUse()) {
1921 addRegAndItsAliases(Reg, TRI, Set&: Uses);
1922 } else {
1923 if (Uses.erase(V: Reg)) {
1924 if (Reg.isPhysical()) {
1925 for (MCPhysReg SubReg : TRI->subregs(Reg))
1926 Uses.erase(V: SubReg); // Use sub-registers to be conservative
1927 }
1928 }
1929 addRegAndItsAliases(Reg, TRI, Set&: Defs);
1930 }
1931 }
1932
1933 return PI;
1934}
1935
1936bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1937 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1938 SmallVector<MachineOperand, 4> Cond;
1939 if (TII->analyzeBranch(MBB&: *MBB, TBB, FBB, Cond, AllowModify: true) || !TBB || Cond.empty())
1940 return false;
1941
1942 if (!FBB) FBB = findFalseBlock(BB: MBB, TrueBB: TBB);
1943 if (!FBB)
1944 // Malformed bcc? True and false blocks are the same?
1945 return false;
1946
1947 // Restrict the optimization to cases where MBB is the only predecessor,
1948 // it is an obvious win.
1949 if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1950 return false;
1951
1952 // Find a suitable position to hoist the common instructions to. Also figure
1953 // out which registers are used or defined by instructions from the insertion
1954 // point to the end of the block.
1955 SmallSet<Register, 4> Uses, Defs;
1956 MachineBasicBlock::iterator Loc =
1957 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1958 if (Loc == MBB->end())
1959 return false;
1960
1961 bool HasDups = false;
1962 SmallSet<Register, 4> ActiveDefsSet, AllDefsSet;
1963 MachineBasicBlock::iterator TIB = TBB->begin();
1964 MachineBasicBlock::iterator FIB = FBB->begin();
1965 MachineBasicBlock::iterator TIE = TBB->end();
1966 MachineBasicBlock::iterator FIE = FBB->end();
1967 while (TIB != TIE && FIB != FIE) {
1968 // Skip dbg_value instructions. These do not count.
1969 TIB = skipDebugInstructionsForward(It: TIB, End: TIE, SkipPseudoOp: false);
1970 FIB = skipDebugInstructionsForward(It: FIB, End: FIE, SkipPseudoOp: false);
1971 if (TIB == TIE || FIB == FIE)
1972 break;
1973
1974 if (!TIB->isIdenticalTo(Other: *FIB, Check: MachineInstr::CheckKillDead))
1975 break;
1976
1977 if (TII->isPredicated(MI: *TIB))
1978 // Hard to reason about register liveness with predicated instruction.
1979 break;
1980
1981 bool IsSafe = true;
1982 for (MachineOperand &MO : TIB->operands()) {
1983 // Don't attempt to hoist instructions with register masks.
1984 if (MO.isRegMask()) {
1985 IsSafe = false;
1986 break;
1987 }
1988 if (!MO.isReg())
1989 continue;
1990 Register Reg = MO.getReg();
1991 if (!Reg)
1992 continue;
1993 if (MO.isDef()) {
1994 if (Uses.count(V: Reg)) {
1995 // Avoid clobbering a register that's used by the instruction at
1996 // the point of insertion.
1997 IsSafe = false;
1998 break;
1999 }
2000
2001 if (Defs.count(V: Reg) && !MO.isDead()) {
2002 // Don't hoist the instruction if the def would be clobber by the
2003 // instruction at the point insertion. FIXME: This is overly
2004 // conservative. It should be possible to hoist the instructions
2005 // in BB2 in the following example:
2006 // BB1:
2007 // r1, eflag = op1 r2, r3
2008 // brcc eflag
2009 //
2010 // BB2:
2011 // r1 = op2, ...
2012 // = op3, killed r1
2013 IsSafe = false;
2014 break;
2015 }
2016 } else if (!ActiveDefsSet.count(V: Reg)) {
2017 if (Defs.count(V: Reg)) {
2018 // Use is defined by the instruction at the point of insertion.
2019 IsSafe = false;
2020 break;
2021 }
2022
2023 if (MO.isKill() && Uses.count(V: Reg))
2024 // Kills a register that's read by the instruction at the point of
2025 // insertion. Remove the kill marker.
2026 MO.setIsKill(false);
2027 }
2028 }
2029 if (!IsSafe)
2030 break;
2031
2032 bool DontMoveAcrossStore = true;
2033 if (!TIB->isSafeToMove(SawStore&: DontMoveAcrossStore))
2034 break;
2035
2036 // Remove kills from ActiveDefsSet, these registers had short live ranges.
2037 for (const MachineOperand &MO : TIB->all_uses()) {
2038 if (!MO.isKill())
2039 continue;
2040 Register Reg = MO.getReg();
2041 if (!Reg)
2042 continue;
2043 if (!AllDefsSet.count(V: Reg)) {
2044 continue;
2045 }
2046 if (Reg.isPhysical()) {
2047 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
2048 ActiveDefsSet.erase(V: *AI);
2049 } else {
2050 ActiveDefsSet.erase(V: Reg);
2051 }
2052 }
2053
2054 // Track local defs so we can update liveins.
2055 for (const MachineOperand &MO : TIB->all_defs()) {
2056 if (MO.isDead())
2057 continue;
2058 Register Reg = MO.getReg();
2059 if (!Reg || Reg.isVirtual())
2060 continue;
2061 addRegAndItsAliases(Reg, TRI, Set&: ActiveDefsSet);
2062 addRegAndItsAliases(Reg, TRI, Set&: AllDefsSet);
2063 }
2064
2065 HasDups = true;
2066 ++TIB;
2067 ++FIB;
2068 }
2069
2070 if (!HasDups)
2071 return false;
2072
2073 // Hoist the instructions from [T.begin, TIB) and then delete [F.begin, FIB).
2074 // If we're hoisting from a single block then just splice. Else step through
2075 // and merge the debug locations.
2076 if (TBB == FBB) {
2077 MBB->splice(Where: Loc, Other: TBB, From: TBB->begin(), To: TIB);
2078 } else {
2079 // TIB and FIB point to the end of the regions to hoist/merge in TBB and
2080 // FBB.
2081 MachineBasicBlock::iterator FE = FIB;
2082 MachineBasicBlock::iterator FI = FBB->begin();
2083 for (MachineBasicBlock::iterator TI :
2084 make_early_inc_range(Range: make_range(x: TBB->begin(), y: TIB))) {
2085 // Move debug instructions and pseudo probes without modifying them.
2086 // FIXME: This is the wrong thing to do for debug locations, which
2087 // should at least be killed (and hoisted from BOTH blocks).
2088 if (TI->isDebugOrPseudoInstr()) {
2089 TI->moveBefore(MovePos: &*Loc);
2090 continue;
2091 }
2092
2093 // Get the next non-meta instruction in FBB.
2094 FI = skipDebugInstructionsForward(It: FI, End: FE, SkipPseudoOp: false);
2095 // NOTE: The loop above checks CheckKillDead but we can't do that here as
2096 // it modifies some kill markers after the check.
2097 assert(TI->isIdenticalTo(*FI, MachineInstr::CheckDefs) &&
2098 "Expected non-debug lockstep");
2099
2100 // Merge debug locs on hoisted instructions.
2101 TI->setDebugLoc(
2102 DILocation::getMergedLocation(LocA: TI->getDebugLoc(), LocB: FI->getDebugLoc()));
2103 TI->moveBefore(MovePos: &*Loc);
2104 ++FI;
2105 }
2106 }
2107 FBB->erase(I: FBB->begin(), E: FIB);
2108
2109 if (UpdateLiveIns)
2110 fullyRecomputeLiveIns(MBBs: {TBB, FBB});
2111
2112 ++NumHoist;
2113 return true;
2114}
2115

Provided by KDAB

Privacy Policy
Learn to use CMake with our Intro Training
Find out more

source code of llvm/lib/CodeGen/BranchFolding.cpp