LLVM 24.0.0git
MipsConstantIslandPass.cpp
Go to the documentation of this file.
1//===- MipsConstantIslandPass.cpp - Emit Pc Relative loads ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass is used to make Pc relative loads of constants.
10// For now, only Mips16 will use this.
11//
12// Loading constants inline is expensive on Mips16 and it's in general better
13// to place the constant nearby in code space and then it can be loaded with a
14// simple 16 bit load instruction.
15//
16// The constants can be not just numbers but addresses of functions and labels.
17// This can be particularly helpful in static relocation mode for embedded
18// non-linux targets.
19//
20//===----------------------------------------------------------------------===//
21
22#include "Mips.h"
23#include "Mips16InstrInfo.h"
24#include "MipsMachineFunction.h"
25#include "MipsSubtarget.h"
26#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringRef.h"
40#include "llvm/Config/llvm-config.h"
41#include "llvm/IR/Analysis.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DebugLoc.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/Type.h"
48#include "llvm/Support/Debug.h"
50#include "llvm/Support/Format.h"
52#include <cassert>
53#include <cstdint>
54#include <iterator>
55#include <vector>
56
57using namespace llvm;
58
59#define DEBUG_TYPE "mips-constant-islands"
60
61STATISTIC(NumCPEs, "Number of constpool entries");
62STATISTIC(NumSplit, "Number of uncond branches inserted");
63STATISTIC(NumCBrFixed, "Number of cond branches fixed");
64STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
65
66static unsigned int branchTargetOperand(MachineInstr *MI) {
67 switch (MI->getOpcode()) {
68 case Mips::Bimm16:
69 case Mips::BimmX16:
70 case Mips::Bteqz16:
71 case Mips::BteqzX16:
72 case Mips::Btnez16:
73 case Mips::BtnezX16:
74 case Mips::JalB16:
75 return 0;
76 case Mips::BeqzRxImm16:
77 case Mips::BeqzRxImmX16:
78 case Mips::BnezRxImm16:
79 case Mips::BnezRxImmX16:
80 return 1;
81 }
82 llvm_unreachable("Unknown branch type");
83}
84
85static unsigned int longformBranchOpcode(unsigned int Opcode) {
86 switch (Opcode) {
87 case Mips::Bimm16:
88 case Mips::BimmX16:
89 return Mips::BimmX16;
90 case Mips::Bteqz16:
91 case Mips::BteqzX16:
92 return Mips::BteqzX16;
93 case Mips::Btnez16:
94 case Mips::BtnezX16:
95 return Mips::BtnezX16;
96 case Mips::JalB16:
97 return Mips::JalB16;
98 case Mips::BeqzRxImm16:
99 case Mips::BeqzRxImmX16:
100 return Mips::BeqzRxImmX16;
101 case Mips::BnezRxImm16:
102 case Mips::BnezRxImmX16:
103 return Mips::BnezRxImmX16;
104 }
105 llvm_unreachable("Unknown branch type");
106}
107
108// FIXME: need to go through this whole constant islands port and check
109// the math for branch ranges and clean this up and make some functions
110// to calculate things that are done many times identically.
111// Need to refactor some of the code to call this routine.
112static unsigned int branchMaxOffsets(unsigned int Opcode) {
113 unsigned Bits, Scale;
114 switch (Opcode) {
115 case Mips::Bimm16:
116 Bits = 11;
117 Scale = 2;
118 break;
119 case Mips::BimmX16:
120 Bits = 16;
121 Scale = 2;
122 break;
123 case Mips::BeqzRxImm16:
124 Bits = 8;
125 Scale = 2;
126 break;
127 case Mips::BeqzRxImmX16:
128 Bits = 16;
129 Scale = 2;
130 break;
131 case Mips::BnezRxImm16:
132 Bits = 8;
133 Scale = 2;
134 break;
135 case Mips::BnezRxImmX16:
136 Bits = 16;
137 Scale = 2;
138 break;
139 case Mips::Bteqz16:
140 Bits = 8;
141 Scale = 2;
142 break;
143 case Mips::BteqzX16:
144 Bits = 16;
145 Scale = 2;
146 break;
147 case Mips::Btnez16:
148 Bits = 8;
149 Scale = 2;
150 break;
151 case Mips::BtnezX16:
152 Bits = 16;
153 Scale = 2;
154 break;
155 default:
156 llvm_unreachable("Unknown branch type");
157 }
158 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
159 return MaxOffs;
160}
161
162namespace {
163
164 using Iter = MachineBasicBlock::iterator;
165 using ReverseIter = MachineBasicBlock::reverse_iterator;
166
167 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
168 /// requires constant pool entries to be scattered among the instructions
169 /// inside a function. To do this, it completely ignores the normal LLVM
170 /// constant pool; instead, it places constants wherever it feels like with
171 /// special instructions.
172 ///
173 /// The terminology used in this pass includes:
174 /// Islands - Clumps of constants placed in the function.
175 /// Water - Potential places where an island could be formed.
176 /// CPE - A constant pool entry that has been placed somewhere, which
177 /// tracks a list of users.
178
179 class MipsConstantIslandLegacy : public MachineFunctionPass {
180 public:
181 static char ID;
182
183 MipsConstantIslandLegacy() : MachineFunctionPass(ID) {}
184
185 StringRef getPassName() const override { return "Mips Constant Islands"; }
186
187 bool runOnMachineFunction(MachineFunction &F) override;
188
189 MachineFunctionProperties getRequiredProperties() const override {
190 return MachineFunctionProperties().setNoVRegs();
191 }
192 };
193
194 class MipsConstantIslandImpl {
195 /// BasicBlockInfo - Information about the offset and size of a single
196 /// basic block.
197 struct BasicBlockInfo {
198 /// Offset - Distance from the beginning of the function to the beginning
199 /// of this basic block.
200 ///
201 /// Offsets are computed assuming worst case padding before an aligned
202 /// block. This means that subtracting basic block offsets always gives a
203 /// conservative estimate of the real distance which may be smaller.
204 ///
205 /// Because worst case padding is used, the computed offset of an aligned
206 /// block may not actually be aligned.
207 unsigned Offset = 0;
208
209 /// Size - Size of the basic block in bytes. If the block contains
210 /// inline assembly, this is a worst case estimate.
211 ///
212 /// The size does not include any alignment padding whether from the
213 /// beginning of the block, or from an aligned jump table at the end.
214 unsigned Size = 0;
215
216 BasicBlockInfo() = default;
217
218 unsigned postOffset() const { return Offset + Size; }
219 };
220
221 std::vector<BasicBlockInfo> BBInfo;
222
223 /// WaterList - A sorted list of basic blocks where islands could be placed
224 /// (i.e. blocks that don't fall through to the following block, due
225 /// to a return, unreachable, or unconditional branch).
226 std::vector<MachineBasicBlock*> WaterList;
227
228 /// NewWaterList - The subset of WaterList that was created since the
229 /// previous iteration by inserting unconditional branches.
230 SmallPtrSet<MachineBasicBlock *, 4> NewWaterList;
231
232 using water_iterator = std::vector<MachineBasicBlock *>::iterator;
233
234 /// CPUser - One user of a constant pool, keeping the machine instruction
235 /// pointer, the constant pool being referenced, and the max displacement
236 /// allowed from the instruction to the CP. The HighWaterMark records the
237 /// highest basic block where a new CPEntry can be placed. To ensure this
238 /// pass terminates, the CP entries are initially placed at the end of the
239 /// function and then move monotonically to lower addresses. The
240 /// exception to this rule is when the current CP entry for a particular
241 /// CPUser is out of range, but there is another CP entry for the same
242 /// constant value in range. We want to use the existing in-range CP
243 /// entry, but if it later moves out of range, the search for new water
244 /// should resume where it left off. The HighWaterMark is used to record
245 /// that point.
246 struct CPUser {
247 MachineInstr *MI;
248 MachineInstr *CPEMI;
249 MachineBasicBlock *HighWaterMark;
250
251 private:
252 unsigned MaxDisp;
253 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
254 // with different displacements
255 unsigned LongFormOpcode;
256
257 public:
258 bool NegOk;
259
260 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
261 bool neg,
262 unsigned longformmaxdisp, unsigned longformopcode)
263 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
264 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
265 NegOk(neg){
266 HighWaterMark = CPEMI->getParent();
267 }
268
269 /// getMaxDisp - Returns the maximum displacement supported by MI.
270 unsigned getMaxDisp() const { return MaxDisp; }
271
272 void setMaxDisp(unsigned val) {
273 MaxDisp = val;
274 }
275
276 unsigned getLongFormMaxDisp() const {
277 return LongFormMaxDisp;
278 }
279
280 unsigned getLongFormOpcode() const {
281 return LongFormOpcode;
282 }
283 };
284
285 /// CPUsers - Keep track of all of the machine instructions that use various
286 /// constant pools and their max displacement.
287 std::vector<CPUser> CPUsers;
288
289 /// CPEntry - One per constant pool entry, keeping the machine instruction
290 /// pointer, the constpool index, and the number of CPUser's which
291 /// reference this entry.
292 struct CPEntry {
293 MachineInstr *CPEMI;
294 unsigned CPI;
295 unsigned RefCount;
296
297 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
298 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
299 };
300
301 /// CPEntries - Keep track of all of the constant pool entry machine
302 /// instructions. For each original constpool index (i.e. those that
303 /// existed upon entry to this pass), it keeps a vector of entries.
304 /// Original elements are cloned as we go along; the clones are
305 /// put in the vector of the original element, but have distinct CPIs.
306 std::vector<std::vector<CPEntry>> CPEntries;
307
308 /// ImmBranch - One per immediate branch, keeping the machine instruction
309 /// pointer, conditional or unconditional, the max displacement,
310 /// and (if isCond is true) the corresponding unconditional branch
311 /// opcode.
312 struct ImmBranch {
313 MachineInstr *MI;
314 unsigned MaxDisp : 31;
316 unsigned isCond : 1;
317 int UncondBr;
318
319 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
320 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
321 };
322
323 /// ImmBranches - Keep track of all the immediate branch instructions.
324 ///
325 std::vector<ImmBranch> ImmBranches;
326
327 const MipsSubtarget *STI = nullptr;
328 const Mips16InstrInfo *TII;
329 MipsFunctionInfo *MFI;
330 MachineFunction *MF = nullptr;
331 MachineConstantPool *MCP = nullptr;
332
333 unsigned PICLabelUId;
334 bool PrescannedForConstants = false;
335
336 void initPICLabelUId(unsigned UId) { PICLabelUId = UId; }
337
338 unsigned createPICLabelUId() { return PICLabelUId++; }
339
340 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
341 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
342 Align getCPEAlign(const MachineInstr &CPEMI);
343 unsigned getMaxDisp(const CPUser &U) const {
344 int SmallOffset = STI->getCLOpts().constant_islands_small_offset;
345 return SmallOffset ? SmallOffset : U.getMaxDisp();
346 }
347 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
348 unsigned getOffsetOf(MachineInstr *MI) const;
349 unsigned getUserOffset(CPUser&) const;
350 void dumpBBs();
351
352 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
353 unsigned Disp, bool NegativeOK);
354 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
355 const CPUser &U);
356
357 void computeBlockSize(MachineBasicBlock *MBB);
358 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);
359 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
360 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
361 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
362 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
363 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
364 bool findAvailableWater(CPUser&U, unsigned UserOffset,
365 water_iterator &WaterIter);
366 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
367 MachineBasicBlock *&NewMBB);
368 bool handleConstantPoolUser(unsigned CPUserIndex);
369 void removeDeadCPEMI(MachineInstr *CPEMI);
370 bool removeUnusedCPEntries();
371 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
372 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
373 bool DoDump = false);
374 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
375 CPUser &U, unsigned &Growth);
376 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
377 bool fixupImmediateBr(ImmBranch &Br);
378 bool fixupConditionalBr(ImmBranch &Br);
379 bool fixupUnconditionalBr(ImmBranch &Br);
380
381 void prescanForConstants();
382
383 public:
384 bool runOnMachineFunction(MachineFunction &MF);
385 };
386
387} // end anonymous namespace
388
389char MipsConstantIslandLegacy::ID = 0;
390
391bool MipsConstantIslandImpl::isOffsetInRange(unsigned UserOffset,
392 unsigned TrialOffset,
393 const CPUser &U) {
394 return isOffsetInRange(UserOffset, TrialOffset, getMaxDisp(U), U.NegOk);
395}
396
397#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
398/// print block size and offset information - debugging
399LLVM_DUMP_METHOD void MipsConstantIslandImpl::dumpBBs() {
400 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
401 const BasicBlockInfo &BBI = BBInfo[J];
402 dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
403 << format(" size=%#x\n", BBInfo[J].Size);
404 }
405}
406#endif
407
408bool MipsConstantIslandImpl::runOnMachineFunction(MachineFunction &mf) {
409 // The intention is for this to be a mips16 only pass for now
410 // FIXME:
411 MF = &mf;
412 MCP = mf.getConstantPool();
413 STI = &mf.getSubtarget<MipsSubtarget>();
414 LLVM_DEBUG(dbgs() << "constant island machine function "
415 << "\n");
416 if (!STI->inMips16Mode() || !STI->useConstantIslands()) {
417 return false;
418 }
419 TII = (const Mips16InstrInfo *)STI->getInstrInfo();
420 MFI = MF->getInfo<MipsFunctionInfo>();
421 LLVM_DEBUG(dbgs() << "constant island processing "
422 << "\n");
423 //
424 // will need to make predermination if there is any constants we need to
425 // put in constant islands. TBD.
426 //
427 if (!PrescannedForConstants) prescanForConstants();
428
429 // This pass invalidates liveness information when it splits basic blocks.
431
432 // Renumber all of the machine basic blocks in the function, guaranteeing that
433 // the numbers agree with the position of the block in the function.
434 MF->RenumberBlocks();
435
436 bool MadeChange = false;
437
438 // Perform the initial placement of the constant pool entries. To start with,
439 // we put them all at the end of the function.
440 std::vector<MachineInstr*> CPEMIs;
441 if (!MCP->isEmpty())
442 doInitialPlacement(CPEMIs);
443
444 /// The next UID to take is the first unused one.
445 initPICLabelUId(CPEMIs.size());
446
447 // Do the initial scan of the function, building up information about the
448 // sizes of each block, the location of all the water, and finding all of the
449 // constant pool users.
450 initializeFunctionInfo(CPEMIs);
451 CPEMIs.clear();
452 LLVM_DEBUG(dumpBBs());
453
454 /// Remove dead constant pool entries.
455 MadeChange |= removeUnusedCPEntries();
456
457 // Iteratively place constant pool entries and fix up branches until there
458 // is no change.
459 unsigned NoCPIters = 0, NoBRIters = 0;
460 (void)NoBRIters;
461 while (true) {
462 LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
463 bool CPChange = false;
464 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
465 CPChange |= handleConstantPoolUser(i);
466 if (CPChange && ++NoCPIters > 30)
467 report_fatal_error("Constant Island pass failed to converge!");
468 LLVM_DEBUG(dumpBBs());
469
470 // Clear NewWaterList now. If we split a block for branches, it should
471 // appear as "new water" for the next iteration of constant pool placement.
472 NewWaterList.clear();
473
474 LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
475 bool BRChange = false;
476 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
477 BRChange |= fixupImmediateBr(ImmBranches[i]);
478 if (BRChange && ++NoBRIters > 30)
479 report_fatal_error("Branch Fix Up pass failed to converge!");
480 LLVM_DEBUG(dumpBBs());
481 if (!CPChange && !BRChange)
482 break;
483 MadeChange = true;
484 }
485
486 LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
487
488 BBInfo.clear();
489 WaterList.clear();
490 CPUsers.clear();
491 CPEntries.clear();
492 ImmBranches.clear();
493 return MadeChange;
494}
495
496/// doInitialPlacement - Perform the initial placement of the constant pool
497/// entries. To start with, we put them all at the end of the function.
498void MipsConstantIslandImpl::doInitialPlacement(
499 std::vector<MachineInstr *> &CPEMIs) {
500 // Create the basic block to hold the CPE's.
501 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
502 MF->push_back(BB);
503
504 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
505 const Align MaxAlign = MCP->getConstantPoolAlign();
506
507 // Mark the basic block as required by the const-pool.
508 // If -mips-align-constant-islands isn't set, use 4-byte alignment for
509 // everything.
510 BB->setAlignment(STI->getCLOpts().align_constant_islands ? MaxAlign
511 : Align(4));
512
513 // The function needs to be as aligned as the basic blocks. The linker may
514 // move functions around based on their alignment.
515 MF->ensureAlignment(BB->getAlignment());
516
517 // Order the entries in BB by descending alignment. That ensures correct
518 // alignment of all entries as long as BB is sufficiently aligned. Keep
519 // track of the insertion point for each alignment. We are going to bucket
520 // sort the entries as they are created.
522 BB->end());
523
524 // Add all of the constants from the constant pool to the end block, use an
525 // identity mapping of CPI's to CPE's.
526 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
527
528 const DataLayout &TD = MF->getDataLayout();
529 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
530 unsigned Size = CPs[i].getSizeInBytes(TD);
531 assert(Size >= 4 && "Too small constant pool entry");
532 Align Alignment = CPs[i].getAlign();
533 // Verify that all constant pool entries are a multiple of their alignment.
534 // If not, we would have to pad them out so that instructions stay aligned.
535 assert(isAligned(Alignment, Size) && "CP Entry not multiple of 4 bytes!");
536
537 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
538 unsigned LogAlign = Log2(Alignment);
539 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
540
541 MachineInstr *CPEMI =
542 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
544
545 CPEMIs.push_back(CPEMI);
546
547 // Ensure that future entries with higher alignment get inserted before
548 // CPEMI. This is bucket sort with iterators.
549 for (unsigned a = LogAlign + 1; a <= Log2(MaxAlign); ++a)
550 if (InsPoint[a] == InsAt)
551 InsPoint[a] = CPEMI;
552 // Add a new CPEntry, but no corresponding CPUser yet.
553 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
554 ++NumCPEs;
555 LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
556 << Size << ", align = " << Alignment.value() << '\n');
557 }
558 LLVM_DEBUG(BB->dump());
559}
560
561/// BBHasFallthrough - Return true if the specified basic block can fallthrough
562/// into the block immediately after it.
564 // Get the next machine basic block in the function.
565 MachineFunction::iterator MBBI = MBB->getIterator();
566 // Can't fall off end of function.
567 if (std::next(MBBI) == MBB->getParent()->end())
568 return false;
569
570 MachineBasicBlock *NextBB = &*std::next(MBBI);
571 return llvm::is_contained(MBB->successors(), NextBB);
572}
573
574/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
575/// look up the corresponding CPEntry.
576MipsConstantIslandImpl::CPEntry *
577MipsConstantIslandImpl::findConstPoolEntry(unsigned CPI,
578 const MachineInstr *CPEMI) {
579 std::vector<CPEntry> &CPEs = CPEntries[CPI];
580 // Number of entries per constpool index should be small, just do a
581 // linear search.
582 for (CPEntry &CPE : CPEs) {
583 if (CPE.CPEMI == CPEMI)
584 return &CPE;
585 }
586 return nullptr;
587}
588
589/// getCPEAlign - Returns the required alignment of the constant pool entry
590/// represented by CPEMI. Alignment is measured in log2(bytes) units.
591Align MipsConstantIslandImpl::getCPEAlign(const MachineInstr &CPEMI) {
592 assert(CPEMI.getOpcode() == Mips::CONSTPOOL_ENTRY);
593
594 // Everything is 4-byte aligned unless -mips-align-constant-islands is set.
595 if (!STI->getCLOpts().align_constant_islands)
596 return Align(4);
597
598 unsigned CPI = CPEMI.getOperand(1).getIndex();
599 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
600 return MCP->getConstants()[CPI].getAlign();
601}
602
603/// initializeFunctionInfo - Do the initial scan of the function, building up
604/// information about the sizes of each block, the location of all the water,
605/// and finding all of the constant pool users.
606void MipsConstantIslandImpl::initializeFunctionInfo(
607 const std::vector<MachineInstr *> &CPEMIs) {
608 BBInfo.clear();
609 BBInfo.resize(MF->getNumBlockIDs());
610
611 // First thing, compute the size of all basic blocks, and see if the function
612 // has any inline assembly in it. If so, we have to be conservative about
613 // alignment assumptions, as we don't know for sure the size of any
614 // instructions in the inline assembly.
615 for (MachineBasicBlock &MBB : *MF)
616 computeBlockSize(&MBB);
617
618 // Compute block offsets.
619 adjustBBOffsetsAfter(&MF->front());
620
621 // Now go back through the instructions and build up our data structures.
622 for (MachineBasicBlock &MBB : *MF) {
623 // If this block doesn't fall through into the next MBB, then this is
624 // 'water' that a constant pool island could be placed.
625 if (!BBHasFallthrough(&MBB))
626 WaterList.push_back(&MBB);
627 for (MachineInstr &MI : MBB) {
628 if (MI.isDebugInstr())
629 continue;
630
631 int Opc = MI.getOpcode();
632 if (MI.isBranch()) {
633 bool isCond = false;
634 unsigned Bits = 0;
635 unsigned Scale = 1;
636 int UOpc = Opc;
637 switch (Opc) {
638 default:
639 continue; // Ignore other branches for now
640 case Mips::Bimm16:
641 Bits = 11;
642 Scale = 2;
643 isCond = false;
644 break;
645 case Mips::BimmX16:
646 Bits = 16;
647 Scale = 2;
648 isCond = false;
649 break;
650 case Mips::BeqzRxImm16:
651 UOpc=Mips::Bimm16;
652 Bits = 8;
653 Scale = 2;
654 isCond = true;
655 break;
656 case Mips::BeqzRxImmX16:
657 UOpc=Mips::Bimm16;
658 Bits = 16;
659 Scale = 2;
660 isCond = true;
661 break;
662 case Mips::BnezRxImm16:
663 UOpc=Mips::Bimm16;
664 Bits = 8;
665 Scale = 2;
666 isCond = true;
667 break;
668 case Mips::BnezRxImmX16:
669 UOpc=Mips::Bimm16;
670 Bits = 16;
671 Scale = 2;
672 isCond = true;
673 break;
674 case Mips::Bteqz16:
675 UOpc=Mips::Bimm16;
676 Bits = 8;
677 Scale = 2;
678 isCond = true;
679 break;
680 case Mips::BteqzX16:
681 UOpc=Mips::Bimm16;
682 Bits = 16;
683 Scale = 2;
684 isCond = true;
685 break;
686 case Mips::Btnez16:
687 UOpc=Mips::Bimm16;
688 Bits = 8;
689 Scale = 2;
690 isCond = true;
691 break;
692 case Mips::BtnezX16:
693 UOpc=Mips::Bimm16;
694 Bits = 16;
695 Scale = 2;
696 isCond = true;
697 break;
698 }
699 // Record this immediate branch.
700 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
701 ImmBranches.push_back(ImmBranch(&MI, MaxOffs, isCond, UOpc));
702 }
703
704 if (Opc == Mips::CONSTPOOL_ENTRY)
705 continue;
706
707 // Scan the instructions for constant pool operands.
708 for (const MachineOperand &MO : MI.operands())
709 if (MO.isCPI()) {
710 // We found one. The addressing mode tells us the max displacement
711 // from the PC that this instruction permits.
712
713 // Basic size info comes from the TSFlags field.
714 unsigned Bits = 0;
715 unsigned Scale = 1;
716 bool NegOk = false;
717 unsigned LongFormBits = 0;
718 unsigned LongFormScale = 0;
719 unsigned LongFormOpcode = 0;
720 switch (Opc) {
721 default:
722 llvm_unreachable("Unknown addressing mode for CP reference!");
723 case Mips::LwRxPcTcp16:
724 Bits = 8;
725 Scale = 4;
726 LongFormOpcode = Mips::LwRxPcTcpX16;
727 LongFormBits = 14;
728 LongFormScale = 1;
729 break;
730 case Mips::LwRxPcTcpX16:
731 Bits = 14;
732 Scale = 1;
733 NegOk = true;
734 break;
735 }
736 // Remember that this is a user of a CP entry.
737 unsigned CPI = MO.getIndex();
738 MachineInstr *CPEMI = CPEMIs[CPI];
739 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
740 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
741 CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk, LongFormMaxOffs,
742 LongFormOpcode));
743
744 // Increment corresponding CPEntry reference count.
745 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
746 assert(CPE && "Cannot find a corresponding CPEntry!");
747 CPE->RefCount++;
748
749 // Instructions can only use one CP entry, don't bother scanning the
750 // rest of the operands.
751 break;
752 }
753 }
754 }
755}
756
757/// computeBlockSize - Compute the size and some alignment information for MBB.
758/// This function updates BBInfo directly.
759void MipsConstantIslandImpl::computeBlockSize(MachineBasicBlock *MBB) {
760 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
761 BBI.Size = 0;
762
763 for (const MachineInstr &MI : *MBB)
764 BBI.Size += TII->getInstSizeInBytes(MI);
765}
766
767/// getOffsetOf - Return the current offset of the specified machine instruction
768/// from the start of the function. This offset changes as stuff is moved
769/// around inside the function.
770unsigned MipsConstantIslandImpl::getOffsetOf(MachineInstr *MI) const {
771 MachineBasicBlock *MBB = MI->getParent();
772
773 // The offset is composed of two things: the sum of the sizes of all MBB's
774 // before this instruction's block, and the offset from the start of the block
775 // it is in.
776 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
777
778 // Sum instructions before MI in MBB.
779 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
780 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
781 Offset += TII->getInstSizeInBytes(*I);
782 }
783 return Offset;
784}
785
786/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
787/// ID.
789 const MachineBasicBlock *RHS) {
790 return LHS->getNumber() < RHS->getNumber();
791}
792
793/// updateForInsertedWaterBlock - When a block is newly inserted into the
794/// machine function, it upsets all of the block numbers. Renumber the blocks
795/// and update the arrays that parallel this numbering.
796void MipsConstantIslandImpl::updateForInsertedWaterBlock(
797 MachineBasicBlock *NewBB) {
798 // Renumber the MBB's to keep them consecutive.
799 NewBB->getParent()->RenumberBlocks(NewBB);
800
801 // Insert an entry into BBInfo to align it properly with the (newly
802 // renumbered) block numbers.
803 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
804
805 // Next, update WaterList. Specifically, we need to add NewMBB as having
806 // available water after it.
807 water_iterator IP = llvm::lower_bound(WaterList, NewBB, CompareMBBNumbers);
808 WaterList.insert(IP, NewBB);
809}
810
811unsigned MipsConstantIslandImpl::getUserOffset(CPUser &U) const {
812 return getOffsetOf(U.MI);
813}
814
815/// Split the basic block containing MI into two blocks, which are joined by
816/// an unconditional branch. Update data structures and renumber blocks to
817/// account for this change and returns the newly created block.
818MachineBasicBlock *
819MipsConstantIslandImpl::splitBlockBeforeInstr(MachineInstr &MI) {
820 MachineBasicBlock *OrigBB = MI.getParent();
821
822 // Create a new MBB for the code after the OrigBB.
823 MachineBasicBlock *NewBB =
824 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
826 MF->insert(MBBI, NewBB);
827
828 // Splice the instructions starting with MI over to NewBB.
829 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
830
831 // Add an unconditional branch from OrigBB to NewBB.
832 // Note the new unconditional branch is not being recorded.
833 // There doesn't seem to be meaningful DebugInfo available; this doesn't
834 // correspond to anything in the source.
835 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
836 ++NumSplit;
837
838 // Update the CFG. All succs of OrigBB are now succs of NewBB.
839 NewBB->transferSuccessors(OrigBB);
840
841 // OrigBB branches to NewBB.
842 OrigBB->addSuccessor(NewBB);
843
844 // Update internal data structures to account for the newly inserted MBB.
845 // This is almost the same as updateForInsertedWaterBlock, except that
846 // the Water goes after OrigBB, not NewBB.
847 MF->RenumberBlocks(NewBB);
848
849 // Insert an entry into BBInfo to align it properly with the (newly
850 // renumbered) block numbers.
851 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
852
853 // Next, update WaterList. Specifically, we need to add OrigMBB as having
854 // available water after it (but not if it's already there, which happens
855 // when splitting before a conditional branch that is followed by an
856 // unconditional branch - in that case we want to insert NewBB).
857 water_iterator IP = llvm::lower_bound(WaterList, OrigBB, CompareMBBNumbers);
858 MachineBasicBlock* WaterBB = *IP;
859 if (WaterBB == OrigBB)
860 WaterList.insert(std::next(IP), NewBB);
861 else
862 WaterList.insert(IP, OrigBB);
863 NewWaterList.insert(OrigBB);
864
865 // Figure out how large the OrigBB is. As the first half of the original
866 // block, it cannot contain a tablejump. The size includes
867 // the new jump we added. (It should be possible to do this without
868 // recounting everything, but it's very confusing, and this is rarely
869 // executed.)
870 computeBlockSize(OrigBB);
871
872 // Figure out how large the NewMBB is. As the second half of the original
873 // block, it may contain a tablejump.
874 computeBlockSize(NewBB);
875
876 // All BBOffsets following these blocks must be modified.
877 adjustBBOffsetsAfter(OrigBB);
878
879 return NewBB;
880}
881
882/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
883/// reference) is within MaxDisp of TrialOffset (a proposed location of a
884/// constant pool entry).
885bool MipsConstantIslandImpl::isOffsetInRange(unsigned UserOffset,
886 unsigned TrialOffset,
887 unsigned MaxDisp,
888 bool NegativeOK) {
889 if (UserOffset <= TrialOffset) {
890 // User before the Trial.
891 if (TrialOffset - UserOffset <= MaxDisp)
892 return true;
893 } else if (NegativeOK) {
894 if (UserOffset - TrialOffset <= MaxDisp)
895 return true;
896 }
897 return false;
898}
899
900/// isWaterInRange - Returns true if a CPE placed after the specified
901/// Water (a basic block) will be in range for the specific MI.
902///
903/// Compute how much the function will grow by inserting a CPE after Water.
904bool MipsConstantIslandImpl::isWaterInRange(unsigned UserOffset,
905 MachineBasicBlock *Water, CPUser &U,
906 unsigned &Growth) {
907 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
908 unsigned NextBlockOffset;
909 Align NextBlockAlignment;
910 MachineFunction::const_iterator NextBlock = ++Water->getIterator();
911 if (NextBlock == MF->end()) {
912 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
913 NextBlockAlignment = Align(1);
914 } else {
915 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
916 NextBlockAlignment = NextBlock->getAlignment();
917 }
918 unsigned Size = U.CPEMI->getOperand(2).getImm();
919 unsigned CPEEnd = CPEOffset + Size;
920
921 // The CPE may be able to hide in the alignment padding before the next
922 // block. It may also cause more padding to be required if it is more aligned
923 // that the next block.
924 if (CPEEnd > NextBlockOffset) {
925 Growth = CPEEnd - NextBlockOffset;
926 // Compute the padding that would go at the end of the CPE to align the next
927 // block.
928 Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);
929
930 // If the CPE is to be inserted before the instruction, that will raise
931 // the offset of the instruction. Also account for unknown alignment padding
932 // in blocks between CPE and the user.
933 if (CPEOffset < UserOffset)
934 UserOffset += Growth;
935 } else
936 // CPE fits in existing padding.
937 Growth = 0;
938
939 return isOffsetInRange(UserOffset, CPEOffset, U);
940}
941
942/// isCPEntryInRange - Returns true if the distance between specific MI and
943/// specific ConstPool entry instruction can fit in MI's displacement field.
944bool MipsConstantIslandImpl::isCPEntryInRange(MachineInstr *MI,
945 unsigned UserOffset,
946 MachineInstr *CPEMI,
947 unsigned MaxDisp, bool NegOk,
948 bool DoDump) {
949 unsigned CPEOffset = getOffsetOf(CPEMI);
950
951 if (DoDump) {
952 LLVM_DEBUG({
953 unsigned Block = MI->getParent()->getNumber();
954 const BasicBlockInfo &BBI = BBInfo[Block];
955 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
956 << " max delta=" << MaxDisp
957 << format(" insn address=%#x", UserOffset) << " in "
958 << printMBBReference(*MI->getParent()) << ": "
959 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
960 << format("CPE address=%#x offset=%+d: ", CPEOffset,
961 int(CPEOffset - UserOffset));
962 });
963 }
964
965 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
966}
967
968#ifndef NDEBUG
969/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
970/// unconditionally branches to its only successor.
972 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
973 return false;
974 MachineBasicBlock *Succ = *MBB->succ_begin();
975 MachineBasicBlock *Pred = *MBB->pred_begin();
976 MachineInstr *PredMI = &Pred->back();
977 if (PredMI->getOpcode() == Mips::Bimm16)
978 return PredMI->getOperand(0).getMBB() == Succ;
979 return false;
980}
981#endif
982
983void MipsConstantIslandImpl::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
984 unsigned BBNum = BB->getNumber();
985 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
986 // Get the offset and known bits at the end of the layout predecessor.
987 // Include the alignment of the current block.
988 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
989 BBInfo[i].Offset = Offset;
990 }
991}
992
993/// decrementCPEReferenceCount - find the constant pool entry with index CPI
994/// and instruction CPEMI, and decrement its refcount. If the refcount
995/// becomes 0 remove the entry and instruction. Returns true if we removed
996/// the entry, false if we didn't.
997bool MipsConstantIslandImpl::decrementCPEReferenceCount(unsigned CPI,
998 MachineInstr *CPEMI) {
999 // Find the old entry. Eliminate it if it is no longer used.
1000 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1001 assert(CPE && "Unexpected!");
1002 if (--CPE->RefCount == 0) {
1003 removeDeadCPEMI(CPEMI);
1004 CPE->CPEMI = nullptr;
1005 --NumCPEs;
1006 return true;
1007 }
1008 return false;
1009}
1010
1011/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1012/// if not, see if an in-range clone of the CPE is in range, and if so,
1013/// change the data structures so the user references the clone. Returns:
1014/// 0 = no existing entry found
1015/// 1 = entry found, and there were no code insertions or deletions
1016/// 2 = entry found, and there were code insertions or deletions
1017int MipsConstantIslandImpl::findInRangeCPEntry(CPUser &U, unsigned UserOffset) {
1018 MachineInstr *UserMI = U.MI;
1019 MachineInstr *CPEMI = U.CPEMI;
1020
1021 // Check to see if the CPE is already in-range.
1022 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, getMaxDisp(U), U.NegOk,
1023 true)) {
1024 LLVM_DEBUG(dbgs() << "In range\n");
1025 return 1;
1026 }
1027
1028 // No. Look for previously created clones of the CPE that are in range.
1029 unsigned CPI = CPEMI->getOperand(1).getIndex();
1030 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1031 for (CPEntry &CPE : CPEs) {
1032 // We already tried this one
1033 if (CPE.CPEMI == CPEMI)
1034 continue;
1035 // Removing CPEs can leave empty entries, skip
1036 if (CPE.CPEMI == nullptr)
1037 continue;
1038 if (isCPEntryInRange(UserMI, UserOffset, CPE.CPEMI, getMaxDisp(U),
1039 U.NegOk)) {
1040 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" << CPE.CPI
1041 << "\n");
1042 // Point the CPUser node to the replacement
1043 U.CPEMI = CPE.CPEMI;
1044 // Change the CPI in the instruction operand to refer to the clone.
1045 for (MachineOperand &MO : UserMI->operands())
1046 if (MO.isCPI()) {
1047 MO.setIndex(CPE.CPI);
1048 break;
1049 }
1050 // Adjust the refcount of the clone...
1051 CPE.RefCount++;
1052 // ...and the original. If we didn't remove the old entry, none of the
1053 // addresses changed, so we don't need another pass.
1054 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1055 }
1056 }
1057 return 0;
1058}
1059
1060/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1061/// This version checks if the longer form of the instruction can be used to
1062/// to satisfy things.
1063/// if not, see if an in-range clone of the CPE is in range, and if so,
1064/// change the data structures so the user references the clone. Returns:
1065/// 0 = no existing entry found
1066/// 1 = entry found, and there were no code insertions or deletions
1067/// 2 = entry found, and there were code insertions or deletions
1068int MipsConstantIslandImpl::findLongFormInRangeCPEntry(CPUser &U,
1069 unsigned UserOffset) {
1070 MachineInstr *UserMI = U.MI;
1071 MachineInstr *CPEMI = U.CPEMI;
1072
1073 // Check to see if the CPE is already in-range.
1074 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1075 U.getLongFormMaxDisp(), U.NegOk,
1076 true)) {
1077 LLVM_DEBUG(dbgs() << "In range\n");
1078 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
1079 U.setMaxDisp(U.getLongFormMaxDisp());
1080 return 2; // instruction is longer length now
1081 }
1082
1083 // No. Look for previously created clones of the CPE that are in range.
1084 unsigned CPI = CPEMI->getOperand(1).getIndex();
1085 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1086 for (CPEntry &CPE : CPEs) {
1087 // We already tried this one
1088 if (CPE.CPEMI == CPEMI)
1089 continue;
1090 // Removing CPEs can leave empty entries, skip
1091 if (CPE.CPEMI == nullptr)
1092 continue;
1093 if (isCPEntryInRange(UserMI, UserOffset, CPE.CPEMI, U.getLongFormMaxDisp(),
1094 U.NegOk)) {
1095 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" << CPE.CPI
1096 << "\n");
1097 // Point the CPUser node to the replacement
1098 U.CPEMI = CPE.CPEMI;
1099 // Change the CPI in the instruction operand to refer to the clone.
1100 for (MachineOperand &MO : UserMI->operands())
1101 if (MO.isCPI()) {
1102 MO.setIndex(CPE.CPI);
1103 break;
1104 }
1105 // Adjust the refcount of the clone...
1106 CPE.RefCount++;
1107 // ...and the original. If we didn't remove the old entry, none of the
1108 // addresses changed, so we don't need another pass.
1109 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1110 }
1111 }
1112 return 0;
1113}
1114
1115/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1116/// the specific unconditional branch instruction.
1117static inline unsigned getUnconditionalBrDisp(int Opc) {
1118 switch (Opc) {
1119 case Mips::Bimm16:
1120 return ((1<<10)-1)*2;
1121 case Mips::BimmX16:
1122 return ((1<<16)-1)*2;
1123 default:
1124 break;
1125 }
1126 return ((1<<16)-1)*2;
1127}
1128
1129/// findAvailableWater - Look for an existing entry in the WaterList in which
1130/// we can place the CPE referenced from U so it's within range of U's MI.
1131/// Returns true if found, false if not. If it returns true, WaterIter
1132/// is set to the WaterList entry.
1133/// To ensure that this pass
1134/// terminates, the CPE location for a particular CPUser is only allowed to
1135/// move to a lower address, so search backward from the end of the list and
1136/// prefer the first water that is in range.
1137bool MipsConstantIslandImpl::findAvailableWater(CPUser &U, unsigned UserOffset,
1138 water_iterator &WaterIter) {
1139 if (WaterList.empty())
1140 return false;
1141
1142 unsigned BestGrowth = ~0u;
1143 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1144 --IP) {
1145 MachineBasicBlock* WaterBB = *IP;
1146 // Check if water is in range and is either at a lower address than the
1147 // current "high water mark" or a new water block that was created since
1148 // the previous iteration by inserting an unconditional branch. In the
1149 // latter case, we want to allow resetting the high water mark back to
1150 // this new water since we haven't seen it before. Inserting branches
1151 // should be relatively uncommon and when it does happen, we want to be
1152 // sure to take advantage of it for all the CPEs near that block, so that
1153 // we don't insert more branches than necessary.
1154 unsigned Growth;
1155 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1156 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1157 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1158 // This is the least amount of required padding seen so far.
1159 BestGrowth = Growth;
1160 WaterIter = IP;
1161 LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
1162 << " Growth=" << Growth << '\n');
1163
1164 // Keep looking unless it is perfect.
1165 if (BestGrowth == 0)
1166 return true;
1167 }
1168 if (IP == B)
1169 break;
1170 }
1171 return BestGrowth != ~0u;
1172}
1173
1174/// createNewWater - No existing WaterList entry will work for
1175/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1176/// block is used if in range, and the conditional branch munged so control
1177/// flow is correct. Otherwise the block is split to create a hole with an
1178/// unconditional branch around it. In either case NewMBB is set to a
1179/// block following which the new island can be inserted (the WaterList
1180/// is not adjusted).
1181void MipsConstantIslandImpl::createNewWater(unsigned CPUserIndex,
1182 unsigned UserOffset,
1183 MachineBasicBlock *&NewMBB) {
1184 CPUser &U = CPUsers[CPUserIndex];
1185 MachineInstr *UserMI = U.MI;
1186 MachineInstr *CPEMI = U.CPEMI;
1187 MachineBasicBlock *UserMBB = UserMI->getParent();
1188 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1189
1190 // If the block does not end in an unconditional branch already, and if the
1191 // end of the block is within range, make new water there.
1192 if (BBHasFallthrough(UserMBB)) {
1193 // Size of branch to insert.
1194 unsigned Delta = 2;
1195 // Compute the offset where the CPE will begin.
1196 unsigned CPEOffset = UserBBI.postOffset() + Delta;
1197
1198 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1199 LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
1200 << format(", expected CPE offset %#x\n", CPEOffset));
1201 NewMBB = &*++UserMBB->getIterator();
1202 // Add an unconditional branch from UserMBB to fallthrough block. Record
1203 // it for branch lengthening; this new branch will not get out of range,
1204 // but if the preceding conditional branch is out of range, the targets
1205 // will be exchanged, and the altered branch may be out of range, so the
1206 // machinery has to know about it.
1207 int UncondBr = Mips::Bimm16;
1208 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1209 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1210 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1211 MaxDisp, false, UncondBr));
1212 BBInfo[UserMBB->getNumber()].Size += Delta;
1213 adjustBBOffsetsAfter(UserMBB);
1214 return;
1215 }
1216 }
1217
1218 // What a big block. Find a place within the block to split it.
1219
1220 // Try to split the block so it's fully aligned. Compute the latest split
1221 // point where we can add a 4-byte branch instruction, and then align to
1222 // Align which is the largest possible alignment in the function.
1223 const Align Align = MF->getAlignment();
1224 unsigned BaseInsertOffset = UserOffset + getMaxDisp(U);
1225 LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1226 BaseInsertOffset));
1227
1228 // The 4 in the following is for the unconditional branch we'll be inserting
1229 // Alignment of the island is handled
1230 // inside isOffsetInRange.
1231 BaseInsertOffset -= 4;
1232
1233 LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1234 << " la=" << Log2(Align) << '\n');
1235
1236 // This could point off the end of the block if we've already got constant
1237 // pool entries following this block; only the last one is in the water list.
1238 // Back past any possible branches (allow for a conditional and a maximally
1239 // long unconditional).
1240 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1241 BaseInsertOffset = UserBBI.postOffset() - 8;
1242 LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1243 }
1244 unsigned EndInsertOffset = BaseInsertOffset + 4 +
1245 CPEMI->getOperand(2).getImm();
1247 ++MI;
1248 unsigned CPUIndex = CPUserIndex+1;
1249 unsigned NumCPUsers = CPUsers.size();
1250 //MachineInstr *LastIT = 0;
1251 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1252 Offset < BaseInsertOffset;
1253 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1254 assert(MI != UserMBB->end() && "Fell off end of block");
1255 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1256 CPUser &U = CPUsers[CPUIndex];
1257 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1258 // Shift intertion point by one unit of alignment so it is within reach.
1259 BaseInsertOffset -= Align.value();
1260 EndInsertOffset -= Align.value();
1261 }
1262 // This is overly conservative, as we don't account for CPEMIs being
1263 // reused within the block, but it doesn't matter much. Also assume CPEs
1264 // are added in order with alignment padding. We may eventually be able
1265 // to pack the aligned CPEs better.
1266 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1267 CPUIndex++;
1268 }
1269 }
1270
1271 NewMBB = splitBlockBeforeInstr(*--MI);
1272}
1273
1274/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1275/// is out-of-range. If so, pick up the constant pool value and move it some
1276/// place in-range. Return true if we changed any addresses (thus must run
1277/// another pass of branch lengthening), false otherwise.
1278bool MipsConstantIslandImpl::handleConstantPoolUser(unsigned CPUserIndex) {
1279 CPUser &U = CPUsers[CPUserIndex];
1280 MachineInstr *UserMI = U.MI;
1281 MachineInstr *CPEMI = U.CPEMI;
1282 unsigned CPI = CPEMI->getOperand(1).getIndex();
1283 unsigned Size = CPEMI->getOperand(2).getImm();
1284 // Compute this only once, it's expensive.
1285 unsigned UserOffset = getUserOffset(U);
1286
1287 // See if the current entry is within range, or there is a clone of it
1288 // in range.
1289 int result = findInRangeCPEntry(U, UserOffset);
1290 if (result==1) return false;
1291 else if (result==2) return true;
1292
1293 // Look for water where we can place this CPE.
1294 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1295 MachineBasicBlock *NewMBB;
1296 water_iterator IP;
1297 if (findAvailableWater(U, UserOffset, IP)) {
1298 LLVM_DEBUG(dbgs() << "Found water in range\n");
1299 MachineBasicBlock *WaterBB = *IP;
1300
1301 // If the original WaterList entry was "new water" on this iteration,
1302 // propagate that to the new island. This is just keeping NewWaterList
1303 // updated to match the WaterList, which will be updated below.
1304 if (NewWaterList.erase(WaterBB))
1305 NewWaterList.insert(NewIsland);
1306
1307 // The new CPE goes before the following block (NewMBB).
1308 NewMBB = &*++WaterBB->getIterator();
1309 } else {
1310 // No water found.
1311 // we first see if a longer form of the instruction could have reached
1312 // the constant. in that case we won't bother to split
1313 if (!STI->getCLOpts().constant_islands_no_load_relaxation) {
1314 result = findLongFormInRangeCPEntry(U, UserOffset);
1315 if (result != 0) return true;
1316 }
1317 LLVM_DEBUG(dbgs() << "No water found\n");
1318 createNewWater(CPUserIndex, UserOffset, NewMBB);
1319
1320 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1321 // called while handling branches so that the water will be seen on the
1322 // next iteration for constant pools, but in this context, we don't want
1323 // it. Check for this so it will be removed from the WaterList.
1324 // Also remove any entry from NewWaterList.
1325 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
1326 IP = llvm::find(WaterList, WaterBB);
1327 if (IP != WaterList.end())
1328 NewWaterList.erase(WaterBB);
1329
1330 // We are adding new water. Update NewWaterList.
1331 NewWaterList.insert(NewIsland);
1332 }
1333
1334 // Remove the original WaterList entry; we want subsequent insertions in
1335 // this vicinity to go after the one we're about to insert. This
1336 // considerably reduces the number of times we have to move the same CPE
1337 // more than once and is also important to ensure the algorithm terminates.
1338 if (IP != WaterList.end())
1339 WaterList.erase(IP);
1340
1341 // Okay, we know we can put an island before NewMBB now, do it!
1342 MF->insert(NewMBB->getIterator(), NewIsland);
1343
1344 // Update internal data structures to account for the newly inserted MBB.
1345 updateForInsertedWaterBlock(NewIsland);
1346
1347 // Decrement the old entry, and remove it if refcount becomes 0.
1348 decrementCPEReferenceCount(CPI, CPEMI);
1349
1350 // No existing clone of this CPE is within range.
1351 // We will be generating a new clone. Get a UID for it.
1352 unsigned ID = createPICLabelUId();
1353
1354 // Now that we have an island to add the CPE to, clone the original CPE and
1355 // add it to the island.
1356 U.HighWaterMark = NewIsland;
1357 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1359 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1360 ++NumCPEs;
1361
1362 // Mark the basic block as aligned as required by the const-pool entry.
1363 NewIsland->setAlignment(getCPEAlign(*U.CPEMI));
1364
1365 // Increase the size of the island block to account for the new entry.
1366 BBInfo[NewIsland->getNumber()].Size += Size;
1367 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
1368
1369 // Finally, change the CPI in the instruction operand to be ID.
1370 for (MachineOperand &MO : UserMI->operands())
1371 if (MO.isCPI()) {
1372 MO.setIndex(ID);
1373 break;
1374 }
1375
1376 LLVM_DEBUG(
1377 dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1378 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1379
1380 return true;
1381}
1382
1383/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1384/// sizes and offsets of impacted basic blocks.
1385void MipsConstantIslandImpl::removeDeadCPEMI(MachineInstr *CPEMI) {
1386 MachineBasicBlock *CPEBB = CPEMI->getParent();
1387 unsigned Size = CPEMI->getOperand(2).getImm();
1388 CPEMI->eraseFromParent();
1389 BBInfo[CPEBB->getNumber()].Size -= Size;
1390 // All succeeding offsets have the current size value added in, fix this.
1391 if (CPEBB->empty()) {
1392 BBInfo[CPEBB->getNumber()].Size = 0;
1393
1394 // This block no longer needs to be aligned.
1395 CPEBB->setAlignment(Align(1));
1396 } else {
1397 // Entries are sorted by descending alignment, so realign from the front.
1398 CPEBB->setAlignment(getCPEAlign(*CPEBB->begin()));
1399 }
1400
1401 adjustBBOffsetsAfter(CPEBB);
1402 // An island has only one predecessor BB and one successor BB. Check if
1403 // this BB's predecessor jumps directly to this BB's successor. This
1404 // shouldn't happen currently.
1405 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1406 // FIXME: remove the empty blocks after all the work is done?
1407}
1408
1409/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1410/// are zero.
1411bool MipsConstantIslandImpl::removeUnusedCPEntries() {
1412 unsigned MadeChange = false;
1413 for (std::vector<CPEntry> &CPEs : CPEntries) {
1414 for (CPEntry &CPE : CPEs) {
1415 if (CPE.RefCount == 0 && CPE.CPEMI) {
1416 removeDeadCPEMI(CPE.CPEMI);
1417 CPE.CPEMI = nullptr;
1418 MadeChange = true;
1419 }
1420 }
1421 }
1422 return MadeChange;
1423}
1424
1425/// isBBInRange - Returns true if the distance between specific MI and
1426/// specific BB can fit in MI's displacement field.
1427bool MipsConstantIslandImpl::isBBInRange(MachineInstr *MI,
1428 MachineBasicBlock *DestBB,
1429 unsigned MaxDisp) {
1430 unsigned PCAdj = 4;
1431 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1432 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1433
1434 LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)
1435 << " from " << printMBBReference(*MI->getParent())
1436 << " max delta=" << MaxDisp << " from " << getOffsetOf(MI)
1437 << " to " << DestOffset << " offset "
1438 << int(DestOffset - BrOffset) << "\t" << *MI);
1439
1440 if (BrOffset <= DestOffset) {
1441 // Branch before the Dest.
1442 if (DestOffset-BrOffset <= MaxDisp)
1443 return true;
1444 } else {
1445 if (BrOffset-DestOffset <= MaxDisp)
1446 return true;
1447 }
1448 return false;
1449}
1450
1451/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1452/// away to fit in its displacement field.
1453bool MipsConstantIslandImpl::fixupImmediateBr(ImmBranch &Br) {
1454 MachineInstr *MI = Br.MI;
1455 unsigned TargetOperand = branchTargetOperand(MI);
1456 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1457
1458 // Check to see if the DestBB is already in-range.
1459 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1460 return false;
1461
1462 if (!Br.isCond)
1463 return fixupUnconditionalBr(Br);
1464 return fixupConditionalBr(Br);
1465}
1466
1467/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1468/// too far away to fit in its displacement field. If the LR register has been
1469/// spilled in the epilogue, then we can use BL to implement a far jump.
1470/// Otherwise, add an intermediate branch instruction to a branch.
1471bool MipsConstantIslandImpl::fixupUnconditionalBr(ImmBranch &Br) {
1472 MachineInstr *MI = Br.MI;
1473 MachineBasicBlock *MBB = MI->getParent();
1474 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1475 // Use BL to implement far jump.
1476 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1477 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1478 Br.MaxDisp = BimmX16MaxDisp;
1479 MI->setDesc(TII->get(Mips::BimmX16));
1480 }
1481 else {
1482 // need to give the math a more careful look here
1483 // this is really a segment address and not
1484 // a PC relative address. FIXME. But I think that
1485 // just reducing the bits by 1 as I've done is correct.
1486 // The basic block we are branching too much be longword aligned.
1487 // we know that RA is saved because we always save it right now.
1488 // this requirement will be relaxed later but we also have an alternate
1489 // way to implement this that I will implement that does not need jal.
1490 // We should have a way to back out this alignment restriction
1491 // if we "can" later. but it is not harmful.
1492 //
1493 DestBB->setAlignment(Align(4));
1494 Br.MaxDisp = ((1<<24)-1) * 2;
1495 MI->setDesc(TII->get(Mips::JalB16));
1496 }
1497 BBInfo[MBB->getNumber()].Size += 2;
1498 adjustBBOffsetsAfter(MBB);
1499 ++NumUBrFixed;
1500
1501 LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI);
1502
1503 return true;
1504}
1505
1506/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1507/// far away to fit in its displacement field. It is converted to an inverse
1508/// conditional branch + an unconditional branch to the destination.
1509bool MipsConstantIslandImpl::fixupConditionalBr(ImmBranch &Br) {
1510 MachineInstr *MI = Br.MI;
1511 unsigned TargetOperand = branchTargetOperand(MI);
1512 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1513 unsigned Opcode = MI->getOpcode();
1514 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1515 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1516
1517 // Check to see if the DestBB is already in-range.
1518 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1519 Br.MaxDisp = LongFormMaxOff;
1520 MI->setDesc(TII->get(LongFormOpcode));
1521 return true;
1522 }
1523
1524 // Add an unconditional branch to the destination and invert the branch
1525 // condition to jump over it:
1526 // bteqz L1
1527 // =>
1528 // bnez L2
1529 // b L1
1530 // L2:
1531
1532 // If the branch is at the end of its MBB and that has a fall-through block,
1533 // direct the updated conditional branch to the fall-through block. Otherwise,
1534 // split the MBB before the next instruction.
1535 MachineBasicBlock *MBB = MI->getParent();
1536 MachineInstr *BMI = &MBB->back();
1537 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1538 unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
1539
1540 ++NumCBrFixed;
1541 if (BMI != MI) {
1542 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1543 BMI->isUnconditionalBranch()) {
1544 // Last MI in the BB is an unconditional branch. Can we simply invert the
1545 // condition and swap destinations:
1546 // beqz L1
1547 // b L2
1548 // =>
1549 // bnez L2
1550 // b L1
1551 unsigned BMITargetOperand = branchTargetOperand(BMI);
1552 MachineBasicBlock *NewDest =
1553 BMI->getOperand(BMITargetOperand).getMBB();
1554 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1555 LLVM_DEBUG(
1556 dbgs() << " Invert Bcc condition and swap its destination with "
1557 << *BMI);
1558 MI->setDesc(TII->get(OppositeBranchOpcode));
1559 BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1560 MI->getOperand(TargetOperand).setMBB(NewDest);
1561 return true;
1562 }
1563 }
1564 }
1565
1566 if (NeedSplit) {
1567 splitBlockBeforeInstr(*MI);
1568 // No need for the branch to the next block. We're adding an unconditional
1569 // branch to the destination.
1570 int delta = TII->getInstSizeInBytes(MBB->back());
1571 BBInfo[MBB->getNumber()].Size -= delta;
1573 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1574 }
1575 MachineBasicBlock *NextBB = &*++MBB->getIterator();
1576
1577 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB)
1578 << " also invert condition and change dest. to "
1579 << printMBBReference(*NextBB) << "\n");
1580
1581 // Insert a new conditional branch and a new unconditional branch.
1582 // Also update the ImmBranch as well as adding a new entry for the new branch.
1583 if (MI->getNumExplicitOperands() == 2) {
1584 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1585 .addReg(MI->getOperand(0).getReg())
1586 .addMBB(NextBB);
1587 } else {
1588 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1589 .addMBB(NextBB);
1590 }
1591 Br.MI = &MBB->back();
1592 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1593 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1594 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1595 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1596 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1597
1598 // Remove the old conditional branch. It may or may not still be in MBB.
1599 BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
1600 MI->eraseFromParent();
1601 adjustBBOffsetsAfter(MBB);
1602 return true;
1603}
1604
1605void MipsConstantIslandImpl::prescanForConstants() {
1606 for (MachineBasicBlock &B : *MF) {
1607 for (MachineInstr &MI : B) {
1608 switch (MI.getDesc().getOpcode()) {
1609 case Mips::LwConstant32: {
1610 PrescannedForConstants = true;
1611 LLVM_DEBUG(dbgs() << "constant island constant " << MI << "\n");
1612 LLVM_DEBUG(dbgs() << "num operands " << MI.getNumOperands() << "\n");
1613 MachineOperand &Literal = MI.getOperand(1);
1614 if (Literal.isImm()) {
1615 int64_t V = Literal.getImm();
1616 LLVM_DEBUG(dbgs() << "literal " << V << "\n");
1617 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
1618 const Constant *C = ConstantInt::getSigned(Int32Ty, V);
1619 unsigned index = MCP->getConstantPoolIndex(C, Align(4));
1620 MI.getOperand(2).ChangeToImmediate(index);
1621 LLVM_DEBUG(dbgs() << "constant island constant " << MI << "\n");
1622 MI.setDesc(TII->get(Mips::LwRxPcTcp16));
1623 MI.removeOperand(1);
1624 MI.removeOperand(1);
1625 MI.addOperand(MachineOperand::CreateCPI(index, 0));
1626 }
1627 break;
1628 }
1629 default:
1630 break;
1631 }
1632 }
1633 }
1634}
1635
1636/// Returns a pass that converts branches to long branches.
1638 return new MipsConstantIslandLegacy();
1639}
1640
1641bool MipsConstantIslandLegacy::runOnMachineFunction(MachineFunction &MF) {
1642 MipsConstantIslandImpl Impl;
1643 return Impl.runOnMachineFunction(MF);
1644}
1645
1646PreservedAnalyses
1649 MipsConstantIslandImpl Impl;
1650 return Impl.runOnMachineFunction(MF)
1653}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool CompareMBBNumbers(const MachineBasicBlock *LHS, const MachineBasicBlock *RHS)
CompareMBBNumbers - Little predicate function to sort the WaterList by MBB ID.
static unsigned getUnconditionalBrDisp(int Opc)
getUnconditionalBrDisp - Returns the maximum displacement that can fit in the specific unconditional ...
static bool BBIsJumpedOver(MachineBasicBlock *MBB)
BBIsJumpedOver - Return true of the specified basic block's only predecessor unconditionally branches...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_PREFERRED_TYPE(T)
\macro LLVM_PREFERRED_TYPE Adjust type of bit-field in debug info.
Definition Compiler.h:770
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define rc(i)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
static unsigned int longformBranchOpcode(unsigned int Opcode)
static unsigned int branchMaxOffsets(unsigned int Opcode)
static bool BBHasFallthrough(MachineBasicBlock *MBB)
BBHasFallthrough - Return true if the specified basic block can fallthrough into the block immediatel...
static unsigned int branchTargetOperand(MachineInstr *MI)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LLVM_ABI void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
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 setAlignment(Align A)
Set alignment of the basic block.
LLVM_ABI void dump() const
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic 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 '...
Align getAlignment() const
Return alignment of the basic block.
MachineInstrBundleIterator< MachineInstr > iterator
Align getConstantPoolAlign() const
Return the alignment required by the whole constant pool, of which the first element must be aligned.
const std::vector< MachineConstantPoolEntry > & getConstants() const
bool isEmpty() const
isEmpty - Return true if this constant pool contains no constants.
LLVM_ABI unsigned getConstantPoolIndex(const Constant *C, Align Alignment)
getConstantPoolIndex - Create a new entry in the constant pool or return an existing one.
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.
void ensureAlignment(Align A)
ensureAlignment - Make sure the function is at least A bytes aligned.
void push_back(MachineBasicBlock *MBB)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
BasicBlockListType::const_iterator const_iterator
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 & addConstantPoolIndex(unsigned Idx, int Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
mop_range operands()
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
bool isUnconditionalBranch(QueryType Type=AnyInBundle) const
Return true if this is a branch which always transfers control flow to some other block.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
int64_t getImm() const
MachineBasicBlock * getMBB() const
void setMBB(MachineBasicBlock *MBB)
static MachineOperand CreateCPI(unsigned Idx, int Offset, unsigned TargetFlags=0)
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const MipsInstrInfo * getInstrInfo() const override
bool inMips16Mode() const
const MipsOptions & getCLOpts() const
bool useConstantIslands() const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
self_iterator getIterator()
Definition ilist_node.h:123
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
FunctionPass * createMipsConstantIslandLegacyPass()
Returns a pass that converts branches to long branches.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition Alignment.h:191
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
APFloat neg(APFloat X)
Returns the negated value of the argument.
Definition APFloat.h:1771
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
unsigned Size
Size - Size of the basic block in bytes.
unsigned postOffset(Align Alignment=Align(1)) const
Compute the offset immediately following this block.
unsigned Offset
Offset - Distance from the beginning of the function to the beginning of this basic block.