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