LLVM 24.0.0git
MipsBranchExpansion.cpp
Go to the documentation of this file.
1//===----------------------- MipsBranchExpansion.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/// \file
9///
10/// This pass do two things:
11/// - it expands a branch or jump instruction into a long branch if its offset
12/// is too large to fit into its immediate field,
13/// - it inserts nops to prevent forbidden slot hazards.
14///
15/// The reason why this pass combines these two tasks is that one of these two
16/// tasks can break the result of the previous one.
17///
18/// Example of that is a situation where at first, no branch should be expanded,
19/// but after adding at least one nop somewhere in the code to prevent a
20/// forbidden slot hazard, offset of some branches may go out of range. In that
21/// case it is necessary to check again if there is some branch that needs
22/// expansion. On the other hand, expanding some branch may cause a control
23/// transfer instruction to appear in the forbidden slot, which is a hazard that
24/// should be fixed. This pass alternates between this two tasks untill no
25/// changes are made. Only then we can be sure that all branches are expanded
26/// properly, and no hazard situations exist.
27///
28/// Regarding branch expanding:
29///
30/// When branch instruction like beqzc or bnezc has offset that is too large
31/// to fit into its immediate field, it has to be expanded to another
32/// instruction or series of instructions.
33///
34/// FIXME: Fix pc-region jump instructions which cross 256MB segment boundaries.
35/// TODO: Handle out of range bc, b (pseudo) instructions.
36///
37/// Regarding compact branch hazard prevention:
38///
39/// Hazards handled: forbidden slots for MIPSR6, FPU slots for MIPS3 and below,
40/// load delay slots for MIPS1.
41///
42/// A forbidden slot hazard occurs when a compact branch instruction is executed
43/// and the adjacent instruction in memory is a control transfer instruction
44/// such as a branch or jump, ERET, ERETNC, DERET, WAIT and PAUSE.
45///
46/// For example:
47///
48/// 0x8004 bnec a1,v0,<P+0x18>
49/// 0x8008 beqc a1,a2,<P+0x54>
50///
51/// In such cases, the processor is required to signal a Reserved Instruction
52/// exception.
53///
54/// Here, if the instruction at 0x8004 is executed, the processor will raise an
55/// exception as there is a control transfer instruction at 0x8008.
56///
57/// There are two sources of forbidden slot hazards:
58///
59/// A) A previous pass has created a compact branch directly.
60/// B) Transforming a delay slot branch into compact branch. This case can be
61/// difficult to process as lookahead for hazards is insufficient, as
62/// backwards delay slot fillling can also produce hazards in previously
63/// processed instructions.
64///
65/// In future this pass can be extended (or new pass can be created) to handle
66/// other pipeline hazards, such as various MIPS1 hazards, processor errata that
67/// require instruction reorganization, etc.
68///
69/// This pass has to run after the delay slot filler as that pass can introduce
70/// pipeline hazards such as compact branch hazard, hence the existing hazard
71/// recognizer is not suitable.
72///
73//===----------------------------------------------------------------------===//
74
78#include "Mips.h"
79#include "MipsInstrInfo.h"
80#include "MipsMachineFunction.h"
81#include "MipsSubtarget.h"
83#include "llvm/ADT/Statistic.h"
84#include "llvm/ADT/StringRef.h"
95#include "llvm/IR/Analysis.h"
96#include "llvm/IR/DebugLoc.h"
99#include <algorithm>
100#include <cassert>
101#include <cstdint>
102#include <iterator>
103#include <utility>
104
105using namespace llvm;
106
107#define DEBUG_TYPE "mips-branch-expansion"
108
109STATISTIC(NumInsertedNops, "Number of nops inserted");
110STATISTIC(LongBranches, "Number of long branches.");
111
112namespace {
113
114using Iter = MachineBasicBlock::iterator;
115using ReverseIter = MachineBasicBlock::reverse_iterator;
116
117struct MBBInfo {
118 uint64_t Size = 0;
119 bool HasLongBranch = false;
120 MachineInstr *Br = nullptr;
121 uint64_t Offset = 0;
122 MBBInfo() = default;
123};
124
125class MipsBranchExpansionLegacy : public MachineFunctionPass {
126public:
127 static char ID;
128
129 MipsBranchExpansionLegacy() : MachineFunctionPass(ID) {}
130
131 StringRef getPassName() const override {
132 return "Mips Branch Expansion Pass";
133 }
134
135 bool runOnMachineFunction(MachineFunction &F) override;
136
137 MachineFunctionProperties getRequiredProperties() const override {
138 return MachineFunctionProperties().setNoVRegs();
139 }
140};
141
142class MipsBranchExpansionImpl {
143 void splitMBB(MachineBasicBlock *MBB);
144 void initMBBInfo();
145 int64_t computeOffset(const MachineInstr *Br);
146 uint64_t computeOffsetFromTheBeginning(int MBB);
147 void replaceBranch(MachineBasicBlock &MBB, Iter Br, const DebugLoc &DL,
148 MachineBasicBlock *MBBOpnd);
149 bool buildProperJumpMI(MachineBasicBlock *MBB,
151 void expandToLongBranch(MBBInfo &Info);
152 template <typename Pred, typename Safe>
153 bool handleSlot(Pred Predicate, Safe SafeInSlot);
154 bool handleForbiddenSlot();
155 bool handleFPUDelaySlot();
156 bool handleLoadDelaySlot();
157 bool handlePossibleLongBranch();
158 bool handleMFLO();
159 unsigned distanceToHILOWrite(MachineBasicBlock &MBB,
161 unsigned Dist);
162
163 const MipsSubtarget *STI;
164 const MipsInstrInfo *TII;
165
166 MachineFunction *MFp;
168 bool IsPIC;
169 MipsABIInfo ABI = MipsABIInfo::Unknown();
170 bool ForceLongBranchFirstPass = false;
171
172public:
173 bool runOnMachineFunction(MachineFunction &MF);
174};
175
176} // end of anonymous namespace
177
178char MipsBranchExpansionLegacy::ID = 0;
179
180INITIALIZE_PASS(MipsBranchExpansionLegacy, DEBUG_TYPE,
181 "Expand out of range branch instructions and fix forbidden"
182 " slot hazards",
183 false, false)
184
185/// Returns a pass that clears pipeline hazards.
187 return new MipsBranchExpansionLegacy();
188}
189
190// Find the next real instruction from the current position in current basic
191// block.
192static Iter getNextMachineInstrInBB(Iter Position) {
193 Iter I = Position, E = Position->getParent()->end();
194 I = std::find_if_not(I, E,
195 [](const Iter &Insn) { return Insn->isTransient(); });
196
197 return I;
198}
199
200// Find the next real instruction from the current position, looking through
201// basic block boundaries.
202static std::pair<Iter, bool> getNextMachineInstr(Iter Position,
203 MachineBasicBlock *Parent) {
204 if (Position == Parent->end()) {
205 do {
206 MachineBasicBlock *Succ = Parent->getNextNode();
207 if (Succ != nullptr && Parent->isSuccessor(Succ)) {
208 Position = Succ->begin();
209 Parent = Succ;
210 } else {
211 return std::make_pair(Position, true);
212 }
213 } while (Parent->empty());
214 }
215
216 Iter Instr = getNextMachineInstrInBB(Position);
217 if (Instr == Parent->end()) {
218 return getNextMachineInstr(Instr, Parent);
219 }
220 return std::make_pair(Instr, false);
221}
222
223/// Iterate over list of Br's operands and search for a MachineBasicBlock
224/// operand.
226 for (unsigned I = 0, E = Br.getDesc().getNumOperands(); I < E; ++I) {
227 const MachineOperand &MO = Br.getOperand(I);
228
229 if (MO.isMBB())
230 return MO.getMBB();
231 }
232
233 llvm_unreachable("This instruction does not have an MBB operand.");
234}
235
236// Traverse the list of instructions backwards until a non-debug instruction is
237// found or it reaches E.
238static ReverseIter getNonDebugInstr(ReverseIter B, const ReverseIter &E) {
239 for (; B != E; ++B)
240 if (!B->isDebugInstr())
241 return B;
242
243 return E;
244}
245
246// Split MBB if it has two direct jumps/branches.
247void MipsBranchExpansionImpl::splitMBB(MachineBasicBlock *MBB) {
248 ReverseIter End = MBB->rend();
249 ReverseIter LastBr = getNonDebugInstr(MBB->rbegin(), End);
250
251 // Return if MBB has no branch instructions.
252 if ((LastBr == End) ||
253 (!LastBr->isConditionalBranch() && !LastBr->isUnconditionalBranch()))
254 return;
255
256 ReverseIter FirstBr = getNonDebugInstr(std::next(LastBr), End);
257
258 // MBB has only one branch instruction if FirstBr is not a branch
259 // instruction.
260 if ((FirstBr == End) ||
261 (!FirstBr->isConditionalBranch() && !FirstBr->isUnconditionalBranch()))
262 return;
263
264 assert(!FirstBr->isIndirectBranch() && "Unexpected indirect branch found.");
265
266 // Create a new MBB. Move instructions in MBB to the newly created MBB.
267 MachineBasicBlock *NewMBB =
269
270 // Insert NewMBB and fix control flow.
271 MachineBasicBlock *Tgt = getTargetMBB(*FirstBr);
272 NewMBB->transferSuccessors(MBB);
273 if (Tgt != getTargetMBB(*LastBr))
274 NewMBB->removeSuccessor(Tgt, true);
275 MBB->addSuccessor(NewMBB);
276 MBB->addSuccessor(Tgt);
277 MFp->insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
278
279 NewMBB->splice(NewMBB->end(), MBB, LastBr.getReverse(), MBB->end());
280}
281
282// Fill MBBInfos.
283void MipsBranchExpansionImpl::initMBBInfo() {
284 // Split the MBBs if they have two branches. Each basic block should have at
285 // most one branch after this loop is executed.
286 for (auto &MBB : *MFp)
287 splitMBB(&MBB);
288
289 MFp->RenumberBlocks();
290 MBBInfos.clear();
291 MBBInfos.resize(MFp->size());
292
293 for (unsigned I = 0, E = MBBInfos.size(); I < E; ++I) {
294 MachineBasicBlock *MBB = MFp->getBlockNumbered(I);
295
296 // Compute size of MBB.
297 for (MachineInstr &MI : *MBB)
298 MBBInfos[I].Size += TII->getInstSizeInBytes(MI);
299 }
300}
301
302// Compute offset of branch in number of bytes.
303int64_t MipsBranchExpansionImpl::computeOffset(const MachineInstr *Br) {
304 int64_t Offset = 0;
305 int ThisMBB = Br->getParent()->getNumber();
306 int TargetMBB = getTargetMBB(*Br)->getNumber();
307
308 // Compute offset of a forward branch.
309 if (ThisMBB < TargetMBB) {
310 for (int N = ThisMBB + 1; N < TargetMBB; ++N)
311 Offset += MBBInfos[N].Size;
312
313 return Offset + 4;
314 }
315
316 // Compute offset of a backward branch.
317 for (int N = ThisMBB; N >= TargetMBB; --N)
318 Offset += MBBInfos[N].Size;
319
320 return -Offset + 4;
321}
322
323// Returns the distance in bytes up until MBB
324uint64_t MipsBranchExpansionImpl::computeOffsetFromTheBeginning(int MBB) {
325 uint64_t Offset = 0;
326 for (int N = 0; N < MBB; ++N)
327 Offset += MBBInfos[N].Size;
328 return Offset;
329}
330
331// Replace Br with a branch which has the opposite condition code and a
332// MachineBasicBlock operand MBBOpnd.
333void MipsBranchExpansionImpl::replaceBranch(MachineBasicBlock &MBB, Iter Br,
334 const DebugLoc &DL,
335 MachineBasicBlock *MBBOpnd) {
336 unsigned NewOpc = TII->getOppositeBranchOpc(Br->getOpcode());
337 const MCInstrDesc &NewDesc = TII->get(NewOpc);
338
339 MachineInstrBuilder MIB = BuildMI(MBB, Br, DL, NewDesc);
340
341 for (unsigned I = 0, E = Br->getDesc().getNumOperands(); I < E; ++I) {
342 MachineOperand &MO = Br->getOperand(I);
343
344 switch (MO.getType()) {
346 MIB.addReg(MO.getReg());
347 break;
349 // Octeon BBIT family of branch has an immediate operand
350 // (e.g. BBIT0 $v0, 3, %bb.1).
351 if (!TII->isBranchWithImm(Br->getOpcode()))
352 llvm_unreachable("Unexpected immediate in branch instruction");
353 MIB.addImm(MO.getImm());
354 break;
356 MIB.addMBB(MBBOpnd);
357 break;
358 default:
359 llvm_unreachable("Unexpected operand type in branch instruction");
360 }
361 }
362
363 if (Br->hasDelaySlot()) {
364 // Bundle the instruction in the delay slot to the newly created branch
365 // and erase the original branch.
366 assert(Br->isBundledWithSucc());
367 MachineBasicBlock::instr_iterator II = Br.getInstrIterator();
368 MIBundleBuilder(&*MIB).append((++II)->removeFromBundle());
369 }
370 Br->eraseFromParent();
371}
372
373bool MipsBranchExpansionImpl::buildProperJumpMI(MachineBasicBlock *MBB,
375 DebugLoc DL) {
376 bool HasR6 = ABI.IsN64() ? STI->hasMips64r6() : STI->hasMips32r6();
377 bool AddImm = HasR6 && !STI->useIndirectJumpsHazard();
378
379 unsigned JR = ABI.IsN64() ? Mips::JR64 : Mips::JR;
380 unsigned JIC = ABI.IsN64() ? Mips::JIC64 : Mips::JIC;
381 unsigned JR_HB = ABI.IsN64() ? Mips::JR_HB64 : Mips::JR_HB;
382 unsigned JR_HB_R6 = ABI.IsN64() ? Mips::JR_HB64_R6 : Mips::JR_HB_R6;
383
384 unsigned JumpOp;
385 if (STI->useIndirectJumpsHazard())
386 JumpOp = HasR6 ? JR_HB_R6 : JR_HB;
387 else
388 JumpOp = HasR6 ? JIC : JR;
389
390 if (JumpOp == Mips::JIC && STI->inMicroMipsMode())
391 JumpOp = Mips::JIC_MMR6;
392
393 unsigned ATReg = ABI.IsN64() ? Mips::R1_64 : Mips::R1;
394 MachineInstrBuilder Instr =
395 BuildMI(*MBB, Pos, DL, TII->get(JumpOp)).addReg(ATReg);
396 if (AddImm)
397 Instr.addImm(0);
398
399 return !AddImm;
400}
401
402// Expand branch instructions to long branches.
403// TODO: This function has to be fixed for beqz16 and bnez16, because it
404// currently assumes that all branches have 16-bit offsets, and will produce
405// wrong code if branches whose allowed offsets are [-128, -126, ..., 126]
406// are present.
407void MipsBranchExpansionImpl::expandToLongBranch(MBBInfo &I) {
409 MachineBasicBlock *MBB = I.Br->getParent(), *TgtMBB = getTargetMBB(*I.Br);
410 DebugLoc DL = I.Br->getDebugLoc();
411 const BasicBlock *BB = MBB->getBasicBlock();
413 MachineBasicBlock *LongBrMBB = MFp->CreateMachineBasicBlock(BB);
414
415 MFp->insert(FallThroughMBB, LongBrMBB);
416 MBB->replaceSuccessor(TgtMBB, LongBrMBB);
417
418 if (IsPIC) {
419 MachineBasicBlock *BalTgtMBB = MFp->CreateMachineBasicBlock(BB);
420 MFp->insert(FallThroughMBB, BalTgtMBB);
421 LongBrMBB->addSuccessor(BalTgtMBB);
422 BalTgtMBB->addSuccessor(TgtMBB);
423
424 // We must select between the MIPS32r6/MIPS64r6 BALC (which is a normal
425 // instruction) and the pre-MIPS32r6/MIPS64r6 definition (which is an
426 // pseudo-instruction wrapping BGEZAL).
427 const unsigned BalOp =
428 STI->hasMips32r6()
429 ? STI->inMicroMipsMode() ? Mips::BALC_MMR6 : Mips::BALC
430 : STI->inMicroMipsMode() ? Mips::BAL_BR_MM : Mips::BAL_BR;
431
432 if (!ABI.IsN64()) {
433 // Pre R6:
434 // $longbr:
435 // addiu $sp, $sp, -8
436 // sw $ra, 0($sp)
437 // lui $at, %hi($tgt - $baltgt)
438 // bal $baltgt
439 // addiu $at, $at, %lo($tgt - $baltgt)
440 // $baltgt:
441 // addu $at, $ra, $at
442 // lw $ra, 0($sp)
443 // jr $at
444 // addiu $sp, $sp, 8
445 // $fallthrough:
446 //
447
448 // R6:
449 // $longbr:
450 // addiu $sp, $sp, -8
451 // sw $ra, 0($sp)
452 // lui $at, %hi($tgt - $baltgt)
453 // addiu $at, $at, %lo($tgt - $baltgt)
454 // balc $baltgt
455 // $baltgt:
456 // addu $at, $ra, $at
457 // lw $ra, 0($sp)
458 // addiu $sp, $sp, 8
459 // jic $at, 0
460 // $fallthrough:
461
462 Pos = LongBrMBB->begin();
463
464 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
466 .addImm(-8);
467 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SW))
470 .addImm(0);
471
472 // LUi and ADDiu instructions create 32-bit offset of the target basic
473 // block from the target of BAL(C) instruction. We cannot use immediate
474 // value for this offset because it cannot be determined accurately when
475 // the program has inline assembly statements. We therefore use the
476 // relocation expressions %hi($tgt-$baltgt) and %lo($tgt-$baltgt) which
477 // are resolved during the fixup, so the values will always be correct.
478 //
479 // Since we cannot create %hi($tgt-$baltgt) and %lo($tgt-$baltgt)
480 // expressions at this point (it is possible only at the MC layer),
481 // we replace LUi and ADDiu with pseudo instructions
482 // LONG_BRANCH_LUi and LONG_BRANCH_ADDiu, and add both basic
483 // blocks as operands to these instructions. When lowering these pseudo
484 // instructions to LUi and ADDiu in the MC layer, we will create
485 // %hi($tgt-$baltgt) and %lo($tgt-$baltgt) expressions and add them as
486 // operands to lowered instructions.
487
488 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi), Mips::R1)
489 .addMBB(TgtMBB, MipsII::MO_ABS_HI)
490 .addMBB(BalTgtMBB);
491
492 MachineInstrBuilder BalInstr =
493 BuildMI(*MFp, DL, TII->get(BalOp)).addMBB(BalTgtMBB);
494 MachineInstrBuilder ADDiuInstr =
495 BuildMI(*MFp, DL, TII->get(Mips::LONG_BRANCH_ADDiu), Mips::R1)
496 .addReg(Mips::R1)
497 .addMBB(TgtMBB, MipsII::MO_ABS_LO)
498 .addMBB(BalTgtMBB);
499 if (STI->hasMips32r6()) {
500 LongBrMBB->insert(Pos, ADDiuInstr);
501 LongBrMBB->insert(Pos, BalInstr);
502 } else {
503 LongBrMBB->insert(Pos, BalInstr);
504 LongBrMBB->insert(Pos, ADDiuInstr);
505 LongBrMBB->rbegin()->bundleWithPred();
506 }
507
508 Pos = BalTgtMBB->begin();
509
510 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDu), Mips::R1)
512 .addReg(Mips::R1);
513 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LW), Mips::RA)
515 .addImm(0);
516
517 // For MIPS32R6, we can skip using a delay slot branch.
518 bool hasDelaySlot = buildProperJumpMI(BalTgtMBB, Pos, DL);
519
520 if (!hasDelaySlot) {
521 BuildMI(*BalTgtMBB, std::prev(Pos), DL, TII->get(Mips::ADDiu), Mips::SP)
523 .addImm(8);
524 }
525 if (hasDelaySlot) {
526 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
528 .addImm(8);
529 BalTgtMBB->rbegin()->bundleWithPred();
530 }
531 } else {
532 // Pre R6:
533 // $longbr:
534 // daddiu $sp, $sp, -16
535 // sd $ra, 0($sp)
536 // daddiu $at, $zero, %hi($tgt - $baltgt)
537 // dsll $at, $at, 16
538 // bal $baltgt
539 // daddiu $at, $at, %lo($tgt - $baltgt)
540 // $baltgt:
541 // daddu $at, $ra, $at
542 // ld $ra, 0($sp)
543 // jr64 $at
544 // daddiu $sp, $sp, 16
545 // $fallthrough:
546
547 // R6:
548 // $longbr:
549 // daddiu $sp, $sp, -16
550 // sd $ra, 0($sp)
551 // daddiu $at, $zero, %hi($tgt - $baltgt)
552 // dsll $at, $at, 16
553 // daddiu $at, $at, %lo($tgt - $baltgt)
554 // balc $baltgt
555 // $baltgt:
556 // daddu $at, $ra, $at
557 // ld $ra, 0($sp)
558 // daddiu $sp, $sp, 16
559 // jic $at, 0
560 // $fallthrough:
561
562 // We assume the branch is within-function, and that offset is within
563 // +/- 2GB. High 32 bits will therefore always be zero.
564
565 // Note that this will work even if the offset is negative, because
566 // of the +1 modification that's added in that case. For example, if the
567 // offset is -1MB (0xFFFFFFFFFFF00000), the computation for %higher is
568 //
569 // 0xFFFFFFFFFFF00000 + 0x80008000 = 0x000000007FF08000
570 //
571 // and the bits [47:32] are zero. For %highest
572 //
573 // 0xFFFFFFFFFFF00000 + 0x800080008000 = 0x000080007FF08000
574 //
575 // and the bits [63:48] are zero.
576
577 Pos = LongBrMBB->begin();
578
579 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DADDiu), Mips::SP_64)
581 .addImm(-16);
582 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SD))
585 .addImm(0);
586 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu),
587 Mips::R1_64)
588 .addReg(Mips::R0_64)
589 .addMBB(TgtMBB, MipsII::MO_ABS_HI)
590 .addMBB(BalTgtMBB);
591 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::R1_64)
592 .addReg(Mips::R1_64)
593 .addImm(16);
594
595 MachineInstrBuilder BalInstr =
596 BuildMI(*MFp, DL, TII->get(BalOp)).addMBB(BalTgtMBB);
597 MachineInstrBuilder DADDiuInstr =
598 BuildMI(*MFp, DL, TII->get(Mips::LONG_BRANCH_DADDiu), Mips::R1_64)
599 .addReg(Mips::R1_64)
600 .addMBB(TgtMBB, MipsII::MO_ABS_LO)
601 .addMBB(BalTgtMBB);
602 if (STI->hasMips32r6()) {
603 LongBrMBB->insert(Pos, DADDiuInstr);
604 LongBrMBB->insert(Pos, BalInstr);
605 } else {
606 LongBrMBB->insert(Pos, BalInstr);
607 LongBrMBB->insert(Pos, DADDiuInstr);
608 LongBrMBB->rbegin()->bundleWithPred();
609 }
610
611 Pos = BalTgtMBB->begin();
612
613 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::DADDu), Mips::R1_64)
615 .addReg(Mips::R1_64);
616 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LD), Mips::RA_64)
618 .addImm(0);
619
620 bool hasDelaySlot = buildProperJumpMI(BalTgtMBB, Pos, DL);
621 // If there is no delay slot, Insert stack adjustment before
622 if (!hasDelaySlot) {
623 BuildMI(*BalTgtMBB, std::prev(Pos), DL, TII->get(Mips::DADDiu),
626 .addImm(16);
627 } else {
628 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::DADDiu), Mips::SP_64)
630 .addImm(16);
631 BalTgtMBB->rbegin()->bundleWithPred();
632 }
633 }
634 } else { // Not PIC
635 Pos = LongBrMBB->begin();
636 LongBrMBB->addSuccessor(TgtMBB);
637
638 // Compute the position of the potentiall jump instruction (basic blocks
639 // before + 4 for the instruction)
640 uint64_t JOffset = computeOffsetFromTheBeginning(MBB->getNumber()) +
641 MBBInfos[MBB->getNumber()].Size + 4;
642 uint64_t TgtMBBOffset = computeOffsetFromTheBeginning(TgtMBB->getNumber());
643 // If it's a forward jump, then TgtMBBOffset will be shifted by two
644 // instructions
645 if (JOffset < TgtMBBOffset)
646 TgtMBBOffset += 2 * 4;
647 // Compare 4 upper bits to check if it's the same segment
648 bool SameSegmentJump = JOffset >> 28 == TgtMBBOffset >> 28;
649
650 if (STI->hasMips32r6() && TII->isBranchOffsetInRange(Mips::BC, I.Offset)) {
651 // R6:
652 // $longbr:
653 // bc $tgt
654 // $fallthrough:
655 //
656 BuildMI(*LongBrMBB, Pos, DL,
657 TII->get(STI->inMicroMipsMode() ? Mips::BC_MMR6 : Mips::BC))
658 .addMBB(TgtMBB);
659 } else if (SameSegmentJump) {
660 // Pre R6:
661 // $longbr:
662 // j $tgt
663 // nop
664 // $fallthrough:
665 //
666 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::J)).addMBB(TgtMBB);
667 TII->insertNop(*LongBrMBB, Pos, DL)->bundleWithPred();
668 } else {
669 // At this point, offset where we need to branch does not fit into
670 // immediate field of the branch instruction and is not in the same
671 // segment as jump instruction. Therefore we will break it into couple
672 // instructions, where we first load the offset into register, and then we
673 // do branch register.
674 if (ABI.IsN64()) {
675 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi2Op_64),
676 Mips::R1_64)
677 .addMBB(TgtMBB, MipsII::MO_HIGHEST);
678 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
679 Mips::R1_64)
680 .addReg(Mips::R1_64)
681 .addMBB(TgtMBB, MipsII::MO_HIGHER);
682 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::R1_64)
683 .addReg(Mips::R1_64)
684 .addImm(16);
685 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
686 Mips::R1_64)
687 .addReg(Mips::R1_64)
688 .addMBB(TgtMBB, MipsII::MO_ABS_HI);
689 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::R1_64)
690 .addReg(Mips::R1_64)
691 .addImm(16);
692 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
693 Mips::R1_64)
694 .addReg(Mips::R1_64)
695 .addMBB(TgtMBB, MipsII::MO_ABS_LO);
696 } else {
697 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi2Op),
698 Mips::R1)
699 .addMBB(TgtMBB, MipsII::MO_ABS_HI);
700 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_ADDiu2Op),
701 Mips::R1)
702 .addReg(Mips::R1)
703 .addMBB(TgtMBB, MipsII::MO_ABS_LO);
704 }
705 buildProperJumpMI(LongBrMBB, Pos, DL);
706 }
707 }
708
709 if (I.Br->isUnconditionalBranch()) {
710 // Change branch destination.
711 assert(I.Br->getDesc().getNumOperands() == 1);
712 I.Br->removeOperand(0);
713 I.Br->addOperand(MachineOperand::CreateMBB(LongBrMBB));
714 } else
715 // Change branch destination and reverse condition.
716 replaceBranch(*MBB, I.Br, DL, &*FallThroughMBB);
717}
718
720 MachineBasicBlock &MBB = F.front();
722 DebugLoc DL = MBB.findDebugLoc(MBB.begin());
723 BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::R2)
725 BuildMI(MBB, I, DL, TII->get(Mips::ADDiu), Mips::R2)
726 .addReg(Mips::R2)
728 MBB.removeLiveIn(Mips::R2);
729}
730
731// Returns how many instructions after an mflo or mfhi the first instruction
732// that writes HI or LO executes, looking at the instructions from I to the end
733// of MBB and then at every successor. Dist is the number of instructions
734// already counted. Returns 0 if no such instruction is within the two that
735// must follow the mflo or mfhi.
736unsigned MipsBranchExpansionImpl::distanceToHILOWrite(
737 MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator I,
738 unsigned Dist) {
740 if (I->isTransient())
741 continue;
742 ++Dist;
743 if (!TII->SafeAfterMflo(*I))
744 return Dist;
745 if (Dist == 2)
746 return 0;
747 }
748
749 unsigned Min = 0;
750 for (MachineBasicBlock *Succ : MBB.successors())
751 if (unsigned D = distanceToHILOWrite(*Succ, Succ->instr_begin(), Dist))
752 Min = Min ? std::min(Min, D) : D;
753 return Min;
754}
755
756// Returns true if MI is a NOP, either the NOP pseudo or the SLL $zero, $zero, 0
757// that insertNop() creates.
758static bool isNop(const MachineInstr &MI) {
759 switch (MI.getOpcode()) {
760 case Mips::NOP:
761 return true;
762 case Mips::SLL:
763 case Mips::SLL_MM:
764 case Mips::SLL_MMR6:
765 return MI.getOperand(0).getReg() == Mips::R0 &&
766 MI.getOperand(1).getReg() == Mips::R0 &&
767 MI.getOperand(2).getImm() == 0;
768 default:
769 return false;
770 }
771}
772
773template <typename Pred, typename Safe>
774bool MipsBranchExpansionImpl::handleSlot(Pred Predicate, Safe SafeInSlot) {
775 bool Changed = false;
776
777 for (MachineFunction::iterator FI = MFp->begin(); FI != MFp->end(); ++FI) {
778 for (Iter I = FI->begin(); I != FI->end(); ++I) {
779
780 // Delay slot hazard handling. Use lookahead over state.
781 if (!Predicate(*I))
782 continue;
783
784 Iter IInSlot;
785 bool LastInstInFunction =
786 std::next(I) == FI->end() && std::next(FI) == MFp->end();
787 if (!LastInstInFunction) {
788 std::pair<Iter, bool> Res = getNextMachineInstr(std::next(I), &*FI);
789 LastInstInFunction |= Res.second;
790 IInSlot = Res.first;
791 }
792
793 if (LastInstInFunction || !SafeInSlot(*IInSlot, *I)) {
794 MachineBasicBlock::instr_iterator Iit = I->getIterator();
795 if (std::next(Iit) == FI->end() || !isNop(*std::next(Iit))) {
796 Changed = true;
797 TII->insertNop(*(I->getParent()), std::next(I), I->getDebugLoc())
798 ->bundleWithPred();
799 NumInsertedNops++;
800 }
801 }
802 }
803 }
804
805 return Changed;
806}
807
808bool MipsBranchExpansionImpl::handleMFLO() {
809 // mips1-4 require a minimum of 2 instructions between a mflo/mfhi
810 // and the next instruction that writes HI or LO. Check every instruction
811 // that can execute next, including those in delay slots and successors.
812 if (STI->hasMips32() || STI->hasMips5())
813 return false;
814
815 bool Changed = false;
816 for (MachineBasicBlock &MBB : *MFp) {
818 E = MBB.instr_end();
819 I != E; ++I) {
820 if (!TII->IsMfloOrMfhi(*I))
821 continue;
822
823 if (!I->isBundledWithPred()) {
824 unsigned Dist = distanceToHILOWrite(MBB, std::next(I), 0);
825 if (!Dist)
826 continue;
827
828 // If the instruction that writes HI or LO is in this block, add the
829 // nops right before it, or before its branch if it is in a delay
830 // slot, where they can also cover a load delay slot. Otherwise add
831 // them right after the mflo, so they are on every path.
833 for (unsigned N = 0; W != E; ++W)
834 if (!W->isTransient() && ++N == Dist)
835 break;
836 bool InBlock = W != E && !TII->SafeAfterMflo(*W);
837 Iter Pos = InBlock ? Iter(getBundleStart(W)) : std::next(Iter(I));
838 for (; Dist <= 2; ++Dist) {
839 MachineInstrBuilder Nop = TII->insertNop(MBB, Pos, I->getDebugLoc());
840 if (!InBlock)
841 Nop->bundleWithPred();
842 NumInsertedNops++;
843 Changed = true;
844 }
845 continue;
846 }
847
848 // The mflo is in a delay slot and ends the block, so add the nops at
849 // the start of each successor that needs them.
850 for (MachineBasicBlock *Succ : MBB.successors()) {
851 unsigned Dist = distanceToHILOWrite(*Succ, Succ->instr_begin(), 0);
852 Iter Pos = Succ->empty() ? Succ->end()
853 : getNextMachineInstrInBB(Succ->begin());
854 for (; Dist && Dist <= 2; ++Dist) {
855 TII->insertNop(*Succ, Pos, I->getDebugLoc());
856 NumInsertedNops++;
857 Changed = true;
858 }
859 }
860 }
861 }
862
863 return Changed;
864}
865
866bool MipsBranchExpansionImpl::handleForbiddenSlot() {
867 // Forbidden slot hazards are only defined for MIPSR6 but not microMIPSR6.
868 if (!STI->hasMips32r6() || STI->inMicroMipsMode())
869 return false;
870
871 return handleSlot(
872 [this](auto &I) -> bool { return TII->HasForbiddenSlot(I); },
873 [this](auto &IInSlot, auto &I) -> bool {
874 return TII->SafeInForbiddenSlot(IInSlot);
875 });
876}
877
878bool MipsBranchExpansionImpl::handleFPUDelaySlot() {
879 // FPU delay slots are only defined for MIPS3 and below.
880 if (STI->hasMips32() || STI->hasMips4())
881 return false;
882
883 return handleSlot([this](auto &I) -> bool { return TII->HasFPUDelaySlot(I); },
884 [this](auto &IInSlot, auto &I) -> bool {
885 return TII->SafeInFPUDelaySlot(IInSlot, I);
886 });
887}
888
889bool MipsBranchExpansionImpl::handleLoadDelaySlot() {
890 // Load delay slot hazards are only for MIPS1.
891 if (STI->hasMips2())
892 return false;
893
894 return handleSlot(
895 [this](auto &I) -> bool { return TII->HasLoadDelaySlot(I); },
896 [this](auto &IInSlot, auto &I) -> bool {
897 return TII->SafeInLoadDelaySlot(IInSlot, I);
898 });
899}
900
901bool MipsBranchExpansionImpl::handlePossibleLongBranch() {
902 if (STI->inMips16Mode())
903 return false;
904
905 if (STI->getCLOpts().skip_mips_long_branch)
906 return false;
907
908 bool EverMadeChange = false, MadeChange = true;
909
910 while (MadeChange) {
911 MadeChange = false;
912
913 initMBBInfo();
914
915 for (unsigned I = 0, E = MBBInfos.size(); I < E; ++I) {
916 MachineBasicBlock *MBB = MFp->getBlockNumbered(I);
917 // Search for MBB's branch instruction.
918 ReverseIter End = MBB->rend();
919 ReverseIter Br = getNonDebugInstr(MBB->rbegin(), End);
920
921 if ((Br != End) && Br->isBranch() && !Br->isIndirectBranch() &&
922 (Br->isConditionalBranch() ||
923 (Br->isUnconditionalBranch() && IsPIC))) {
924 int64_t Offset = computeOffset(&*Br);
925
926 if (ForceLongBranchFirstPass ||
927 !TII->isBranchOffsetInRange(Br->getOpcode(), Offset)) {
928 MBBInfos[I].Offset = Offset;
929 MBBInfos[I].Br = &*Br;
930 }
931 }
932 } // End for
933
934 ForceLongBranchFirstPass = false;
935
936 SmallVectorImpl<MBBInfo>::iterator I, E = MBBInfos.end();
937
938 for (I = MBBInfos.begin(); I != E; ++I) {
939 // Skip if this MBB doesn't have a branch or the branch has already been
940 // converted to a long branch.
941 if (!I->Br)
942 continue;
943
944 expandToLongBranch(*I);
945 ++LongBranches;
946 EverMadeChange = MadeChange = true;
947 }
948
949 MFp->RenumberBlocks();
950 }
951
952 return EverMadeChange;
953}
954
955bool MipsBranchExpansionImpl::runOnMachineFunction(MachineFunction &MF) {
956 const TargetMachine &TM = MF.getTarget();
957 IsPIC = TM.isPositionIndependent();
958 STI = &MF.getSubtarget<MipsSubtarget>();
959 ABI = STI->getABI();
960 TII = STI->getInstrInfo();
961
962 if (IsPIC && ABI.IsO32() &&
963 MF.getInfo<MipsFunctionInfo>()->globalBaseRegSet())
964 emitGPDisp(MF, TII);
965
966 MFp = &MF;
967
968 ForceLongBranchFirstPass = STI->getCLOpts().force_mips_long_branch;
969 // Long branch expansion does not create MFLO/MFHI hazards, so only run
970 // handleMFLO() once.
971 bool Changed = handleMFLO();
972
973 // Only long branch expansion depends on instruction sizes, so run it last
974 // and repeat until it makes no more changes. Long branch expansion can
975 // create new hazards, so handle those again after each change.
976 bool LongBranchChanged;
977 do {
978 Changed |= handleForbiddenSlot();
979 Changed |= handleFPUDelaySlot();
980 Changed |= handleLoadDelaySlot();
981 LongBranchChanged = handlePossibleLongBranch();
982 Changed |= LongBranchChanged;
983 } while (LongBranchChanged);
984
985 return Changed;
986}
987
988bool MipsBranchExpansionLegacy::runOnMachineFunction(MachineFunction &MF) {
989 MipsBranchExpansionImpl Impl;
990 return Impl.runOnMachineFunction(MF);
991}
992
993PreservedAnalyses
996 MipsBranchExpansionImpl Impl;
997 return Impl.runOnMachineFunction(MF)
1000}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
uint64_t uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static std::pair< Iter, bool > getNextMachineInstr(Iter Position, MachineBasicBlock *Parent)
static MachineBasicBlock * getTargetMBB(const MachineInstr &Br)
Iterate over list of Br's operands and search for a MachineBasicBlock operand.
static bool isNop(const MachineInstr &MI)
static void emitGPDisp(MachineFunction &F, const MipsInstrInfo *TII)
static ReverseIter getNonDebugInstr(ReverseIter B, const ReverseIter &E)
static Iter getNextMachineInstrInBB(Iter Position)
uint64_t IntrinsicInst * II
static bool splitMBB(BlockSplitInfo &BSI)
Splits a MachineBasicBlock to branch before SplitBefore.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool InBlock(const Value *V, const BasicBlock *BB)
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:170
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
GetInstSize - Return the number of bytes of code the specified instruction may be.
bool isBranchOffsetInRange(unsigned BranchOpc, int64_t BrOffset) const override
A debug info location.
Definition DebugLoc.h:126
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
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 addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
Instructions::iterator instr_iterator
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
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 '...
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
LLVM_ABI void bundleWithPred()
Bundle this instruction with its predecessor.
const MachineBasicBlock * getParent() const
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
MachineBasicBlock * getMBB() const
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
Register getReg() const
getReg - Returns the register number.
@ MO_Immediate
Immediate operand.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
bool IsN64() const
Definition MipsABIInfo.h:41
static MipsABIInfo Unknown()
Definition MipsABIInfo.h:31
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
bool hasMips32r6() const
bool hasMips4() const
bool inMicroMipsMode() const
const MipsInstrInfo * getInstrInfo() const override
bool useIndirectJumpsHazard() const
bool hasMips64r6() const
bool inMips16Mode() const
bool hasMips5() const
bool hasMips32() const
const MipsOptions & getCLOpts() const
const MipsABIInfo & getABI() const
bool hasMips2() const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
typename SuperClass::iterator iterator
bool isPositionIndependent() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
constexpr MCPhysReg RA_64
constexpr MCPhysReg SP
constexpr MCPhysReg SP_64
constexpr MCPhysReg RA
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
MachineBasicBlock::instr_iterator getBundleStart(MachineBasicBlock::instr_iterator I)
Returns an iterator to the first instruction in the bundle containing I.
FunctionPass * createMipsBranchExpansionLegacyPass()
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
#define N