LLVM 24.0.0git
BranchRelaxation.cpp
Go to the documentation of this file.
1//===- BranchRelaxation.cpp -----------------------------------------------===//
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
11#include "llvm/ADT/Statistic.h"
22#include "llvm/Config/llvm-config.h"
23#include "llvm/IR/DebugLoc.h"
25#include "llvm/Pass.h"
27#include "llvm/Support/Debug.h"
29#include "llvm/Support/Format.h"
32#include <cassert>
33#include <cstdint>
34#include <iterator>
35#include <memory>
36
37using namespace llvm;
38
39#define DEBUG_TYPE "branch-relaxation"
40
41STATISTIC(NumSplit, "Number of basic blocks split");
42STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
43STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
44
45#define BRANCH_RELAX_NAME "Branch relaxation pass"
46
47namespace {
48
49class BranchRelaxation {
50 /// BasicBlockInfo - Information about the offset and size of a single
51 /// basic block.
52 struct BasicBlockInfo {
53 /// Offset - Distance from the beginning of the function to the beginning
54 /// of this basic block.
55 ///
56 /// The offset is always aligned as required by the basic block.
57 unsigned Offset = 0;
58
59 /// Size - Size of the basic block in bytes. If the block contains
60 /// inline assembly, this is a worst case estimate.
61 ///
62 /// The size does not include any alignment padding whether from the
63 /// beginning of the block, or from an aligned jump table at the end.
64 unsigned Size = 0;
65
66 BasicBlockInfo() = default;
67
68 /// Compute the offset immediately following this block. \p MBB is the next
69 /// block.
70 unsigned postOffset(const MachineBasicBlock &MBB) const {
71 const unsigned PO = Offset + Size;
72 const Align Alignment = MBB.getAlignment();
73 const Align ParentAlign = MBB.getParent()->getAlignment();
74 if (Alignment <= ParentAlign)
75 return alignTo(PO, Alignment);
76
77 // The alignment of this MBB is larger than the function's alignment, so
78 // we can't tell whether or not it will insert nops. Assume that it will.
79 return alignTo(PO, Alignment) + Alignment.value() - ParentAlign.value();
80 }
81 };
82
84
85 // The basic block after which trampolines are inserted. This is the last
86 // basic block that isn't in the cold section.
87 MachineBasicBlock *TrampolineInsertionPoint = nullptr;
89 RelaxedUnconditionals;
90 std::unique_ptr<RegScavenger> RS;
92
93 MachineFunction *MF = nullptr;
94 const TargetRegisterInfo *TRI = nullptr;
95 const TargetInstrInfo *TII = nullptr;
96 const TargetMachine *TM = nullptr;
97
98 bool relaxBranchInstructions();
99 void scanFunction();
100
101 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &OrigMBB);
102 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &OrigMBB,
103 const BasicBlock *BB);
104
105 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
106 MachineBasicBlock *DestBB);
107 void adjustBlockOffsets(MachineBasicBlock &Start);
108 // Computes basic block offsets for blocks in the range (Start, End),
109 // i.e. beginning with the block immediately following Start.
110 void adjustBlockOffsets(MachineBasicBlock &Start,
112 bool isBlockInRange(const MachineInstr &MI,
113 const MachineBasicBlock &BB) const;
114
115 bool fixupConditionalBranch(MachineInstr &MI);
116 bool fixupUnconditionalBranch(MachineInstr &MI);
117 uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
118 unsigned getInstrOffset(const MachineInstr &MI) const;
119 void dumpBBs();
120 void verify();
121
122public:
123 bool run(MachineFunction &MF);
124};
125
126class BranchRelaxationLegacy : public MachineFunctionPass {
127public:
128 static char ID;
129
130 BranchRelaxationLegacy() : MachineFunctionPass(ID) {}
131
132 bool runOnMachineFunction(MachineFunction &MF) override {
133 return BranchRelaxation().run(MF);
134 }
135
136 StringRef getPassName() const override { return BRANCH_RELAX_NAME; }
137};
138
139} // end anonymous namespace
140
141char BranchRelaxationLegacy::ID = 0;
142
143char &llvm::BranchRelaxationPassID = BranchRelaxationLegacy::ID;
144
145INITIALIZE_PASS(BranchRelaxationLegacy, DEBUG_TYPE, BRANCH_RELAX_NAME, false,
146 false)
147
148/// verify - check BBOffsets, BBSizes, alignment of islands
149void BranchRelaxation::verify() {
150#ifndef NDEBUG
151 unsigned PrevNum = MF->begin()->getNumber();
152 for (MachineBasicBlock &MBB : *MF) {
153 const unsigned Num = MBB.getNumber();
154 assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
155 assert(BlockInfo[Num].Size == computeBlockSize(MBB));
156 PrevNum = Num;
157 }
158
159 for (MachineBasicBlock &MBB : *MF) {
160 for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
161 J != MBB.end(); J = std::next(J)) {
162 MachineInstr &MI = *J;
163 if (!MI.isConditionalBranch() && !MI.isUnconditionalBranch())
164 continue;
165 if (MI.getOpcode() == TargetOpcode::FAULTING_OP)
166 continue;
167 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
168 assert(isBlockInRange(MI, *DestBB) ||
169 RelaxedUnconditionals.contains({&MBB, DestBB}));
170 }
171 }
172#endif
173}
174
175#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
176/// print block size and offset information - debugging
177LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {
178 for (auto &MBB : *MF) {
179 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
180 dbgs() << format("%%bb.%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
181 << format("size=%#x\n", BBI.Size);
182 }
183}
184#endif
185
186/// scanFunction - Do the initial scan of the function, building up
187/// information about each block.
188void BranchRelaxation::scanFunction() {
189 BlockInfo.clear();
190 BlockInfo.resize(MF->getNumBlockIDs());
191
192 TrampolineInsertionPoint = nullptr;
193 RelaxedUnconditionals.clear();
194
195 // First thing, compute the size of all basic blocks, and see if the function
196 // has any inline assembly in it. If so, we have to be conservative about
197 // alignment assumptions, as we don't know for sure the size of any
198 // instructions in the inline assembly. At the same time, place the
199 // trampoline insertion point at the end of the hot portion of the function.
200 for (MachineBasicBlock &MBB : *MF) {
201 BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
202
204 TrampolineInsertionPoint = &MBB;
205 }
206
207 // Compute block offsets and known bits.
208 adjustBlockOffsets(*MF->begin());
209
210 if (TrampolineInsertionPoint == nullptr) {
211 LLVM_DEBUG(dbgs() << " No suitable trampoline insertion point found in "
212 << MF->getName() << ".\n");
213 }
214}
215
216/// computeBlockSize - Compute the size for MBB.
218BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
219 uint64_t Size = 0;
220 for (const MachineInstr &MI : MBB)
221 Size += TII->getInstSizeInBytes(MI);
222 return Size;
223}
224
225/// getInstrOffset - Return the current offset of the specified machine
226/// instruction from the start of the function. This offset changes as stuff is
227/// moved around inside the function.
228unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
229 const MachineBasicBlock *MBB = MI.getParent();
230
231 // The offset is composed of two things: the sum of the sizes of all MBB's
232 // before this instruction's block, and the offset from the start of the block
233 // it is in.
234 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
235
236 // Sum instructions before MI in MBB.
237 for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
238 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
239 Offset += TII->getInstSizeInBytes(*I);
240 }
241
242 return Offset;
243}
244
245void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
246 adjustBlockOffsets(Start, MF->end());
247}
248
249void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start,
251 unsigned PrevNum = Start.getNumber();
252 for (auto &MBB :
253 make_range(std::next(MachineFunction::iterator(Start)), End)) {
254 unsigned Num = MBB.getNumber();
255 // Get the offset and known bits at the end of the layout predecessor.
256 // Include the alignment of the current block.
257 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
258
259 PrevNum = Num;
260 }
261}
262
263/// Insert a new empty MachineBasicBlock and insert it after \p OrigMBB
264MachineBasicBlock *
265BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigBB) {
266 return createNewBlockAfter(OrigBB, OrigBB.getBasicBlock());
267}
268
269/// Insert a new empty MachineBasicBlock with \p BB as its BasicBlock
270/// and insert it after \p OrigMBB
271MachineBasicBlock *
272BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigMBB,
273 const BasicBlock *BB) {
274 // Create a new MBB for the code after the OrigBB.
275 MachineBasicBlock *NewBB = MF->CreateMachineBasicBlock(BB);
276 MF->insert(++OrigMBB.getIterator(), NewBB);
277
278 // Place the new block in the same section as OrigBB
279 NewBB->setSectionID(OrigMBB.getSectionID());
280 NewBB->setIsEndSection(OrigMBB.isEndSection());
281 OrigMBB.setIsEndSection(false);
282
283 // Insert an entry into BlockInfo to align it properly with the block numbers.
284 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
285
286 // Keep the block offsets approximately up to date. While they will be
287 // slight underestimates, we will update them appropriately in the next
288 // scan through the function.
289 adjustBlockOffsets(OrigMBB, std::next(NewBB->getIterator()));
290
291 return NewBB;
292}
293
294/// Split the basic block containing MI into two blocks, which are joined by
295/// an unconditional branch. Update data structures and renumber blocks to
296/// account for this change and returns the newly created block.
297MachineBasicBlock *
298BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
299 MachineBasicBlock *DestBB) {
300 MachineBasicBlock *OrigBB = MI.getParent();
301
302 // Create a new MBB for the code after the OrigBB.
303 MachineBasicBlock *NewBB =
304 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
305 MF->insert(++OrigBB->getIterator(), NewBB);
306
307 // Place the new block in the same section as OrigBB.
308 NewBB->setSectionID(OrigBB->getSectionID());
309 NewBB->setIsEndSection(OrigBB->isEndSection());
310 OrigBB->setIsEndSection(false);
311
312 // Splice the instructions starting with MI over to NewBB.
313 NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
314
315 // Add an unconditional branch from OrigBB to NewBB.
316 // Note the new unconditional branch is not being recorded.
317 // There doesn't seem to be meaningful DebugInfo available; this doesn't
318 // correspond to anything in the source.
319 TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
320
321 // Insert an entry into BlockInfo to align it properly with the block numbers.
322 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
323
324 NewBB->transferSuccessors(OrigBB);
325 OrigBB->addSuccessor(NewBB);
326 OrigBB->addSuccessor(DestBB);
327
328 // Cleanup potential unconditional branch to successor block.
329 // Note that updateTerminator may change the size of the blocks.
330 OrigBB->updateTerminator(NewBB);
331
332 // Figure out how large the OrigBB is. As the first half of the original
333 // block, it cannot contain a tablejump. The size includes
334 // the new jump we added. (It should be possible to do this without
335 // recounting everything, but it's very confusing, and this is rarely
336 // executed.)
337 BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
338
339 // Figure out how large the NewMBB is. As the second half of the original
340 // block, it may contain a tablejump.
341 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
342
343 // Update the offset of the new block.
344 adjustBlockOffsets(*OrigBB, std::next(NewBB->getIterator()));
345
346 // Need to fix live-in lists if we track liveness.
347 if (TRI->trackLivenessAfterRegAlloc(*MF))
348 computeAndAddLiveIns(LiveRegs, *NewBB);
349
350 ++NumSplit;
351
352 return NewBB;
353}
354
355/// isBlockInRange - Returns true if the distance between specific MI and
356/// specific BB can fit in MI's displacement field.
357bool BranchRelaxation::isBlockInRange(const MachineInstr &MI,
358 const MachineBasicBlock &DestBB) const {
359 int64_t BrOffset = getInstrOffset(MI);
360 int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
361
362 const MachineBasicBlock *SrcBB = MI.getParent();
363
364 if (TII->isBranchOffsetInRange(MI.getOpcode(),
365 SrcBB->getSectionID() != DestBB.getSectionID()
366 ? TM->getMaxCodeSize()
367 : DestOffset - BrOffset))
368 return true;
369
370 LLVM_DEBUG(dbgs() << "Out of range branch to destination "
371 << printMBBReference(DestBB) << " from "
372 << printMBBReference(*MI.getParent()) << " to "
373 << DestOffset << " offset " << DestOffset - BrOffset << '\t'
374 << MI);
375
376 return false;
377}
378
379/// fixupConditionalBranch - Fix up a conditional branch whose destination is
380/// too far away to fit in its displacement field. It is converted to an inverse
381/// conditional branch + an unconditional branch to the destination.
382bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
383 DebugLoc DL = MI.getDebugLoc();
384 MachineBasicBlock *MBB = MI.getParent();
385 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
386 MachineBasicBlock *NewBB = nullptr;
388
389 auto insertUncondBranch = [&](MachineBasicBlock *MBB,
390 MachineBasicBlock *DestBB) {
391 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
392 int NewBrSize = 0;
393 TII->insertUnconditionalBranch(*MBB, DestBB, DL, &NewBrSize);
394 BBSize += NewBrSize;
395 };
396 auto insertBranch = [&](MachineBasicBlock *MBB, MachineBasicBlock *TBB,
397 MachineBasicBlock *FBB,
398 SmallVectorImpl<MachineOperand> &Cond) {
399 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
400 int NewBrSize = 0;
401 TII->insertBranch(*MBB, TBB, FBB, Cond, DL, &NewBrSize);
402 BBSize += NewBrSize;
403 };
404 auto removeBranch = [&](MachineBasicBlock *MBB) {
405 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
406 int RemovedSize = 0;
407 TII->removeBranch(*MBB, &RemovedSize);
408 BBSize -= RemovedSize;
409 };
410
411 // Populate the block offset and live-ins for a new basic block.
412 auto updateLiveness = [&](MachineBasicBlock *NewBB) {
413 assert(NewBB != nullptr && "can't update liveness for nullptr");
414
415 // Need to fix live-in lists if we track liveness.
416 if (TRI->trackLivenessAfterRegAlloc(*MF))
417 computeAndAddLiveIns(LiveRegs, *NewBB);
418 };
419
420 bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
421 assert(!Fail && "branches to be relaxed must be analyzable");
422 (void)Fail;
423
424 // Since cross-section conditional branches to the cold section are rarely
425 // taken, try to avoid inverting the condition. Instead, add a "trampoline
426 // branch", which unconditionally branches to the branch destination. Place
427 // the trampoline branch at the end of the function and retarget the
428 // conditional branch to the trampoline.
429 // tbz L1
430 // =>
431 // tbz L1Trampoline
432 // ...
433 // L1Trampoline: b L1
434 if (MBB->getSectionID() != TBB->getSectionID() &&
436 TrampolineInsertionPoint != nullptr) {
437 // If the insertion point is out of range, we can't put a trampoline there.
438 NewBB =
439 createNewBlockAfter(*TrampolineInsertionPoint, MBB->getBasicBlock());
440
441 if (isBlockInRange(MI, *NewBB)) {
442 LLVM_DEBUG(dbgs() << " Retarget destination to trampoline at "
443 << NewBB->back());
444
445 insertUncondBranch(NewBB, TBB);
446
447 // Update the successor lists to include the trampoline.
448 MBB->replaceSuccessor(TBB, NewBB);
449 NewBB->addSuccessor(TBB);
450
451 // Replace branch in the current (MBB) block.
452 removeBranch(MBB);
453 insertBranch(MBB, NewBB, FBB, Cond);
454
455 TrampolineInsertionPoint = NewBB;
456 updateLiveness(NewBB);
457 return true;
458 }
459
461 dbgs() << " Trampoline insertion point out of range for Bcc from "
462 << printMBBReference(*MBB) << " to " << printMBBReference(*TBB)
463 << ".\n");
464 TrampolineInsertionPoint->setIsEndSection(NewBB->isEndSection());
465 MF->erase(NewBB);
466 NewBB = nullptr;
467 }
468
469 // Add an unconditional branch to the destination and invert the branch
470 // condition to jump over it:
471 // tbz L1
472 // =>
473 // tbnz L2
474 // b L1
475 // L2:
476
477 bool ReversedCond = !TII->reverseBranchCondition(Cond);
478 if (ReversedCond) {
479 if (FBB && isBlockInRange(MI, *FBB)) {
480 // Last MI in the BB is an unconditional branch. We can simply invert the
481 // condition and swap destinations:
482 // beq L1
483 // b L2
484 // =>
485 // bne L2
486 // b L1
487 LLVM_DEBUG(dbgs() << " Invert condition and swap "
488 "its destination with "
489 << MBB->back());
490
491 removeBranch(MBB);
492 insertBranch(MBB, FBB, TBB, Cond);
493 return true;
494 }
495 if (FBB) {
496 // If we get here with a MBB which ends like this:
497 //
498 // bb.1:
499 // successors: %bb.2;
500 // ...
501 // BNE $x1, $x0, %bb.2
502 // PseudoBR %bb.2
503 //
504 // Just remove conditional branch.
505 if (TBB == FBB) {
506 removeBranch(MBB);
507 insertUncondBranch(MBB, TBB);
508 return true;
509 }
510 // We need to split the basic block here to obtain two long-range
511 // unconditional branches.
512 NewBB = createNewBlockAfter(*MBB);
513
514 insertUncondBranch(NewBB, FBB);
515 // Update the succesor lists according to the transformation to follow.
516 // Do it here since if there's no split, no update is needed.
517 MBB->replaceSuccessor(FBB, NewBB);
518 NewBB->addSuccessor(FBB);
519 updateLiveness(NewBB);
520 }
521
522 // We now have an appropriate fall-through block in place (either naturally
523 // or just created), so we can use the inverted the condition.
524 MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
525
526 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*TBB)
527 << ", invert condition and change dest. to "
528 << printMBBReference(NextBB) << '\n');
529
530 removeBranch(MBB);
531 // Insert a new conditional branch and a new unconditional branch.
532 insertBranch(MBB, &NextBB, TBB, Cond);
533 return true;
534 }
535 // Branch cond can't be inverted.
536 // In this case we always add a block after the MBB.
537 LLVM_DEBUG(dbgs() << " The branch condition can't be inverted. "
538 << " Insert a new BB after " << MBB->back());
539
540 if (!FBB)
541 FBB = &(*std::next(MachineFunction::iterator(MBB)));
542
543 // This is the block with cond. branch and the distance to TBB is too long.
544 // beq L1
545 // L2:
546
547 // We do the following transformation:
548 // beq NewBB
549 // b L2
550 // NewBB:
551 // b L1
552 // L2:
553
554 NewBB = createNewBlockAfter(*MBB);
555 insertUncondBranch(NewBB, TBB);
556
557 LLVM_DEBUG(dbgs() << " Insert cond B to the new BB "
558 << printMBBReference(*NewBB)
559 << " Keep the exiting condition.\n"
560 << " Insert B to " << printMBBReference(*FBB) << ".\n"
561 << " In the new BB: Insert B to "
562 << printMBBReference(*TBB) << ".\n");
563
564 // Update the successor lists according to the transformation to follow.
565 MBB->replaceSuccessor(TBB, NewBB);
566 NewBB->addSuccessor(TBB);
567
568 // Replace branch in the current (MBB) block.
569 removeBranch(MBB);
570 insertBranch(MBB, NewBB, FBB, Cond);
571
572 updateLiveness(NewBB);
573 return true;
574}
575
576bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
577 MachineBasicBlock *MBB = MI.getParent();
578 unsigned OldBrSize = TII->getInstSizeInBytes(MI);
579 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
580
581 int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
582 int64_t SrcOffset = getInstrOffset(MI);
583
584 assert(!TII->isBranchOffsetInRange(
585 MI.getOpcode(), MBB->getSectionID() != DestBB->getSectionID()
586 ? TM->getMaxCodeSize()
587 : DestOffset - SrcOffset));
588
589 BlockInfo[MBB->getNumber()].Size -= OldBrSize;
590
591 MachineBasicBlock *BranchBB = MBB;
592
593 // If this was an expanded conditional branch, there is already a single
594 // unconditional branch in a block.
595 if (!MBB->empty()) {
596 BranchBB = createNewBlockAfter(*MBB);
597
598 // Add live outs.
599 for (const MachineBasicBlock *Succ : MBB->successors()) {
600 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
601 BranchBB->addLiveIn(LiveIn);
602 }
603
604 BranchBB->sortUniqueLiveIns();
605 BranchBB->addSuccessor(DestBB);
606 MBB->replaceSuccessor(DestBB, BranchBB);
607 if (TrampolineInsertionPoint == MBB)
608 TrampolineInsertionPoint = BranchBB;
609 }
610
611 DebugLoc DL = MI.getDebugLoc();
613
614 // Create the optional restore block and, initially, place it at the end of
615 // function. That block will be placed later if it's used; otherwise, it will
616 // be erased.
617 MachineBasicBlock *RestoreBB =
618 createNewBlockAfter(MF->back(), DestBB->getBasicBlock());
619 std::prev(RestoreBB->getIterator())
620 ->setIsEndSection(RestoreBB->isEndSection());
621 RestoreBB->setIsEndSection(false);
622
623 TII->insertIndirectBranch(*BranchBB, *DestBB, *RestoreBB, DL,
624 BranchBB->getSectionID() != DestBB->getSectionID()
625 ? TM->getMaxCodeSize()
626 : DestOffset - SrcOffset,
627 RS.get());
628
629 // Update the block size and offset for the BranchBB (which may be newly
630 // created).
631 BlockInfo[BranchBB->getNumber()].Size = computeBlockSize(*BranchBB);
632 adjustBlockOffsets(*MBB, std::next(BranchBB->getIterator()));
633
634 // If RestoreBB is required, place it appropriately.
635 if (!RestoreBB->empty()) {
636 // If the jump is Cold -> Hot, don't place the restore block (which is
637 // cold) in the middle of the function. Place it at the end.
640 MachineBasicBlock *NewBB = createNewBlockAfter(*TrampolineInsertionPoint);
641 TII->insertUnconditionalBranch(*NewBB, DestBB, DebugLoc());
642 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
643 adjustBlockOffsets(*TrampolineInsertionPoint,
644 std::next(NewBB->getIterator()));
645
646 // New trampolines should be inserted after NewBB.
647 TrampolineInsertionPoint = NewBB;
648
649 // Retarget the unconditional branch to the trampoline block.
650 BranchBB->replaceSuccessor(DestBB, NewBB);
651 NewBB->addSuccessor(DestBB);
652
653 DestBB = NewBB;
654 }
655
656 // In all other cases, try to place just before DestBB.
657
658 // TODO: For multiple far branches to the same destination, there are
659 // chances that some restore blocks could be shared if they clobber the
660 // same registers and share the same restore sequence. So far, those
661 // restore blocks are just duplicated for each far branch.
662 assert(!DestBB->isEntryBlock());
663 MachineBasicBlock *PrevBB = &*std::prev(DestBB->getIterator());
664 // Fall through only if PrevBB has no unconditional branch as one of its
665 // terminators.
666 if (auto *FT = PrevBB->getLogicalFallThrough()) {
667 assert(FT == DestBB);
668 TII->insertUnconditionalBranch(*PrevBB, FT, DebugLoc());
669 BlockInfo[PrevBB->getNumber()].Size = computeBlockSize(*PrevBB);
670 }
671 // Now, RestoreBB could be placed directly before DestBB.
672 MF->splice(DestBB->getIterator(), RestoreBB->getIterator());
673 // Update successors and predecessors.
674 RestoreBB->addSuccessor(DestBB);
675 BranchBB->replaceSuccessor(DestBB, RestoreBB);
676 if (TRI->trackLivenessAfterRegAlloc(*MF))
677 computeAndAddLiveIns(LiveRegs, *RestoreBB);
678 // Compute the restore block size.
679 BlockInfo[RestoreBB->getNumber()].Size = computeBlockSize(*RestoreBB);
680 // Update the estimated offset for the restore block.
681 adjustBlockOffsets(*PrevBB, DestBB->getIterator());
682
683 // Fix up section information for RestoreBB and DestBB
684 RestoreBB->setSectionID(DestBB->getSectionID());
685 RestoreBB->setIsBeginSection(DestBB->isBeginSection());
686 DestBB->setIsBeginSection(false);
687 RelaxedUnconditionals.insert({BranchBB, RestoreBB});
688 } else {
689 // Remove restore block if it's not required.
690 MF->erase(RestoreBB);
691 RelaxedUnconditionals.insert({BranchBB, DestBB});
692 }
693
694 return true;
695}
696
697bool BranchRelaxation::relaxBranchInstructions() {
698 bool Changed = false;
699
700 // Relaxing branches involves creating new basic blocks, so re-eval
701 // end() for termination.
702 for (MachineBasicBlock &MBB : *MF) {
703 // Empty block?
705 if (Last == MBB.end())
706 continue;
707
708 // Expand the unconditional branch first if necessary. If there is a
709 // conditional branch, this will end up changing the branch destination of
710 // it to be over the newly inserted indirect branch block, which may avoid
711 // the need to try expanding the conditional branch first, saving an extra
712 // jump.
713 if (Last->isUnconditionalBranch()) {
714 // Unconditional branch destination might be unanalyzable, assume these
715 // are OK.
716 if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
717 if (!isBlockInRange(*Last, *DestBB) && !TII->isTailCall(*Last) &&
718 !RelaxedUnconditionals.contains({&MBB, DestBB})) {
719 fixupUnconditionalBranch(*Last);
720 ++NumUnconditionalRelaxed;
721 Changed = true;
722 }
723 }
724 }
725
726 // Loop over the conditional branches.
729 J != MBB.end(); J = Next) {
730 Next = std::next(J);
731 MachineInstr &MI = *J;
732
733 if (!MI.isConditionalBranch())
734 continue;
735
736 if (MI.getOpcode() == TargetOpcode::FAULTING_OP)
737 // FAULTING_OP's destination is not encoded in the instruction stream
738 // and thus never needs relaxed.
739 continue;
740
741 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
742 if (!isBlockInRange(MI, *DestBB)) {
743 if (Next != MBB.end() && Next->isConditionalBranch()) {
744 // If there are multiple conditional branches, this isn't an
745 // analyzable block. Split later terminators into a new block so
746 // each one will be analyzable.
747
748 splitBlockBeforeInstr(*Next, DestBB);
749 } else {
750 fixupConditionalBranch(MI);
751 ++NumConditionalRelaxed;
752 }
753
754 Changed = true;
755
756 // This may have modified all of the terminators, so start over.
758 }
759 }
760 }
761
762 // If we relaxed a branch, we must recompute offsets for *all* basic blocks.
763 // Otherwise, we may underestimate branch distances and fail to relax a branch
764 // that has been pushed out of range.
765 if (Changed)
766 adjustBlockOffsets(MF->front());
767
768 return Changed;
769}
770
771PreservedAnalyses
778
779bool BranchRelaxation::run(MachineFunction &mf) {
780 MF = &mf;
781
782 LLVM_DEBUG(dbgs() << "***** BranchRelaxation *****\n");
783
784 const TargetSubtargetInfo &ST = MF->getSubtarget();
785 TII = ST.getInstrInfo();
786 TM = &MF->getTarget();
787
788 TRI = ST.getRegisterInfo();
789 if (TRI->trackLivenessAfterRegAlloc(*MF))
790 RS.reset(new RegScavenger());
791
792 // Renumber all of the machine basic blocks in the function, guaranteeing that
793 // the numbers agree with the position of the block in the function.
794 MF->RenumberBlocks();
795
796 // Do the initial scan of the function, building up information about the
797 // sizes of each block.
798 scanFunction();
799
800 LLVM_DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
801
802 bool MadeChange = false;
803 while (relaxBranchInstructions())
804 MadeChange = true;
805
806 // After a while, this might be made debug-only, but it is not expensive.
807 verify();
808
809 LLVM_DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
810
811 BlockInfo.clear();
812 RelaxedUnconditionals.clear();
813
814 return MadeChange;
815}
#define Fail
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static cl::opt< bool > BranchRelaxation("aarch64-enable-branch-relax", cl::Hidden, cl::init(true), cl::desc("Relax out of range conditional branches"))
unsigned uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define BRANCH_RELAX_NAME
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
ppc ctr loops verify
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
This file declares the machine register scavenger class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
Remove the branching code at the end of the specific MBB.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
Insert branch code into the end of the specified MachineBasicBlock.
bool isTailCall(const MachineInstr &MI) const override
A set of physical registers with utility functions to track liveness when walking backward/forward th...
void setIsEndSection(bool V=true)
MachineInstrBundleIterator< const MachineInstr > const_iterator
MachineBasicBlock * getLogicalFallThrough()
Return the fallthrough block if the block can implicitly transfer control to it's successor,...
LLVM_ABI void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
LLVM_ABI void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor)
Update the terminator instructions in block to account for changes to block layout which may have bee...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
LLVM_ABI bool isEntryBlock() const
Returns true if this is the entry block of the function.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
void setSectionID(MBBSectionID V)
Sets the section ID for this basic block.
LLVM_ABI iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
bool isBeginSection() const
Returns true if this block begins any section.
iterator_range< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
bool isEndSection() const
Returns true if this block ends any section.
MachineInstrBundleIterator< MachineInstr > iterator
void setIsBeginSection(bool V=true)
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
BasicBlockListType::iterator iterator
Representation of each machine instruction.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
Primary interface to the complete machine description for the target machine.
uint64_t getMaxCodeSize() const
Returns the maximum code size possible under the code model.
const Target & getTarget() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
self_iterator getIterator()
Definition ilist_node.h:123
Changed
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI char & BranchRelaxationPassID
BranchRelaxation - This pass replaces branches that need to jump further than is supported by a branc...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
LLVM_ABI void computeAndAddLiveIns(LivePhysRegs &LiveRegs, MachineBasicBlock &MBB)
Convenience function combining computeLiveIns() and addLiveIns().
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
BasicBlockInfo - Information about the offset and size of a single basic block.
unsigned Size
Size - Size of the basic block in bytes.
unsigned Offset
Offset - Distance from the beginning of the function to the beginning of this basic block.
LLVM_ABI static const MBBSectionID ColdSectionID