xref: /freebsd/contrib/llvm-project/llvm/lib/Target/Mips/MipsBranchExpansion.cpp (revision 5956d97f4b3204318ceb6aa9c77bd0bc6ea87a41)
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 ///
41 /// A forbidden slot hazard occurs when a compact branch instruction is executed
42 /// and the adjacent instruction in memory is a control transfer instruction
43 /// such as a branch or jump, ERET, ERETNC, DERET, WAIT and PAUSE.
44 ///
45 /// For example:
46 ///
47 /// 0x8004      bnec    a1,v0,<P+0x18>
48 /// 0x8008      beqc    a1,a2,<P+0x54>
49 ///
50 /// In such cases, the processor is required to signal a Reserved Instruction
51 /// exception.
52 ///
53 /// Here, if the instruction at 0x8004 is executed, the processor will raise an
54 /// exception as there is a control transfer instruction at 0x8008.
55 ///
56 /// There are two sources of forbidden slot hazards:
57 ///
58 /// A) A previous pass has created a compact branch directly.
59 /// B) Transforming a delay slot branch into compact branch. This case can be
60 ///    difficult to process as lookahead for hazards is insufficient, as
61 ///    backwards delay slot fillling can also produce hazards in previously
62 ///    processed instuctions.
63 ///
64 /// In future this pass can be extended (or new pass can be created) to handle
65 /// other pipeline hazards, such as various MIPS1 hazards, processor errata that
66 /// require instruction reorganization, etc.
67 ///
68 /// This pass has to run after the delay slot filler as that pass can introduce
69 /// pipeline hazards such as compact branch hazard, hence the existing hazard
70 /// recognizer is not suitable.
71 ///
72 //===----------------------------------------------------------------------===//
73 
74 #include "MCTargetDesc/MipsABIInfo.h"
75 #include "MCTargetDesc/MipsBaseInfo.h"
76 #include "MCTargetDesc/MipsMCNaCl.h"
77 #include "MCTargetDesc/MipsMCTargetDesc.h"
78 #include "Mips.h"
79 #include "MipsInstrInfo.h"
80 #include "MipsMachineFunction.h"
81 #include "MipsSubtarget.h"
82 #include "MipsTargetMachine.h"
83 #include "llvm/ADT/SmallVector.h"
84 #include "llvm/ADT/Statistic.h"
85 #include "llvm/ADT/StringRef.h"
86 #include "llvm/CodeGen/MachineBasicBlock.h"
87 #include "llvm/CodeGen/MachineFunction.h"
88 #include "llvm/CodeGen/MachineFunctionPass.h"
89 #include "llvm/CodeGen/MachineInstr.h"
90 #include "llvm/CodeGen/MachineInstrBuilder.h"
91 #include "llvm/CodeGen/MachineModuleInfo.h"
92 #include "llvm/CodeGen/MachineOperand.h"
93 #include "llvm/CodeGen/TargetSubtargetInfo.h"
94 #include "llvm/IR/DebugLoc.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/ErrorHandling.h"
97 #include "llvm/Support/MathExtras.h"
98 #include "llvm/Target/TargetMachine.h"
99 #include <algorithm>
100 #include <cassert>
101 #include <cstdint>
102 #include <iterator>
103 #include <utility>
104 
105 using namespace llvm;
106 
107 #define DEBUG_TYPE "mips-branch-expansion"
108 
109 STATISTIC(NumInsertedNops, "Number of nops inserted");
110 STATISTIC(LongBranches, "Number of long branches.");
111 
112 static cl::opt<bool>
113     SkipLongBranch("skip-mips-long-branch", cl::init(false),
114                    cl::desc("MIPS: Skip branch expansion pass."), cl::Hidden);
115 
116 static cl::opt<bool>
117     ForceLongBranch("force-mips-long-branch", cl::init(false),
118                     cl::desc("MIPS: Expand all branches to long format."),
119                     cl::Hidden);
120 
121 namespace {
122 
123 using Iter = MachineBasicBlock::iterator;
124 using ReverseIter = MachineBasicBlock::reverse_iterator;
125 
126 struct MBBInfo {
127   uint64_t Size = 0;
128   bool HasLongBranch = false;
129   MachineInstr *Br = nullptr;
130   uint64_t Offset = 0;
131   MBBInfo() = default;
132 };
133 
134 class MipsBranchExpansion : public MachineFunctionPass {
135 public:
136   static char ID;
137 
138   MipsBranchExpansion() : MachineFunctionPass(ID), ABI(MipsABIInfo::Unknown()) {
139     initializeMipsBranchExpansionPass(*PassRegistry::getPassRegistry());
140   }
141 
142   StringRef getPassName() const override {
143     return "Mips Branch Expansion Pass";
144   }
145 
146   bool runOnMachineFunction(MachineFunction &F) override;
147 
148   MachineFunctionProperties getRequiredProperties() const override {
149     return MachineFunctionProperties().set(
150         MachineFunctionProperties::Property::NoVRegs);
151   }
152 
153 private:
154   void splitMBB(MachineBasicBlock *MBB);
155   void initMBBInfo();
156   int64_t computeOffset(const MachineInstr *Br);
157   uint64_t computeOffsetFromTheBeginning(int MBB);
158   void replaceBranch(MachineBasicBlock &MBB, Iter Br, const DebugLoc &DL,
159                      MachineBasicBlock *MBBOpnd);
160   bool buildProperJumpMI(MachineBasicBlock *MBB,
161                          MachineBasicBlock::iterator Pos, DebugLoc DL);
162   void expandToLongBranch(MBBInfo &Info);
163   template <typename Pred, typename Safe>
164   bool handleSlot(Pred Predicate, Safe SafeInSlot);
165   bool handleForbiddenSlot();
166   bool handleFPUDelaySlot();
167   bool handlePossibleLongBranch();
168 
169   const MipsSubtarget *STI;
170   const MipsInstrInfo *TII;
171 
172   MachineFunction *MFp;
173   SmallVector<MBBInfo, 16> MBBInfos;
174   bool IsPIC;
175   MipsABIInfo ABI;
176   bool ForceLongBranchFirstPass = false;
177 };
178 
179 } // end of anonymous namespace
180 
181 char MipsBranchExpansion::ID = 0;
182 
183 INITIALIZE_PASS(MipsBranchExpansion, DEBUG_TYPE,
184                 "Expand out of range branch instructions and fix forbidden"
185                 " slot hazards",
186                 false, false)
187 
188 /// Returns a pass that clears pipeline hazards.
189 FunctionPass *llvm::createMipsBranchExpansion() {
190   return new MipsBranchExpansion();
191 }
192 
193 // Find the next real instruction from the current position in current basic
194 // block.
195 static Iter getNextMachineInstrInBB(Iter Position) {
196   Iter I = Position, E = Position->getParent()->end();
197   I = std::find_if_not(I, E,
198                        [](const Iter &Insn) { return Insn->isTransient(); });
199 
200   return I;
201 }
202 
203 // Find the next real instruction from the current position, looking through
204 // basic block boundaries.
205 static std::pair<Iter, bool> getNextMachineInstr(Iter Position,
206                                                  MachineBasicBlock *Parent) {
207   if (Position == Parent->end()) {
208     do {
209       MachineBasicBlock *Succ = Parent->getNextNode();
210       if (Succ != nullptr && Parent->isSuccessor(Succ)) {
211         Position = Succ->begin();
212         Parent = Succ;
213       } else {
214         return std::make_pair(Position, true);
215       }
216     } while (Parent->empty());
217   }
218 
219   Iter Instr = getNextMachineInstrInBB(Position);
220   if (Instr == Parent->end()) {
221     return getNextMachineInstr(Instr, Parent);
222   }
223   return std::make_pair(Instr, false);
224 }
225 
226 /// Iterate over list of Br's operands and search for a MachineBasicBlock
227 /// operand.
228 static MachineBasicBlock *getTargetMBB(const MachineInstr &Br) {
229   for (unsigned I = 0, E = Br.getDesc().getNumOperands(); I < E; ++I) {
230     const MachineOperand &MO = Br.getOperand(I);
231 
232     if (MO.isMBB())
233       return MO.getMBB();
234   }
235 
236   llvm_unreachable("This instruction does not have an MBB operand.");
237 }
238 
239 // Traverse the list of instructions backwards until a non-debug instruction is
240 // found or it reaches E.
241 static ReverseIter getNonDebugInstr(ReverseIter B, const ReverseIter &E) {
242   for (; B != E; ++B)
243     if (!B->isDebugInstr())
244       return B;
245 
246   return E;
247 }
248 
249 // Split MBB if it has two direct jumps/branches.
250 void MipsBranchExpansion::splitMBB(MachineBasicBlock *MBB) {
251   ReverseIter End = MBB->rend();
252   ReverseIter LastBr = getNonDebugInstr(MBB->rbegin(), End);
253 
254   // Return if MBB has no branch instructions.
255   if ((LastBr == End) ||
256       (!LastBr->isConditionalBranch() && !LastBr->isUnconditionalBranch()))
257     return;
258 
259   ReverseIter FirstBr = getNonDebugInstr(std::next(LastBr), End);
260 
261   // MBB has only one branch instruction if FirstBr is not a branch
262   // instruction.
263   if ((FirstBr == End) ||
264       (!FirstBr->isConditionalBranch() && !FirstBr->isUnconditionalBranch()))
265     return;
266 
267   assert(!FirstBr->isIndirectBranch() && "Unexpected indirect branch found.");
268 
269   // Create a new MBB. Move instructions in MBB to the newly created MBB.
270   MachineBasicBlock *NewMBB =
271       MFp->CreateMachineBasicBlock(MBB->getBasicBlock());
272 
273   // Insert NewMBB and fix control flow.
274   MachineBasicBlock *Tgt = getTargetMBB(*FirstBr);
275   NewMBB->transferSuccessors(MBB);
276   if (Tgt != getTargetMBB(*LastBr))
277     NewMBB->removeSuccessor(Tgt, true);
278   MBB->addSuccessor(NewMBB);
279   MBB->addSuccessor(Tgt);
280   MFp->insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
281 
282   NewMBB->splice(NewMBB->end(), MBB, LastBr.getReverse(), MBB->end());
283 }
284 
285 // Fill MBBInfos.
286 void MipsBranchExpansion::initMBBInfo() {
287   // Split the MBBs if they have two branches. Each basic block should have at
288   // most one branch after this loop is executed.
289   for (auto &MBB : *MFp)
290     splitMBB(&MBB);
291 
292   MFp->RenumberBlocks();
293   MBBInfos.clear();
294   MBBInfos.resize(MFp->size());
295 
296   for (unsigned I = 0, E = MBBInfos.size(); I < E; ++I) {
297     MachineBasicBlock *MBB = MFp->getBlockNumbered(I);
298 
299     // Compute size of MBB.
300     for (MachineBasicBlock::instr_iterator MI = MBB->instr_begin();
301          MI != MBB->instr_end(); ++MI)
302       MBBInfos[I].Size += TII->getInstSizeInBytes(*MI);
303   }
304 }
305 
306 // Compute offset of branch in number of bytes.
307 int64_t MipsBranchExpansion::computeOffset(const MachineInstr *Br) {
308   int64_t Offset = 0;
309   int ThisMBB = Br->getParent()->getNumber();
310   int TargetMBB = getTargetMBB(*Br)->getNumber();
311 
312   // Compute offset of a forward branch.
313   if (ThisMBB < TargetMBB) {
314     for (int N = ThisMBB + 1; N < TargetMBB; ++N)
315       Offset += MBBInfos[N].Size;
316 
317     return Offset + 4;
318   }
319 
320   // Compute offset of a backward branch.
321   for (int N = ThisMBB; N >= TargetMBB; --N)
322     Offset += MBBInfos[N].Size;
323 
324   return -Offset + 4;
325 }
326 
327 // Returns the distance in bytes up until MBB
328 uint64_t MipsBranchExpansion::computeOffsetFromTheBeginning(int MBB) {
329   uint64_t Offset = 0;
330   for (int N = 0; N < MBB; ++N)
331     Offset += MBBInfos[N].Size;
332   return Offset;
333 }
334 
335 // Replace Br with a branch which has the opposite condition code and a
336 // MachineBasicBlock operand MBBOpnd.
337 void MipsBranchExpansion::replaceBranch(MachineBasicBlock &MBB, Iter Br,
338                                         const DebugLoc &DL,
339                                         MachineBasicBlock *MBBOpnd) {
340   unsigned NewOpc = TII->getOppositeBranchOpc(Br->getOpcode());
341   const MCInstrDesc &NewDesc = TII->get(NewOpc);
342 
343   MachineInstrBuilder MIB = BuildMI(MBB, Br, DL, NewDesc);
344 
345   for (unsigned I = 0, E = Br->getDesc().getNumOperands(); I < E; ++I) {
346     MachineOperand &MO = Br->getOperand(I);
347 
348     switch (MO.getType()) {
349     case MachineOperand::MO_Register:
350       MIB.addReg(MO.getReg());
351       break;
352     case MachineOperand::MO_Immediate:
353       // Octeon BBIT family of branch has an immediate operand
354       // (e.g. BBIT0 $v0, 3, %bb.1).
355       if (!TII->isBranchWithImm(Br->getOpcode()))
356         llvm_unreachable("Unexpected immediate in branch instruction");
357       MIB.addImm(MO.getImm());
358       break;
359     case MachineOperand::MO_MachineBasicBlock:
360       MIB.addMBB(MBBOpnd);
361       break;
362     default:
363       llvm_unreachable("Unexpected operand type in branch instruction");
364     }
365   }
366 
367   if (Br->hasDelaySlot()) {
368     // Bundle the instruction in the delay slot to the newly created branch
369     // and erase the original branch.
370     assert(Br->isBundledWithSucc());
371     MachineBasicBlock::instr_iterator II = Br.getInstrIterator();
372     MIBundleBuilder(&*MIB).append((++II)->removeFromBundle());
373   }
374   Br->eraseFromParent();
375 }
376 
377 bool MipsBranchExpansion::buildProperJumpMI(MachineBasicBlock *MBB,
378                                             MachineBasicBlock::iterator Pos,
379                                             DebugLoc DL) {
380   bool HasR6 = ABI.IsN64() ? STI->hasMips64r6() : STI->hasMips32r6();
381   bool AddImm = HasR6 && !STI->useIndirectJumpsHazard();
382 
383   unsigned JR = ABI.IsN64() ? Mips::JR64 : Mips::JR;
384   unsigned JIC = ABI.IsN64() ? Mips::JIC64 : Mips::JIC;
385   unsigned JR_HB = ABI.IsN64() ? Mips::JR_HB64 : Mips::JR_HB;
386   unsigned JR_HB_R6 = ABI.IsN64() ? Mips::JR_HB64_R6 : Mips::JR_HB_R6;
387 
388   unsigned JumpOp;
389   if (STI->useIndirectJumpsHazard())
390     JumpOp = HasR6 ? JR_HB_R6 : JR_HB;
391   else
392     JumpOp = HasR6 ? JIC : JR;
393 
394   if (JumpOp == Mips::JIC && STI->inMicroMipsMode())
395     JumpOp = Mips::JIC_MMR6;
396 
397   unsigned ATReg = ABI.IsN64() ? Mips::AT_64 : Mips::AT;
398   MachineInstrBuilder Instr =
399       BuildMI(*MBB, Pos, DL, TII->get(JumpOp)).addReg(ATReg);
400   if (AddImm)
401     Instr.addImm(0);
402 
403   return !AddImm;
404 }
405 
406 // Expand branch instructions to long branches.
407 // TODO: This function has to be fixed for beqz16 and bnez16, because it
408 // currently assumes that all branches have 16-bit offsets, and will produce
409 // wrong code if branches whose allowed offsets are [-128, -126, ..., 126]
410 // are present.
411 void MipsBranchExpansion::expandToLongBranch(MBBInfo &I) {
412   MachineBasicBlock::iterator Pos;
413   MachineBasicBlock *MBB = I.Br->getParent(), *TgtMBB = getTargetMBB(*I.Br);
414   DebugLoc DL = I.Br->getDebugLoc();
415   const BasicBlock *BB = MBB->getBasicBlock();
416   MachineFunction::iterator FallThroughMBB = ++MachineFunction::iterator(MBB);
417   MachineBasicBlock *LongBrMBB = MFp->CreateMachineBasicBlock(BB);
418 
419   MFp->insert(FallThroughMBB, LongBrMBB);
420   MBB->replaceSuccessor(TgtMBB, LongBrMBB);
421 
422   if (IsPIC) {
423     MachineBasicBlock *BalTgtMBB = MFp->CreateMachineBasicBlock(BB);
424     MFp->insert(FallThroughMBB, BalTgtMBB);
425     LongBrMBB->addSuccessor(BalTgtMBB);
426     BalTgtMBB->addSuccessor(TgtMBB);
427 
428     // We must select between the MIPS32r6/MIPS64r6 BALC (which is a normal
429     // instruction) and the pre-MIPS32r6/MIPS64r6 definition (which is an
430     // pseudo-instruction wrapping BGEZAL).
431     const unsigned BalOp =
432         STI->hasMips32r6()
433             ? STI->inMicroMipsMode() ? Mips::BALC_MMR6 : Mips::BALC
434             : STI->inMicroMipsMode() ? Mips::BAL_BR_MM : Mips::BAL_BR;
435 
436     if (!ABI.IsN64()) {
437       // Pre R6:
438       // $longbr:
439       //  addiu $sp, $sp, -8
440       //  sw $ra, 0($sp)
441       //  lui $at, %hi($tgt - $baltgt)
442       //  bal $baltgt
443       //  addiu $at, $at, %lo($tgt - $baltgt)
444       // $baltgt:
445       //  addu $at, $ra, $at
446       //  lw $ra, 0($sp)
447       //  jr $at
448       //  addiu $sp, $sp, 8
449       // $fallthrough:
450       //
451 
452       // R6:
453       // $longbr:
454       //  addiu $sp, $sp, -8
455       //  sw $ra, 0($sp)
456       //  lui $at, %hi($tgt - $baltgt)
457       //  addiu $at, $at, %lo($tgt - $baltgt)
458       //  balc $baltgt
459       // $baltgt:
460       //  addu $at, $ra, $at
461       //  lw $ra, 0($sp)
462       //  addiu $sp, $sp, 8
463       //  jic $at, 0
464       // $fallthrough:
465 
466       Pos = LongBrMBB->begin();
467 
468       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
469           .addReg(Mips::SP)
470           .addImm(-8);
471       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SW))
472           .addReg(Mips::RA)
473           .addReg(Mips::SP)
474           .addImm(0);
475 
476       // LUi and ADDiu instructions create 32-bit offset of the target basic
477       // block from the target of BAL(C) instruction.  We cannot use immediate
478       // value for this offset because it cannot be determined accurately when
479       // the program has inline assembly statements.  We therefore use the
480       // relocation expressions %hi($tgt-$baltgt) and %lo($tgt-$baltgt) which
481       // are resolved during the fixup, so the values will always be correct.
482       //
483       // Since we cannot create %hi($tgt-$baltgt) and %lo($tgt-$baltgt)
484       // expressions at this point (it is possible only at the MC layer),
485       // we replace LUi and ADDiu with pseudo instructions
486       // LONG_BRANCH_LUi and LONG_BRANCH_ADDiu, and add both basic
487       // blocks as operands to these instructions.  When lowering these pseudo
488       // instructions to LUi and ADDiu in the MC layer, we will create
489       // %hi($tgt-$baltgt) and %lo($tgt-$baltgt) expressions and add them as
490       // operands to lowered instructions.
491 
492       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi), Mips::AT)
493           .addMBB(TgtMBB, MipsII::MO_ABS_HI)
494           .addMBB(BalTgtMBB);
495 
496       MachineInstrBuilder BalInstr =
497           BuildMI(*MFp, DL, TII->get(BalOp)).addMBB(BalTgtMBB);
498       MachineInstrBuilder ADDiuInstr =
499           BuildMI(*MFp, DL, TII->get(Mips::LONG_BRANCH_ADDiu), Mips::AT)
500               .addReg(Mips::AT)
501               .addMBB(TgtMBB, MipsII::MO_ABS_LO)
502               .addMBB(BalTgtMBB);
503       if (STI->hasMips32r6()) {
504         LongBrMBB->insert(Pos, ADDiuInstr);
505         LongBrMBB->insert(Pos, BalInstr);
506       } else {
507         LongBrMBB->insert(Pos, BalInstr);
508         LongBrMBB->insert(Pos, ADDiuInstr);
509         LongBrMBB->rbegin()->bundleWithPred();
510       }
511 
512       Pos = BalTgtMBB->begin();
513 
514       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDu), Mips::AT)
515           .addReg(Mips::RA)
516           .addReg(Mips::AT);
517       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LW), Mips::RA)
518           .addReg(Mips::SP)
519           .addImm(0);
520       if (STI->isTargetNaCl())
521         // Bundle-align the target of indirect branch JR.
522         TgtMBB->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
523 
524       // In NaCl, modifying the sp is not allowed in branch delay slot.
525       // For MIPS32R6, we can skip using a delay slot branch.
526       bool hasDelaySlot = buildProperJumpMI(BalTgtMBB, Pos, DL);
527 
528       if (STI->isTargetNaCl() || !hasDelaySlot) {
529         BuildMI(*BalTgtMBB, std::prev(Pos), DL, TII->get(Mips::ADDiu), Mips::SP)
530             .addReg(Mips::SP)
531             .addImm(8);
532       }
533       if (hasDelaySlot) {
534         if (STI->isTargetNaCl()) {
535           BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::NOP));
536         } else {
537           BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
538               .addReg(Mips::SP)
539               .addImm(8);
540         }
541         BalTgtMBB->rbegin()->bundleWithPred();
542       }
543     } else {
544       // Pre R6:
545       // $longbr:
546       //  daddiu $sp, $sp, -16
547       //  sd $ra, 0($sp)
548       //  daddiu $at, $zero, %hi($tgt - $baltgt)
549       //  dsll $at, $at, 16
550       //  bal $baltgt
551       //  daddiu $at, $at, %lo($tgt - $baltgt)
552       // $baltgt:
553       //  daddu $at, $ra, $at
554       //  ld $ra, 0($sp)
555       //  jr64 $at
556       //  daddiu $sp, $sp, 16
557       // $fallthrough:
558 
559       // R6:
560       // $longbr:
561       //  daddiu $sp, $sp, -16
562       //  sd $ra, 0($sp)
563       //  daddiu $at, $zero, %hi($tgt - $baltgt)
564       //  dsll $at, $at, 16
565       //  daddiu $at, $at, %lo($tgt - $baltgt)
566       //  balc $baltgt
567       // $baltgt:
568       //  daddu $at, $ra, $at
569       //  ld $ra, 0($sp)
570       //  daddiu $sp, $sp, 16
571       //  jic $at, 0
572       // $fallthrough:
573 
574       // We assume the branch is within-function, and that offset is within
575       // +/- 2GB.  High 32 bits will therefore always be zero.
576 
577       // Note that this will work even if the offset is negative, because
578       // of the +1 modification that's added in that case.  For example, if the
579       // offset is -1MB (0xFFFFFFFFFFF00000), the computation for %higher is
580       //
581       // 0xFFFFFFFFFFF00000 + 0x80008000 = 0x000000007FF08000
582       //
583       // and the bits [47:32] are zero.  For %highest
584       //
585       // 0xFFFFFFFFFFF00000 + 0x800080008000 = 0x000080007FF08000
586       //
587       // and the bits [63:48] are zero.
588 
589       Pos = LongBrMBB->begin();
590 
591       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DADDiu), Mips::SP_64)
592           .addReg(Mips::SP_64)
593           .addImm(-16);
594       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SD))
595           .addReg(Mips::RA_64)
596           .addReg(Mips::SP_64)
597           .addImm(0);
598       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu),
599               Mips::AT_64)
600           .addReg(Mips::ZERO_64)
601           .addMBB(TgtMBB, MipsII::MO_ABS_HI)
602           .addMBB(BalTgtMBB);
603       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::AT_64)
604           .addReg(Mips::AT_64)
605           .addImm(16);
606 
607       MachineInstrBuilder BalInstr =
608           BuildMI(*MFp, DL, TII->get(BalOp)).addMBB(BalTgtMBB);
609       MachineInstrBuilder DADDiuInstr =
610           BuildMI(*MFp, DL, TII->get(Mips::LONG_BRANCH_DADDiu), Mips::AT_64)
611               .addReg(Mips::AT_64)
612               .addMBB(TgtMBB, MipsII::MO_ABS_LO)
613               .addMBB(BalTgtMBB);
614       if (STI->hasMips32r6()) {
615         LongBrMBB->insert(Pos, DADDiuInstr);
616         LongBrMBB->insert(Pos, BalInstr);
617       } else {
618         LongBrMBB->insert(Pos, BalInstr);
619         LongBrMBB->insert(Pos, DADDiuInstr);
620         LongBrMBB->rbegin()->bundleWithPred();
621       }
622 
623       Pos = BalTgtMBB->begin();
624 
625       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::DADDu), Mips::AT_64)
626           .addReg(Mips::RA_64)
627           .addReg(Mips::AT_64);
628       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LD), Mips::RA_64)
629           .addReg(Mips::SP_64)
630           .addImm(0);
631 
632       bool hasDelaySlot = buildProperJumpMI(BalTgtMBB, Pos, DL);
633       // If there is no delay slot, Insert stack adjustment before
634       if (!hasDelaySlot) {
635         BuildMI(*BalTgtMBB, std::prev(Pos), DL, TII->get(Mips::DADDiu),
636                 Mips::SP_64)
637             .addReg(Mips::SP_64)
638             .addImm(16);
639       } else {
640         BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::DADDiu), Mips::SP_64)
641             .addReg(Mips::SP_64)
642             .addImm(16);
643         BalTgtMBB->rbegin()->bundleWithPred();
644       }
645     }
646   } else { // Not PIC
647     Pos = LongBrMBB->begin();
648     LongBrMBB->addSuccessor(TgtMBB);
649 
650     // Compute the position of the potentiall jump instruction (basic blocks
651     // before + 4 for the instruction)
652     uint64_t JOffset = computeOffsetFromTheBeginning(MBB->getNumber()) +
653                        MBBInfos[MBB->getNumber()].Size + 4;
654     uint64_t TgtMBBOffset = computeOffsetFromTheBeginning(TgtMBB->getNumber());
655     // If it's a forward jump, then TgtMBBOffset will be shifted by two
656     // instructions
657     if (JOffset < TgtMBBOffset)
658       TgtMBBOffset += 2 * 4;
659     // Compare 4 upper bits to check if it's the same segment
660     bool SameSegmentJump = JOffset >> 28 == TgtMBBOffset >> 28;
661 
662     if (STI->hasMips32r6() && TII->isBranchOffsetInRange(Mips::BC, I.Offset)) {
663       // R6:
664       // $longbr:
665       //  bc $tgt
666       // $fallthrough:
667       //
668       BuildMI(*LongBrMBB, Pos, DL,
669               TII->get(STI->inMicroMipsMode() ? Mips::BC_MMR6 : Mips::BC))
670           .addMBB(TgtMBB);
671     } else if (SameSegmentJump) {
672       // Pre R6:
673       // $longbr:
674       //  j $tgt
675       //  nop
676       // $fallthrough:
677       //
678       MIBundleBuilder(*LongBrMBB, Pos)
679           .append(BuildMI(*MFp, DL, TII->get(Mips::J)).addMBB(TgtMBB))
680           .append(BuildMI(*MFp, DL, TII->get(Mips::NOP)));
681     } else {
682       // At this point, offset where we need to branch does not fit into
683       // immediate field of the branch instruction and is not in the same
684       // segment as jump instruction. Therefore we will break it into couple
685       // instructions, where we first load the offset into register, and then we
686       // do branch register.
687       if (ABI.IsN64()) {
688         BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi2Op_64),
689                 Mips::AT_64)
690             .addMBB(TgtMBB, MipsII::MO_HIGHEST);
691         BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
692                 Mips::AT_64)
693             .addReg(Mips::AT_64)
694             .addMBB(TgtMBB, MipsII::MO_HIGHER);
695         BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::AT_64)
696             .addReg(Mips::AT_64)
697             .addImm(16);
698         BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
699                 Mips::AT_64)
700             .addReg(Mips::AT_64)
701             .addMBB(TgtMBB, MipsII::MO_ABS_HI);
702         BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::AT_64)
703             .addReg(Mips::AT_64)
704             .addImm(16);
705         BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
706                 Mips::AT_64)
707             .addReg(Mips::AT_64)
708             .addMBB(TgtMBB, MipsII::MO_ABS_LO);
709       } else {
710         BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi2Op),
711                 Mips::AT)
712             .addMBB(TgtMBB, MipsII::MO_ABS_HI);
713         BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_ADDiu2Op),
714                 Mips::AT)
715             .addReg(Mips::AT)
716             .addMBB(TgtMBB, MipsII::MO_ABS_LO);
717       }
718       buildProperJumpMI(LongBrMBB, Pos, DL);
719     }
720   }
721 
722   if (I.Br->isUnconditionalBranch()) {
723     // Change branch destination.
724     assert(I.Br->getDesc().getNumOperands() == 1);
725     I.Br->RemoveOperand(0);
726     I.Br->addOperand(MachineOperand::CreateMBB(LongBrMBB));
727   } else
728     // Change branch destination and reverse condition.
729     replaceBranch(*MBB, I.Br, DL, &*FallThroughMBB);
730 }
731 
732 static void emitGPDisp(MachineFunction &F, const MipsInstrInfo *TII) {
733   MachineBasicBlock &MBB = F.front();
734   MachineBasicBlock::iterator I = MBB.begin();
735   DebugLoc DL = MBB.findDebugLoc(MBB.begin());
736   BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::V0)
737       .addExternalSymbol("_gp_disp", MipsII::MO_ABS_HI);
738   BuildMI(MBB, I, DL, TII->get(Mips::ADDiu), Mips::V0)
739       .addReg(Mips::V0)
740       .addExternalSymbol("_gp_disp", MipsII::MO_ABS_LO);
741   MBB.removeLiveIn(Mips::V0);
742 }
743 
744 template <typename Pred, typename Safe>
745 bool MipsBranchExpansion::handleSlot(Pred Predicate, Safe SafeInSlot) {
746   bool Changed = false;
747 
748   for (MachineFunction::iterator FI = MFp->begin(); FI != MFp->end(); ++FI) {
749     for (Iter I = FI->begin(); I != FI->end(); ++I) {
750 
751       // Delay slot hazard handling. Use lookahead over state.
752       if (!Predicate(*I))
753         continue;
754 
755       Iter IInSlot;
756       bool LastInstInFunction =
757           std::next(I) == FI->end() && std::next(FI) == MFp->end();
758       if (!LastInstInFunction) {
759         std::pair<Iter, bool> Res = getNextMachineInstr(std::next(I), &*FI);
760         LastInstInFunction |= Res.second;
761         IInSlot = Res.first;
762       }
763 
764       if (LastInstInFunction || !SafeInSlot(*IInSlot, *I)) {
765 
766         MachineBasicBlock::instr_iterator Iit = I->getIterator();
767         if (std::next(Iit) == FI->end() ||
768             std::next(Iit)->getOpcode() != Mips::NOP) {
769           Changed = true;
770           MIBundleBuilder(&*I).append(
771               BuildMI(*MFp, I->getDebugLoc(), TII->get(Mips::NOP)));
772           NumInsertedNops++;
773         }
774       }
775     }
776   }
777 
778   return Changed;
779 }
780 
781 bool MipsBranchExpansion::handleForbiddenSlot() {
782   // Forbidden slot hazards are only defined for MIPSR6 but not microMIPSR6.
783   if (!STI->hasMips32r6() || STI->inMicroMipsMode())
784     return false;
785 
786   return handleSlot(
787       [this](auto &I) -> bool { return TII->HasForbiddenSlot(I); },
788       [this](auto &IInSlot, auto &I) -> bool {
789         return TII->SafeInForbiddenSlot(IInSlot);
790       });
791 }
792 
793 bool MipsBranchExpansion::handleFPUDelaySlot() {
794   // FPU delay slots are only defined for MIPS3 and below.
795   if (STI->hasMips32() || STI->hasMips4())
796     return false;
797 
798   return handleSlot([this](auto &I) -> bool { return TII->HasFPUDelaySlot(I); },
799                     [this](auto &IInSlot, auto &I) -> bool {
800                       return TII->SafeInFPUDelaySlot(IInSlot, I);
801                     });
802 }
803 
804 bool MipsBranchExpansion::handlePossibleLongBranch() {
805   if (STI->inMips16Mode() || !STI->enableLongBranchPass())
806     return false;
807 
808   if (SkipLongBranch)
809     return false;
810 
811   bool EverMadeChange = false, MadeChange = true;
812 
813   while (MadeChange) {
814     MadeChange = false;
815 
816     initMBBInfo();
817 
818     for (unsigned I = 0, E = MBBInfos.size(); I < E; ++I) {
819       MachineBasicBlock *MBB = MFp->getBlockNumbered(I);
820       // Search for MBB's branch instruction.
821       ReverseIter End = MBB->rend();
822       ReverseIter Br = getNonDebugInstr(MBB->rbegin(), End);
823 
824       if ((Br != End) && Br->isBranch() && !Br->isIndirectBranch() &&
825           (Br->isConditionalBranch() ||
826            (Br->isUnconditionalBranch() && IsPIC))) {
827         int64_t Offset = computeOffset(&*Br);
828 
829         if (STI->isTargetNaCl()) {
830           // The offset calculation does not include sandboxing instructions
831           // that will be added later in the MC layer.  Since at this point we
832           // don't know the exact amount of code that "sandboxing" will add, we
833           // conservatively estimate that code will not grow more than 100%.
834           Offset *= 2;
835         }
836 
837         if (ForceLongBranchFirstPass ||
838             !TII->isBranchOffsetInRange(Br->getOpcode(), Offset)) {
839           MBBInfos[I].Offset = Offset;
840           MBBInfos[I].Br = &*Br;
841         }
842       }
843     } // End for
844 
845     ForceLongBranchFirstPass = false;
846 
847     SmallVectorImpl<MBBInfo>::iterator I, E = MBBInfos.end();
848 
849     for (I = MBBInfos.begin(); I != E; ++I) {
850       // Skip if this MBB doesn't have a branch or the branch has already been
851       // converted to a long branch.
852       if (!I->Br)
853         continue;
854 
855       expandToLongBranch(*I);
856       ++LongBranches;
857       EverMadeChange = MadeChange = true;
858     }
859 
860     MFp->RenumberBlocks();
861   }
862 
863   return EverMadeChange;
864 }
865 
866 bool MipsBranchExpansion::runOnMachineFunction(MachineFunction &MF) {
867   const TargetMachine &TM = MF.getTarget();
868   IsPIC = TM.isPositionIndependent();
869   ABI = static_cast<const MipsTargetMachine &>(TM).getABI();
870   STI = &static_cast<const MipsSubtarget &>(MF.getSubtarget());
871   TII = static_cast<const MipsInstrInfo *>(STI->getInstrInfo());
872 
873   if (IsPIC && ABI.IsO32() &&
874       MF.getInfo<MipsFunctionInfo>()->globalBaseRegSet())
875     emitGPDisp(MF, TII);
876 
877   MFp = &MF;
878 
879   ForceLongBranchFirstPass = ForceLongBranch;
880   // Run these two at least once
881   bool longBranchChanged = handlePossibleLongBranch();
882   bool forbiddenSlotChanged = handleForbiddenSlot();
883   bool fpuDelaySlotChanged = handleFPUDelaySlot();
884 
885   bool Changed =
886       longBranchChanged || forbiddenSlotChanged || fpuDelaySlotChanged;
887 
888   // Then run them alternatively while there are changes
889   while (forbiddenSlotChanged) {
890     longBranchChanged = handlePossibleLongBranch();
891     fpuDelaySlotChanged = handleFPUDelaySlot();
892     if (!longBranchChanged && !fpuDelaySlotChanged)
893       break;
894     forbiddenSlotChanged = handleForbiddenSlot();
895   }
896 
897   return Changed;
898 }
899