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