LLVM 20.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 instuctions.
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
79#include "Mips.h"
80#include "MipsInstrInfo.h"
81#include "MipsMachineFunction.h"
82#include "MipsSubtarget.h"
83#include "MipsTargetMachine.h"
85#include "llvm/ADT/Statistic.h"
86#include "llvm/ADT/StringRef.h"
95#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
112static cl::opt<bool>
113 SkipLongBranch("skip-mips-long-branch", cl::init(false),
114 cl::desc("MIPS: Skip branch expansion pass."), cl::Hidden);
115
116static 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
121namespace {
122
123using Iter = MachineBasicBlock::iterator;
124using ReverseIter = MachineBasicBlock::reverse_iterator;
125
126struct MBBInfo {
127 uint64_t Size = 0;
128 bool HasLongBranch = false;
129 MachineInstr *Br = nullptr;
130 uint64_t Offset = 0;
131 MBBInfo() = default;
132};
133
134class MipsBranchExpansion : public MachineFunctionPass {
135public:
136 static char ID;
137
138 MipsBranchExpansion() : MachineFunctionPass(ID), ABI(MipsABIInfo::Unknown()) {
140 }
141
142 StringRef getPassName() const override {
143 return "Mips Branch Expansion Pass";
144 }
145
146 bool runOnMachineFunction(MachineFunction &F) override;
147
150 MachineFunctionProperties::Property::NoVRegs);
151 }
152
153private:
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,
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 handleLoadDelaySlot();
168 bool handlePossibleLongBranch();
169 bool handleMFLO();
170 template <typename Pred, typename Safe>
171 bool handleMFLOSlot(Pred Predicate, Safe SafeInSlot);
172
173 const MipsSubtarget *STI;
174 const MipsInstrInfo *TII;
175
176 MachineFunction *MFp;
178 bool IsPIC;
180 bool ForceLongBranchFirstPass = false;
181};
182
183} // end of anonymous namespace
184
185char MipsBranchExpansion::ID = 0;
186
187INITIALIZE_PASS(MipsBranchExpansion, DEBUG_TYPE,
188 "Expand out of range branch instructions and fix forbidden"
189 " slot hazards",
190 false, false)
191
192/// Returns a pass that clears pipeline hazards.
194 return new MipsBranchExpansion();
195}
196
197// Find the next real instruction from the current position in current basic
198// block.
199static Iter getNextMachineInstrInBB(Iter Position) {
200 Iter I = Position, E = Position->getParent()->end();
201 I = std::find_if_not(I, E,
202 [](const Iter &Insn) { return Insn->isTransient(); });
203
204 return I;
205}
206
207// Find the next real instruction from the current position, looking through
208// basic block boundaries.
209static std::pair<Iter, bool> getNextMachineInstr(Iter Position,
210 MachineBasicBlock *Parent) {
211 if (Position == Parent->end()) {
212 do {
213 MachineBasicBlock *Succ = Parent->getNextNode();
214 if (Succ != nullptr && Parent->isSuccessor(Succ)) {
215 Position = Succ->begin();
216 Parent = Succ;
217 } else {
218 return std::make_pair(Position, true);
219 }
220 } while (Parent->empty());
221 }
222
223 Iter Instr = getNextMachineInstrInBB(Position);
224 if (Instr == Parent->end()) {
225 return getNextMachineInstr(Instr, Parent);
226 }
227 return std::make_pair(Instr, false);
228}
229
230/// Iterate over list of Br's operands and search for a MachineBasicBlock
231/// operand.
233 for (unsigned I = 0, E = Br.getDesc().getNumOperands(); I < E; ++I) {
234 const MachineOperand &MO = Br.getOperand(I);
235
236 if (MO.isMBB())
237 return MO.getMBB();
238 }
239
240 llvm_unreachable("This instruction does not have an MBB operand.");
241}
242
243// Traverse the list of instructions backwards until a non-debug instruction is
244// found or it reaches E.
245static ReverseIter getNonDebugInstr(ReverseIter B, const ReverseIter &E) {
246 for (; B != E; ++B)
247 if (!B->isDebugInstr())
248 return B;
249
250 return E;
251}
252
253// Split MBB if it has two direct jumps/branches.
254void MipsBranchExpansion::splitMBB(MachineBasicBlock *MBB) {
255 ReverseIter End = MBB->rend();
256 ReverseIter LastBr = getNonDebugInstr(MBB->rbegin(), End);
257
258 // Return if MBB has no branch instructions.
259 if ((LastBr == End) ||
260 (!LastBr->isConditionalBranch() && !LastBr->isUnconditionalBranch()))
261 return;
262
263 ReverseIter FirstBr = getNonDebugInstr(std::next(LastBr), End);
264
265 // MBB has only one branch instruction if FirstBr is not a branch
266 // instruction.
267 if ((FirstBr == End) ||
268 (!FirstBr->isConditionalBranch() && !FirstBr->isUnconditionalBranch()))
269 return;
270
271 assert(!FirstBr->isIndirectBranch() && "Unexpected indirect branch found.");
272
273 // Create a new MBB. Move instructions in MBB to the newly created MBB.
274 MachineBasicBlock *NewMBB =
275 MFp->CreateMachineBasicBlock(MBB->getBasicBlock());
276
277 // Insert NewMBB and fix control flow.
278 MachineBasicBlock *Tgt = getTargetMBB(*FirstBr);
279 NewMBB->transferSuccessors(MBB);
280 if (Tgt != getTargetMBB(*LastBr))
281 NewMBB->removeSuccessor(Tgt, true);
282 MBB->addSuccessor(NewMBB);
283 MBB->addSuccessor(Tgt);
284 MFp->insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
285
286 NewMBB->splice(NewMBB->end(), MBB, LastBr.getReverse(), MBB->end());
287}
288
289// Fill MBBInfos.
290void MipsBranchExpansion::initMBBInfo() {
291 // Split the MBBs if they have two branches. Each basic block should have at
292 // most one branch after this loop is executed.
293 for (auto &MBB : *MFp)
294 splitMBB(&MBB);
295
296 MFp->RenumberBlocks();
297 MBBInfos.clear();
298 MBBInfos.resize(MFp->size());
299
300 for (unsigned I = 0, E = MBBInfos.size(); I < E; ++I) {
301 MachineBasicBlock *MBB = MFp->getBlockNumbered(I);
302
303 // Compute size of MBB.
304 for (MachineInstr &MI : MBB->instrs())
305 MBBInfos[I].Size += TII->getInstSizeInBytes(MI);
306 }
307}
308
309// Compute offset of branch in number of bytes.
310int64_t MipsBranchExpansion::computeOffset(const MachineInstr *Br) {
311 int64_t Offset = 0;
312 int ThisMBB = Br->getParent()->getNumber();
313 int TargetMBB = getTargetMBB(*Br)->getNumber();
314
315 // Compute offset of a forward branch.
316 if (ThisMBB < TargetMBB) {
317 for (int N = ThisMBB + 1; N < TargetMBB; ++N)
318 Offset += MBBInfos[N].Size;
319
320 return Offset + 4;
321 }
322
323 // Compute offset of a backward branch.
324 for (int N = ThisMBB; N >= TargetMBB; --N)
325 Offset += MBBInfos[N].Size;
326
327 return -Offset + 4;
328}
329
330// Returns the distance in bytes up until MBB
331uint64_t MipsBranchExpansion::computeOffsetFromTheBeginning(int MBB) {
332 uint64_t Offset = 0;
333 for (int N = 0; N < MBB; ++N)
334 Offset += MBBInfos[N].Size;
335 return Offset;
336}
337
338// Replace Br with a branch which has the opposite condition code and a
339// MachineBasicBlock operand MBBOpnd.
340void MipsBranchExpansion::replaceBranch(MachineBasicBlock &MBB, Iter Br,
341 const DebugLoc &DL,
342 MachineBasicBlock *MBBOpnd) {
343 unsigned NewOpc = TII->getOppositeBranchOpc(Br->getOpcode());
344 const MCInstrDesc &NewDesc = TII->get(NewOpc);
345
346 MachineInstrBuilder MIB = BuildMI(MBB, Br, DL, NewDesc);
347
348 for (unsigned I = 0, E = Br->getDesc().getNumOperands(); I < E; ++I) {
349 MachineOperand &MO = Br->getOperand(I);
350
351 switch (MO.getType()) {
353 MIB.addReg(MO.getReg());
354 break;
356 // Octeon BBIT family of branch has an immediate operand
357 // (e.g. BBIT0 $v0, 3, %bb.1).
358 if (!TII->isBranchWithImm(Br->getOpcode()))
359 llvm_unreachable("Unexpected immediate in branch instruction");
360 MIB.addImm(MO.getImm());
361 break;
363 MIB.addMBB(MBBOpnd);
364 break;
365 default:
366 llvm_unreachable("Unexpected operand type in branch instruction");
367 }
368 }
369
370 if (Br->hasDelaySlot()) {
371 // Bundle the instruction in the delay slot to the newly created branch
372 // and erase the original branch.
373 assert(Br->isBundledWithSucc());
374 MachineBasicBlock::instr_iterator II = Br.getInstrIterator();
375 MIBundleBuilder(&*MIB).append((++II)->removeFromBundle());
376 }
377 Br->eraseFromParent();
378}
379
380bool MipsBranchExpansion::buildProperJumpMI(MachineBasicBlock *MBB,
382 DebugLoc DL) {
383 bool HasR6 = ABI.IsN64() ? STI->hasMips64r6() : STI->hasMips32r6();
384 bool AddImm = HasR6 && !STI->useIndirectJumpsHazard();
385
386 unsigned JR = ABI.IsN64() ? Mips::JR64 : Mips::JR;
387 unsigned JIC = ABI.IsN64() ? Mips::JIC64 : Mips::JIC;
388 unsigned JR_HB = ABI.IsN64() ? Mips::JR_HB64 : Mips::JR_HB;
389 unsigned JR_HB_R6 = ABI.IsN64() ? Mips::JR_HB64_R6 : Mips::JR_HB_R6;
390
391 unsigned JumpOp;
392 if (STI->useIndirectJumpsHazard())
393 JumpOp = HasR6 ? JR_HB_R6 : JR_HB;
394 else
395 JumpOp = HasR6 ? JIC : JR;
396
397 if (JumpOp == Mips::JIC && STI->inMicroMipsMode())
398 JumpOp = Mips::JIC_MMR6;
399
400 unsigned ATReg = ABI.IsN64() ? Mips::AT_64 : Mips::AT;
402 BuildMI(*MBB, Pos, DL, TII->get(JumpOp)).addReg(ATReg);
403 if (AddImm)
404 Instr.addImm(0);
405
406 return !AddImm;
407}
408
409// Expand branch instructions to long branches.
410// TODO: This function has to be fixed for beqz16 and bnez16, because it
411// currently assumes that all branches have 16-bit offsets, and will produce
412// wrong code if branches whose allowed offsets are [-128, -126, ..., 126]
413// are present.
414void MipsBranchExpansion::expandToLongBranch(MBBInfo &I) {
416 MachineBasicBlock *MBB = I.Br->getParent(), *TgtMBB = getTargetMBB(*I.Br);
417 DebugLoc DL = I.Br->getDebugLoc();
418 const BasicBlock *BB = MBB->getBasicBlock();
420 MachineBasicBlock *LongBrMBB = MFp->CreateMachineBasicBlock(BB);
421
422 MFp->insert(FallThroughMBB, LongBrMBB);
423 MBB->replaceSuccessor(TgtMBB, LongBrMBB);
424
425 if (IsPIC) {
426 MachineBasicBlock *BalTgtMBB = MFp->CreateMachineBasicBlock(BB);
427 MFp->insert(FallThroughMBB, BalTgtMBB);
428 LongBrMBB->addSuccessor(BalTgtMBB);
429 BalTgtMBB->addSuccessor(TgtMBB);
430
431 // We must select between the MIPS32r6/MIPS64r6 BALC (which is a normal
432 // instruction) and the pre-MIPS32r6/MIPS64r6 definition (which is an
433 // pseudo-instruction wrapping BGEZAL).
434 const unsigned BalOp =
435 STI->hasMips32r6()
436 ? STI->inMicroMipsMode() ? Mips::BALC_MMR6 : Mips::BALC
437 : STI->inMicroMipsMode() ? Mips::BAL_BR_MM : Mips::BAL_BR;
438
439 if (!ABI.IsN64()) {
440 // Pre R6:
441 // $longbr:
442 // addiu $sp, $sp, -8
443 // sw $ra, 0($sp)
444 // lui $at, %hi($tgt - $baltgt)
445 // bal $baltgt
446 // addiu $at, $at, %lo($tgt - $baltgt)
447 // $baltgt:
448 // addu $at, $ra, $at
449 // lw $ra, 0($sp)
450 // jr $at
451 // addiu $sp, $sp, 8
452 // $fallthrough:
453 //
454
455 // R6:
456 // $longbr:
457 // addiu $sp, $sp, -8
458 // sw $ra, 0($sp)
459 // lui $at, %hi($tgt - $baltgt)
460 // addiu $at, $at, %lo($tgt - $baltgt)
461 // balc $baltgt
462 // $baltgt:
463 // addu $at, $ra, $at
464 // lw $ra, 0($sp)
465 // addiu $sp, $sp, 8
466 // jic $at, 0
467 // $fallthrough:
468
469 Pos = LongBrMBB->begin();
470
471 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
472 .addReg(Mips::SP)
473 .addImm(-8);
474 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SW))
475 .addReg(Mips::RA)
476 .addReg(Mips::SP)
477 .addImm(0);
478
479 // LUi and ADDiu instructions create 32-bit offset of the target basic
480 // block from the target of BAL(C) instruction. We cannot use immediate
481 // value for this offset because it cannot be determined accurately when
482 // the program has inline assembly statements. We therefore use the
483 // relocation expressions %hi($tgt-$baltgt) and %lo($tgt-$baltgt) which
484 // are resolved during the fixup, so the values will always be correct.
485 //
486 // Since we cannot create %hi($tgt-$baltgt) and %lo($tgt-$baltgt)
487 // expressions at this point (it is possible only at the MC layer),
488 // we replace LUi and ADDiu with pseudo instructions
489 // LONG_BRANCH_LUi and LONG_BRANCH_ADDiu, and add both basic
490 // blocks as operands to these instructions. When lowering these pseudo
491 // instructions to LUi and ADDiu in the MC layer, we will create
492 // %hi($tgt-$baltgt) and %lo($tgt-$baltgt) expressions and add them as
493 // operands to lowered instructions.
494
495 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi), Mips::AT)
496 .addMBB(TgtMBB, MipsII::MO_ABS_HI)
497 .addMBB(BalTgtMBB);
498
499 MachineInstrBuilder BalInstr =
500 BuildMI(*MFp, DL, TII->get(BalOp)).addMBB(BalTgtMBB);
501 MachineInstrBuilder ADDiuInstr =
502 BuildMI(*MFp, DL, TII->get(Mips::LONG_BRANCH_ADDiu), Mips::AT)
503 .addReg(Mips::AT)
504 .addMBB(TgtMBB, MipsII::MO_ABS_LO)
505 .addMBB(BalTgtMBB);
506 if (STI->hasMips32r6()) {
507 LongBrMBB->insert(Pos, ADDiuInstr);
508 LongBrMBB->insert(Pos, BalInstr);
509 } else {
510 LongBrMBB->insert(Pos, BalInstr);
511 LongBrMBB->insert(Pos, ADDiuInstr);
512 LongBrMBB->rbegin()->bundleWithPred();
513 }
514
515 Pos = BalTgtMBB->begin();
516
517 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDu), Mips::AT)
518 .addReg(Mips::RA)
519 .addReg(Mips::AT);
520 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LW), Mips::RA)
521 .addReg(Mips::SP)
522 .addImm(0);
523 if (STI->isTargetNaCl())
524 // Bundle-align the target of indirect branch JR.
525 TgtMBB->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
526
527 // In NaCl, modifying the sp is not allowed in branch delay slot.
528 // For MIPS32R6, we can skip using a delay slot branch.
529 bool hasDelaySlot = buildProperJumpMI(BalTgtMBB, Pos, DL);
530
531 if (STI->isTargetNaCl() || !hasDelaySlot) {
532 BuildMI(*BalTgtMBB, std::prev(Pos), DL, TII->get(Mips::ADDiu), Mips::SP)
533 .addReg(Mips::SP)
534 .addImm(8);
535 }
536 if (hasDelaySlot) {
537 if (STI->isTargetNaCl()) {
538 TII->insertNop(*BalTgtMBB, Pos, DL);
539 } else {
540 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
541 .addReg(Mips::SP)
542 .addImm(8);
543 }
544 BalTgtMBB->rbegin()->bundleWithPred();
545 }
546 } else {
547 // Pre 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 // bal $baltgt
554 // daddiu $at, $at, %lo($tgt - $baltgt)
555 // $baltgt:
556 // daddu $at, $ra, $at
557 // ld $ra, 0($sp)
558 // jr64 $at
559 // daddiu $sp, $sp, 16
560 // $fallthrough:
561
562 // R6:
563 // $longbr:
564 // daddiu $sp, $sp, -16
565 // sd $ra, 0($sp)
566 // daddiu $at, $zero, %hi($tgt - $baltgt)
567 // dsll $at, $at, 16
568 // daddiu $at, $at, %lo($tgt - $baltgt)
569 // balc $baltgt
570 // $baltgt:
571 // daddu $at, $ra, $at
572 // ld $ra, 0($sp)
573 // daddiu $sp, $sp, 16
574 // jic $at, 0
575 // $fallthrough:
576
577 // We assume the branch is within-function, and that offset is within
578 // +/- 2GB. High 32 bits will therefore always be zero.
579
580 // Note that this will work even if the offset is negative, because
581 // of the +1 modification that's added in that case. For example, if the
582 // offset is -1MB (0xFFFFFFFFFFF00000), the computation for %higher is
583 //
584 // 0xFFFFFFFFFFF00000 + 0x80008000 = 0x000000007FF08000
585 //
586 // and the bits [47:32] are zero. For %highest
587 //
588 // 0xFFFFFFFFFFF00000 + 0x800080008000 = 0x000080007FF08000
589 //
590 // and the bits [63:48] are zero.
591
592 Pos = LongBrMBB->begin();
593
594 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DADDiu), Mips::SP_64)
595 .addReg(Mips::SP_64)
596 .addImm(-16);
597 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SD))
598 .addReg(Mips::RA_64)
599 .addReg(Mips::SP_64)
600 .addImm(0);
601 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu),
602 Mips::AT_64)
603 .addReg(Mips::ZERO_64)
604 .addMBB(TgtMBB, MipsII::MO_ABS_HI)
605 .addMBB(BalTgtMBB);
606 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::AT_64)
607 .addReg(Mips::AT_64)
608 .addImm(16);
609
610 MachineInstrBuilder BalInstr =
611 BuildMI(*MFp, DL, TII->get(BalOp)).addMBB(BalTgtMBB);
612 MachineInstrBuilder DADDiuInstr =
613 BuildMI(*MFp, DL, TII->get(Mips::LONG_BRANCH_DADDiu), Mips::AT_64)
614 .addReg(Mips::AT_64)
615 .addMBB(TgtMBB, MipsII::MO_ABS_LO)
616 .addMBB(BalTgtMBB);
617 if (STI->hasMips32r6()) {
618 LongBrMBB->insert(Pos, DADDiuInstr);
619 LongBrMBB->insert(Pos, BalInstr);
620 } else {
621 LongBrMBB->insert(Pos, BalInstr);
622 LongBrMBB->insert(Pos, DADDiuInstr);
623 LongBrMBB->rbegin()->bundleWithPred();
624 }
625
626 Pos = BalTgtMBB->begin();
627
628 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::DADDu), Mips::AT_64)
629 .addReg(Mips::RA_64)
630 .addReg(Mips::AT_64);
631 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LD), Mips::RA_64)
632 .addReg(Mips::SP_64)
633 .addImm(0);
634
635 bool hasDelaySlot = buildProperJumpMI(BalTgtMBB, Pos, DL);
636 // If there is no delay slot, Insert stack adjustment before
637 if (!hasDelaySlot) {
638 BuildMI(*BalTgtMBB, std::prev(Pos), DL, TII->get(Mips::DADDiu),
639 Mips::SP_64)
640 .addReg(Mips::SP_64)
641 .addImm(16);
642 } else {
643 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::DADDiu), Mips::SP_64)
644 .addReg(Mips::SP_64)
645 .addImm(16);
646 BalTgtMBB->rbegin()->bundleWithPred();
647 }
648 }
649 } else { // Not PIC
650 Pos = LongBrMBB->begin();
651 LongBrMBB->addSuccessor(TgtMBB);
652
653 // Compute the position of the potentiall jump instruction (basic blocks
654 // before + 4 for the instruction)
655 uint64_t JOffset = computeOffsetFromTheBeginning(MBB->getNumber()) +
656 MBBInfos[MBB->getNumber()].Size + 4;
657 uint64_t TgtMBBOffset = computeOffsetFromTheBeginning(TgtMBB->getNumber());
658 // If it's a forward jump, then TgtMBBOffset will be shifted by two
659 // instructions
660 if (JOffset < TgtMBBOffset)
661 TgtMBBOffset += 2 * 4;
662 // Compare 4 upper bits to check if it's the same segment
663 bool SameSegmentJump = JOffset >> 28 == TgtMBBOffset >> 28;
664
665 if (STI->hasMips32r6() && TII->isBranchOffsetInRange(Mips::BC, I.Offset)) {
666 // R6:
667 // $longbr:
668 // bc $tgt
669 // $fallthrough:
670 //
671 BuildMI(*LongBrMBB, Pos, DL,
672 TII->get(STI->inMicroMipsMode() ? Mips::BC_MMR6 : Mips::BC))
673 .addMBB(TgtMBB);
674 } else if (SameSegmentJump) {
675 // Pre R6:
676 // $longbr:
677 // j $tgt
678 // nop
679 // $fallthrough:
680 //
681 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::J)).addMBB(TgtMBB);
682 TII->insertNop(*LongBrMBB, Pos, DL)->bundleWithPred();
683 } else {
684 // At this point, offset where we need to branch does not fit into
685 // immediate field of the branch instruction and is not in the same
686 // segment as jump instruction. Therefore we will break it into couple
687 // instructions, where we first load the offset into register, and then we
688 // do branch register.
689 if (ABI.IsN64()) {
690 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi2Op_64),
691 Mips::AT_64)
692 .addMBB(TgtMBB, MipsII::MO_HIGHEST);
693 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
694 Mips::AT_64)
695 .addReg(Mips::AT_64)
696 .addMBB(TgtMBB, MipsII::MO_HIGHER);
697 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::AT_64)
698 .addReg(Mips::AT_64)
699 .addImm(16);
700 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
701 Mips::AT_64)
702 .addReg(Mips::AT_64)
703 .addMBB(TgtMBB, MipsII::MO_ABS_HI);
704 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::AT_64)
705 .addReg(Mips::AT_64)
706 .addImm(16);
707 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
708 Mips::AT_64)
709 .addReg(Mips::AT_64)
710 .addMBB(TgtMBB, MipsII::MO_ABS_LO);
711 } else {
712 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi2Op),
713 Mips::AT)
714 .addMBB(TgtMBB, MipsII::MO_ABS_HI);
715 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_ADDiu2Op),
716 Mips::AT)
717 .addReg(Mips::AT)
718 .addMBB(TgtMBB, MipsII::MO_ABS_LO);
719 }
720 buildProperJumpMI(LongBrMBB, Pos, DL);
721 }
722 }
723
724 if (I.Br->isUnconditionalBranch()) {
725 // Change branch destination.
726 assert(I.Br->getDesc().getNumOperands() == 1);
727 I.Br->removeOperand(0);
728 I.Br->addOperand(MachineOperand::CreateMBB(LongBrMBB));
729 } else
730 // Change branch destination and reverse condition.
731 replaceBranch(*MBB, I.Br, DL, &*FallThroughMBB);
732}
733
735 MachineBasicBlock &MBB = F.front();
738 BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::V0)
740 BuildMI(MBB, I, DL, TII->get(Mips::ADDiu), Mips::V0)
741 .addReg(Mips::V0)
743 MBB.removeLiveIn(Mips::V0);
744}
745
746template <typename Pred, typename Safe>
747bool MipsBranchExpansion::handleMFLOSlot(Pred Predicate, Safe SafeInSlot) {
748 bool Changed = false;
749 bool hasPendingMFLO = false;
750
751 for (MachineFunction::iterator FI = MFp->begin(); FI != MFp->end(); ++FI) {
752 for (Iter I = FI->begin(); I != FI->end(); ++I) {
753
754 if (!Predicate(*I) && !hasPendingMFLO) {
755 continue;
756 }
757
758 Iter IInSlot;
759 bool LastInstInFunction =
760 std::next(I) == FI->end() && std::next(FI) == MFp->end();
761 // We need process several situations:
762 // mflo is last instruction, do not process;
763 // mflo + div, add two nop between them;
764 // mflo + none-div + none-div, do not process;
765 // mflo + none-div + div, add nop between none-div and div.
766 if (!LastInstInFunction) {
767 std::pair<Iter, bool> Res = getNextMachineInstr(std::next(I), &*FI);
768 LastInstInFunction |= Res.second;
769 IInSlot = Res.first;
770 if (!SafeInSlot(*IInSlot, *I)) {
771 Changed = true;
772 TII->insertNop(*(I->getParent()), std::next(I), I->getDebugLoc())
773 ->bundleWithPred();
774 NumInsertedNops++;
775 if (IsMFLOMFHI(I->getOpcode())) {
776 TII->insertNop(*(I->getParent()), std::next(I), I->getDebugLoc())
777 ->bundleWithPred();
778 NumInsertedNops++;
779 }
780 if (hasPendingMFLO)
781 hasPendingMFLO = false;
782 } else if (hasPendingMFLO)
783 hasPendingMFLO = false;
784 else if (IsMFLOMFHI(I->getOpcode()))
785 hasPendingMFLO = true;
786 }
787 }
788 }
789
790 return Changed;
791}
792
793template <typename Pred, typename Safe>
794bool MipsBranchExpansion::handleSlot(Pred Predicate, Safe SafeInSlot) {
795 bool Changed = false;
796
797 for (MachineFunction::iterator FI = MFp->begin(); FI != MFp->end(); ++FI) {
798 for (Iter I = FI->begin(); I != FI->end(); ++I) {
799
800 // Delay slot hazard handling. Use lookahead over state.
801 if (!Predicate(*I))
802 continue;
803
804 Iter IInSlot;
805 bool LastInstInFunction =
806 std::next(I) == FI->end() && std::next(FI) == MFp->end();
807 if (!LastInstInFunction) {
808 std::pair<Iter, bool> Res = getNextMachineInstr(std::next(I), &*FI);
809 LastInstInFunction |= Res.second;
810 IInSlot = Res.first;
811 }
812
813 if (LastInstInFunction || !SafeInSlot(*IInSlot, *I)) {
814 MachineBasicBlock::instr_iterator Iit = I->getIterator();
815 if (std::next(Iit) == FI->end() ||
816 std::next(Iit)->getOpcode() != Mips::NOP) {
817 Changed = true;
818 TII->insertNop(*(I->getParent()), std::next(I), I->getDebugLoc())
819 ->bundleWithPred();
820 NumInsertedNops++;
821 }
822 }
823 }
824 }
825
826 return Changed;
827}
828
829bool MipsBranchExpansion::handleMFLO() {
830 // mips1-4 require a minimum of 2 instructions between a mflo/mfhi
831 // and the next mul/div instruction.
832 if (STI->hasMips32() || STI->hasMips5())
833 return false;
834
835 return handleMFLOSlot(
836 [this](auto &I) -> bool { return TII->IsMfloOrMfhi(I); },
837 [this](auto &IInSlot, auto &I) -> bool {
838 return TII->SafeAfterMflo(IInSlot);
839 });
840}
841
842bool MipsBranchExpansion::handleForbiddenSlot() {
843 // Forbidden slot hazards are only defined for MIPSR6 but not microMIPSR6.
844 if (!STI->hasMips32r6() || STI->inMicroMipsMode())
845 return false;
846
847 return handleSlot(
848 [this](auto &I) -> bool { return TII->HasForbiddenSlot(I); },
849 [this](auto &IInSlot, auto &I) -> bool {
850 return TII->SafeInForbiddenSlot(IInSlot);
851 });
852}
853
854bool MipsBranchExpansion::handleFPUDelaySlot() {
855 // FPU delay slots are only defined for MIPS3 and below.
856 if (STI->hasMips32() || STI->hasMips4())
857 return false;
858
859 return handleSlot([this](auto &I) -> bool { return TII->HasFPUDelaySlot(I); },
860 [this](auto &IInSlot, auto &I) -> bool {
861 return TII->SafeInFPUDelaySlot(IInSlot, I);
862 });
863}
864
865bool MipsBranchExpansion::handleLoadDelaySlot() {
866 // Load delay slot hazards are only for MIPS1.
867 if (STI->hasMips2())
868 return false;
869
870 return handleSlot(
871 [this](auto &I) -> bool { return TII->HasLoadDelaySlot(I); },
872 [this](auto &IInSlot, auto &I) -> bool {
873 return TII->SafeInLoadDelaySlot(IInSlot, I);
874 });
875}
876
877bool MipsBranchExpansion::handlePossibleLongBranch() {
878 if (STI->inMips16Mode() || !STI->enableLongBranchPass())
879 return false;
880
881 if (SkipLongBranch)
882 return false;
883
884 bool EverMadeChange = false, MadeChange = true;
885
886 while (MadeChange) {
887 MadeChange = false;
888
889 initMBBInfo();
890
891 for (unsigned I = 0, E = MBBInfos.size(); I < E; ++I) {
892 MachineBasicBlock *MBB = MFp->getBlockNumbered(I);
893 // Search for MBB's branch instruction.
894 ReverseIter End = MBB->rend();
895 ReverseIter Br = getNonDebugInstr(MBB->rbegin(), End);
896
897 if ((Br != End) && Br->isBranch() && !Br->isIndirectBranch() &&
898 (Br->isConditionalBranch() ||
899 (Br->isUnconditionalBranch() && IsPIC))) {
900 int64_t Offset = computeOffset(&*Br);
901
902 if (STI->isTargetNaCl()) {
903 // The offset calculation does not include sandboxing instructions
904 // that will be added later in the MC layer. Since at this point we
905 // don't know the exact amount of code that "sandboxing" will add, we
906 // conservatively estimate that code will not grow more than 100%.
907 Offset *= 2;
908 }
909
910 if (ForceLongBranchFirstPass ||
911 !TII->isBranchOffsetInRange(Br->getOpcode(), Offset)) {
912 MBBInfos[I].Offset = Offset;
913 MBBInfos[I].Br = &*Br;
914 }
915 }
916 } // End for
917
918 ForceLongBranchFirstPass = false;
919
920 SmallVectorImpl<MBBInfo>::iterator I, E = MBBInfos.end();
921
922 for (I = MBBInfos.begin(); I != E; ++I) {
923 // Skip if this MBB doesn't have a branch or the branch has already been
924 // converted to a long branch.
925 if (!I->Br)
926 continue;
927
928 expandToLongBranch(*I);
929 ++LongBranches;
930 EverMadeChange = MadeChange = true;
931 }
932
933 MFp->RenumberBlocks();
934 }
935
936 return EverMadeChange;
937}
938
939bool MipsBranchExpansion::runOnMachineFunction(MachineFunction &MF) {
940 const TargetMachine &TM = MF.getTarget();
941 IsPIC = TM.isPositionIndependent();
942 ABI = static_cast<const MipsTargetMachine &>(TM).getABI();
943 STI = &MF.getSubtarget<MipsSubtarget>();
944 TII = static_cast<const MipsInstrInfo *>(STI->getInstrInfo());
945
946 if (IsPIC && ABI.IsO32() &&
947 MF.getInfo<MipsFunctionInfo>()->globalBaseRegSet())
948 emitGPDisp(MF, TII);
949
950 MFp = &MF;
951
952 ForceLongBranchFirstPass = ForceLongBranch;
953 // Run these at least once.
954 bool longBranchChanged = handlePossibleLongBranch();
955 bool forbiddenSlotChanged = handleForbiddenSlot();
956 bool fpuDelaySlotChanged = handleFPUDelaySlot();
957 bool loadDelaySlotChanged = handleLoadDelaySlot();
958 bool MfloChanged = handleMFLO();
959
960 bool Changed = longBranchChanged || forbiddenSlotChanged ||
961 fpuDelaySlotChanged || loadDelaySlotChanged || MfloChanged;
962
963 // Then run them alternatively while there are changes.
964 while (forbiddenSlotChanged) {
965 longBranchChanged = handlePossibleLongBranch();
966 fpuDelaySlotChanged = handleFPUDelaySlot();
967 loadDelaySlotChanged = handleLoadDelaySlot();
968 MfloChanged = handleMFLO();
969 if (!longBranchChanged && !fpuDelaySlotChanged && !loadDelaySlotChanged &&
970 !MfloChanged)
971 break;
972 forbiddenSlotChanged = handleForbiddenSlot();
973 }
974
975 return Changed;
976}
SmallVector< AArch64_IMM::ImmInsnModel, 4 > Insn
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static std::pair< Iter, bool > getNextMachineInstr(Iter Position, MachineBasicBlock *Parent)
static cl::opt< bool > ForceLongBranch("force-mips-long-branch", cl::init(false), cl::desc("MIPS: Expand all branches to long format."), cl::Hidden)
static cl::opt< bool > SkipLongBranch("skip-mips-long-branch", cl::init(false), cl::desc("MIPS: Skip branch expansion pass."), cl::Hidden)
static MachineBasicBlock * getTargetMBB(const MachineInstr &Br)
Iterate over list of Br's operands and search for a MachineBasicBlock operand.
#define DEBUG_TYPE
static void emitGPDisp(MachineFunction &F, const MipsInstrInfo *TII)
static ReverseIter getNonDebugInstr(ReverseIter B, const ReverseIter &E)
static Iter getNextMachineInstrInBB(Iter Position)
#define IsMFLOMFHI(instr)
Definition: Mips.h:20
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:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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:166
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
A debug info location.
Definition: DebugLoc.h:33
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:198
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:237
Helper class for constructing bundles of MachineInstrs.
MIBundleBuilder & append(MachineInstr *MI)
Insert MI into MBB by appending it to the instructions in the bundle.
reverse_iterator rend()
void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
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.
void removeLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Remove the specified register from the live in set.
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
Instructions::iterator instr_iterator
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
reverse_iterator rbegin()
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...
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
virtual MachineFunctionProperties getRequiredProperties() const
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
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...
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 & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
Definition: MachineInstr.h:69
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:347
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:572
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:585
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.
MipsFunctionInfo - This class is derived from MachineFunction private Mips target-specific informatio...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
typename SuperClass::iterator iterator
Definition: SmallVector.h:577
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:353
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ MO_ABS_HI
MO_ABS_HI/LO - Represents the hi or low part of an absolute symbol address.
Definition: MipsBaseInfo.h:52
@ MO_HIGHER
MO_HIGHER/HIGHEST - Represents the highest or higher half word of a 64-bit symbol address.
Definition: MipsBaseInfo.h:85
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
Definition: PPCPredicates.h:26
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
NodeAddr< InstrNode * > Instr
Definition: RDFGraph.h:389
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void initializeMipsBranchExpansionPass(PassRegistry &)
FunctionPass * createMipsBranchExpansion()
static const Align MIPS_NACL_BUNDLE_ALIGN
Definition: MipsMCNaCl.h:18
#define N