1 //===- CSKYConstantIslandPass.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 //
10 // Loading constants inline is expensive on CSKY and it's in general better
11 // to place the constant nearby in code space and then it can be loaded with a
12 // simple 16/32 bit load instruction like lrw.
13 //
14 // The constants can be not just numbers but addresses of functions and labels.
15 // This can be particularly helpful in static relocation mode for embedded
16 // non-linux targets.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "CSKY.h"
21 #include "CSKYConstantPoolValue.h"
22 #include "CSKYMachineFunctionInfo.h"
23 #include "CSKYSubtarget.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineDominators.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineOperand.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/Config/llvm-config.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/Format.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <algorithm>
52 #include <cassert>
53 #include <cstdint>
54 #include <iterator>
55 #include <vector>
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "CSKY-constant-islands"
60 
61 STATISTIC(NumCPEs, "Number of constpool entries");
62 STATISTIC(NumSplit, "Number of uncond branches inserted");
63 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
64 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
65 
66 namespace {
67 
68 using Iter = MachineBasicBlock::iterator;
69 using ReverseIter = MachineBasicBlock::reverse_iterator;
70 
71 /// CSKYConstantIslands - Due to limited PC-relative displacements, CSKY
72 /// requires constant pool entries to be scattered among the instructions
73 /// inside a function.  To do this, it completely ignores the normal LLVM
74 /// constant pool; instead, it places constants wherever it feels like with
75 /// special instructions.
76 ///
77 /// The terminology used in this pass includes:
78 ///   Islands - Clumps of constants placed in the function.
79 ///   Water   - Potential places where an island could be formed.
80 ///   CPE     - A constant pool entry that has been placed somewhere, which
81 ///             tracks a list of users.
82 
83 class CSKYConstantIslands : public MachineFunctionPass {
84   /// BasicBlockInfo - Information about the offset and size of a single
85   /// basic block.
86   struct BasicBlockInfo {
87     /// Offset - Distance from the beginning of the function to the beginning
88     /// of this basic block.
89     ///
90     /// Offsets are computed assuming worst case padding before an aligned
91     /// block. This means that subtracting basic block offsets always gives a
92     /// conservative estimate of the real distance which may be smaller.
93     ///
94     /// Because worst case padding is used, the computed offset of an aligned
95     /// block may not actually be aligned.
96     unsigned Offset = 0;
97 
98     /// Size - Size of the basic block in bytes.  If the block contains
99     /// inline assembly, this is a worst case estimate.
100     ///
101     /// The size does not include any alignment padding whether from the
102     /// beginning of the block, or from an aligned jump table at the end.
103     unsigned Size = 0;
104 
105     BasicBlockInfo() = default;
106 
107     unsigned postOffset() const { return Offset + Size; }
108   };
109 
110   std::vector<BasicBlockInfo> BBInfo;
111 
112   /// WaterList - A sorted list of basic blocks where islands could be placed
113   /// (i.e. blocks that don't fall through to the following block, due
114   /// to a return, unreachable, or unconditional branch).
115   std::vector<MachineBasicBlock *> WaterList;
116 
117   /// NewWaterList - The subset of WaterList that was created since the
118   /// previous iteration by inserting unconditional branches.
119   SmallSet<MachineBasicBlock *, 4> NewWaterList;
120 
121   using water_iterator = std::vector<MachineBasicBlock *>::iterator;
122 
123   /// CPUser - One user of a constant pool, keeping the machine instruction
124   /// pointer, the constant pool being referenced, and the max displacement
125   /// allowed from the instruction to the CP.  The HighWaterMark records the
126   /// highest basic block where a new CPEntry can be placed.  To ensure this
127   /// pass terminates, the CP entries are initially placed at the end of the
128   /// function and then move monotonically to lower addresses.  The
129   /// exception to this rule is when the current CP entry for a particular
130   /// CPUser is out of range, but there is another CP entry for the same
131   /// constant value in range.  We want to use the existing in-range CP
132   /// entry, but if it later moves out of range, the search for new water
133   /// should resume where it left off.  The HighWaterMark is used to record
134   /// that point.
135   struct CPUser {
136     MachineInstr *MI;
137     MachineInstr *CPEMI;
138     MachineBasicBlock *HighWaterMark;
139 
140   private:
141     unsigned MaxDisp;
142 
143   public:
144     bool NegOk;
145 
146     CPUser(MachineInstr *Mi, MachineInstr *Cpemi, unsigned Maxdisp, bool Neg)
147         : MI(Mi), CPEMI(Cpemi), MaxDisp(Maxdisp), NegOk(Neg) {
148       HighWaterMark = CPEMI->getParent();
149     }
150 
151     /// getMaxDisp - Returns the maximum displacement supported by MI.
152     unsigned getMaxDisp() const { return MaxDisp - 16; }
153 
154     void setMaxDisp(unsigned Val) { MaxDisp = Val; }
155   };
156 
157   /// CPUsers - Keep track of all of the machine instructions that use various
158   /// constant pools and their max displacement.
159   std::vector<CPUser> CPUsers;
160 
161   /// CPEntry - One per constant pool entry, keeping the machine instruction
162   /// pointer, the constpool index, and the number of CPUser's which
163   /// reference this entry.
164   struct CPEntry {
165     MachineInstr *CPEMI;
166     unsigned CPI;
167     unsigned RefCount;
168 
169     CPEntry(MachineInstr *Cpemi, unsigned Cpi, unsigned Rc = 0)
170         : CPEMI(Cpemi), CPI(Cpi), RefCount(Rc) {}
171   };
172 
173   /// CPEntries - Keep track of all of the constant pool entry machine
174   /// instructions. For each original constpool index (i.e. those that
175   /// existed upon entry to this pass), it keeps a vector of entries.
176   /// Original elements are cloned as we go along; the clones are
177   /// put in the vector of the original element, but have distinct CPIs.
178   std::vector<std::vector<CPEntry>> CPEntries;
179 
180   /// ImmBranch - One per immediate branch, keeping the machine instruction
181   /// pointer, conditional or unconditional, the max displacement,
182   /// and (if isCond is true) the corresponding unconditional branch
183   /// opcode.
184   struct ImmBranch {
185     MachineInstr *MI;
186     unsigned MaxDisp : 31;
187     bool IsCond : 1;
188     int UncondBr;
189 
190     ImmBranch(MachineInstr *Mi, unsigned Maxdisp, bool Cond, int Ubr)
191         : MI(Mi), MaxDisp(Maxdisp), IsCond(Cond), UncondBr(Ubr) {}
192   };
193 
194   /// ImmBranches - Keep track of all the immediate branch instructions.
195   ///
196   std::vector<ImmBranch> ImmBranches;
197 
198   const CSKYSubtarget *STI = nullptr;
199   const CSKYInstrInfo *TII;
200   CSKYMachineFunctionInfo *MFI;
201   MachineFunction *MF = nullptr;
202   MachineConstantPool *MCP = nullptr;
203 
204   unsigned PICLabelUId;
205 
206   void initPICLabelUId(unsigned UId) { PICLabelUId = UId; }
207 
208   unsigned createPICLabelUId() { return PICLabelUId++; }
209 
210 public:
211   static char ID;
212 
213   CSKYConstantIslands() : MachineFunctionPass(ID) {}
214 
215   StringRef getPassName() const override { return "CSKY Constant Islands"; }
216 
217   bool runOnMachineFunction(MachineFunction &F) override;
218 
219   void getAnalysisUsage(AnalysisUsage &AU) const override {
220     AU.addRequired<MachineDominatorTree>();
221     MachineFunctionPass::getAnalysisUsage(AU);
222   }
223 
224   MachineFunctionProperties getRequiredProperties() const override {
225     return MachineFunctionProperties().set(
226         MachineFunctionProperties::Property::NoVRegs);
227   }
228 
229   void doInitialPlacement(std::vector<MachineInstr *> &CPEMIs);
230   CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
231   Align getCPEAlign(const MachineInstr &CPEMI);
232   void initializeFunctionInfo(const std::vector<MachineInstr *> &CPEMIs);
233   unsigned getOffsetOf(MachineInstr *MI) const;
234   unsigned getUserOffset(CPUser &) const;
235   void dumpBBs();
236 
237   bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, unsigned Disp,
238                        bool NegativeOK);
239   bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
240                        const CPUser &U);
241 
242   void computeBlockSize(MachineBasicBlock *MBB);
243   MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);
244   void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
245   void adjustBBOffsetsAfter(MachineBasicBlock *BB);
246   bool decrementCPEReferenceCount(unsigned CPI, MachineInstr *CPEMI);
247   int findInRangeCPEntry(CPUser &U, unsigned UserOffset);
248   bool findAvailableWater(CPUser &U, unsigned UserOffset,
249                           water_iterator &WaterIter);
250   void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
251                       MachineBasicBlock *&NewMBB);
252   bool handleConstantPoolUser(unsigned CPUserIndex);
253   void removeDeadCPEMI(MachineInstr *CPEMI);
254   bool removeUnusedCPEntries();
255   bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
256                         MachineInstr *CPEMI, unsigned Disp, bool NegOk,
257                         bool DoDump = false);
258   bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water, CPUser &U,
259                       unsigned &Growth);
260   bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
261   bool fixupImmediateBr(ImmBranch &Br);
262   bool fixupConditionalBr(ImmBranch &Br);
263   bool fixupUnconditionalBr(ImmBranch &Br);
264 };
265 } // end anonymous namespace
266 
267 char CSKYConstantIslands::ID = 0;
268 
269 bool CSKYConstantIslands::isOffsetInRange(unsigned UserOffset,
270                                           unsigned TrialOffset,
271                                           const CPUser &U) {
272   return isOffsetInRange(UserOffset, TrialOffset, U.getMaxDisp(), U.NegOk);
273 }
274 
275 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
276 /// print block size and offset information - debugging
277 LLVM_DUMP_METHOD void CSKYConstantIslands::dumpBBs() {
278   for (unsigned J = 0, E = BBInfo.size(); J != E; ++J) {
279     const BasicBlockInfo &BBI = BBInfo[J];
280     dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
281            << format(" size=%#x\n", BBInfo[J].Size);
282   }
283 }
284 #endif
285 
286 bool CSKYConstantIslands::runOnMachineFunction(MachineFunction &Mf) {
287   MF = &Mf;
288   MCP = Mf.getConstantPool();
289   STI = &static_cast<const CSKYSubtarget &>(Mf.getSubtarget());
290 
291   LLVM_DEBUG(dbgs() << "***** CSKYConstantIslands: "
292                     << MCP->getConstants().size() << " CP entries, aligned to "
293                     << MCP->getConstantPoolAlign().value() << " bytes *****\n");
294 
295   TII = STI->getInstrInfo();
296   MFI = MF->getInfo<CSKYMachineFunctionInfo>();
297 
298   // This pass invalidates liveness information when it splits basic blocks.
299   MF->getRegInfo().invalidateLiveness();
300 
301   // Renumber all of the machine basic blocks in the function, guaranteeing that
302   // the numbers agree with the position of the block in the function.
303   MF->RenumberBlocks();
304 
305   bool MadeChange = false;
306 
307   // Perform the initial placement of the constant pool entries.  To start with,
308   // we put them all at the end of the function.
309   std::vector<MachineInstr *> CPEMIs;
310   if (!MCP->isEmpty())
311     doInitialPlacement(CPEMIs);
312 
313   /// The next UID to take is the first unused one.
314   initPICLabelUId(CPEMIs.size());
315 
316   // Do the initial scan of the function, building up information about the
317   // sizes of each block, the location of all the water, and finding all of the
318   // constant pool users.
319   initializeFunctionInfo(CPEMIs);
320   CPEMIs.clear();
321   LLVM_DEBUG(dumpBBs());
322 
323   /// Remove dead constant pool entries.
324   MadeChange |= removeUnusedCPEntries();
325 
326   // Iteratively place constant pool entries and fix up branches until there
327   // is no change.
328   unsigned NoCPIters = 0, NoBRIters = 0;
329   (void)NoBRIters;
330   while (true) {
331     LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
332     bool CPChange = false;
333     for (unsigned I = 0, E = CPUsers.size(); I != E; ++I)
334       CPChange |= handleConstantPoolUser(I);
335     if (CPChange && ++NoCPIters > 30)
336       report_fatal_error("Constant Island pass failed to converge!");
337     LLVM_DEBUG(dumpBBs());
338 
339     // Clear NewWaterList now.  If we split a block for branches, it should
340     // appear as "new water" for the next iteration of constant pool placement.
341     NewWaterList.clear();
342 
343     LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
344     bool BRChange = false;
345     for (unsigned I = 0, E = ImmBranches.size(); I != E; ++I)
346       BRChange |= fixupImmediateBr(ImmBranches[I]);
347     if (BRChange && ++NoBRIters > 30)
348       report_fatal_error("Branch Fix Up pass failed to converge!");
349     LLVM_DEBUG(dumpBBs());
350     if (!CPChange && !BRChange)
351       break;
352     MadeChange = true;
353   }
354 
355   LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
356 
357   BBInfo.clear();
358   WaterList.clear();
359   CPUsers.clear();
360   CPEntries.clear();
361   ImmBranches.clear();
362   return MadeChange;
363 }
364 
365 /// doInitialPlacement - Perform the initial placement of the constant pool
366 /// entries.  To start with, we put them all at the end of the function.
367 void CSKYConstantIslands::doInitialPlacement(
368     std::vector<MachineInstr *> &CPEMIs) {
369   // Create the basic block to hold the CPE's.
370   MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
371   MF->push_back(BB);
372 
373   // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
374   const Align MaxAlign = MCP->getConstantPoolAlign();
375 
376   // Mark the basic block as required by the const-pool.
377   BB->setAlignment(Align(2));
378 
379   // The function needs to be as aligned as the basic blocks. The linker may
380   // move functions around based on their alignment.
381   MF->ensureAlignment(BB->getAlignment());
382 
383   // Order the entries in BB by descending alignment.  That ensures correct
384   // alignment of all entries as long as BB is sufficiently aligned.  Keep
385   // track of the insertion point for each alignment.  We are going to bucket
386   // sort the entries as they are created.
387   SmallVector<MachineBasicBlock::iterator, 8> InsPoint(Log2(MaxAlign) + 1,
388                                                        BB->end());
389 
390   // Add all of the constants from the constant pool to the end block, use an
391   // identity mapping of CPI's to CPE's.
392   const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
393 
394   const DataLayout &TD = MF->getDataLayout();
395   for (unsigned I = 0, E = CPs.size(); I != E; ++I) {
396     unsigned Size = CPs[I].getSizeInBytes(TD);
397     assert(Size >= 4 && "Too small constant pool entry");
398     Align Alignment = CPs[I].getAlign();
399     // Verify that all constant pool entries are a multiple of their alignment.
400     // If not, we would have to pad them out so that instructions stay aligned.
401     assert(isAligned(Alignment, Size) && "CP Entry not multiple of 4 bytes!");
402 
403     // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
404     unsigned LogAlign = Log2(Alignment);
405     MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
406 
407     MachineInstr *CPEMI =
408         BuildMI(*BB, InsAt, DebugLoc(), TII->get(CSKY::CONSTPOOL_ENTRY))
409             .addImm(I)
410             .addConstantPoolIndex(I)
411             .addImm(Size);
412 
413     CPEMIs.push_back(CPEMI);
414 
415     // Ensure that future entries with higher alignment get inserted before
416     // CPEMI. This is bucket sort with iterators.
417     for (unsigned A = LogAlign + 1; A <= Log2(MaxAlign); ++A)
418       if (InsPoint[A] == InsAt)
419         InsPoint[A] = CPEMI;
420     // Add a new CPEntry, but no corresponding CPUser yet.
421     CPEntries.emplace_back(1, CPEntry(CPEMI, I));
422     ++NumCPEs;
423     LLVM_DEBUG(dbgs() << "Moved CPI#" << I << " to end of function, size = "
424                       << Size << ", align = " << Alignment.value() << '\n');
425   }
426   LLVM_DEBUG(BB->dump());
427 }
428 
429 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
430 /// into the block immediately after it.
431 static bool bbHasFallthrough(MachineBasicBlock *MBB) {
432   // Get the next machine basic block in the function.
433   MachineFunction::iterator MBBI = MBB->getIterator();
434   // Can't fall off end of function.
435   if (std::next(MBBI) == MBB->getParent()->end())
436     return false;
437 
438   MachineBasicBlock *NextBB = &*std::next(MBBI);
439   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
440                                         E = MBB->succ_end();
441        I != E; ++I)
442     if (*I == NextBB)
443       return true;
444 
445   return false;
446 }
447 
448 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
449 /// look up the corresponding CPEntry.
450 CSKYConstantIslands::CPEntry *
451 CSKYConstantIslands::findConstPoolEntry(unsigned CPI,
452                                         const MachineInstr *CPEMI) {
453   std::vector<CPEntry> &CPEs = CPEntries[CPI];
454   // Number of entries per constpool index should be small, just do a
455   // linear search.
456   for (unsigned I = 0, E = CPEs.size(); I != E; ++I) {
457     if (CPEs[I].CPEMI == CPEMI)
458       return &CPEs[I];
459   }
460   return nullptr;
461 }
462 
463 /// getCPEAlign - Returns the required alignment of the constant pool entry
464 /// represented by CPEMI.  Alignment is measured in log2(bytes) units.
465 Align CSKYConstantIslands::getCPEAlign(const MachineInstr &CPEMI) {
466   assert(CPEMI.getOpcode() == CSKY::CONSTPOOL_ENTRY);
467 
468   unsigned CPI = CPEMI.getOperand(1).getIndex();
469   assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
470   return MCP->getConstants()[CPI].getAlign();
471 }
472 
473 /// initializeFunctionInfo - Do the initial scan of the function, building up
474 /// information about the sizes of each block, the location of all the water,
475 /// and finding all of the constant pool users.
476 void CSKYConstantIslands::initializeFunctionInfo(
477     const std::vector<MachineInstr *> &CPEMIs) {
478   BBInfo.clear();
479   BBInfo.resize(MF->getNumBlockIDs());
480 
481   // First thing, compute the size of all basic blocks, and see if the function
482   // has any inline assembly in it. If so, we have to be conservative about
483   // alignment assumptions, as we don't know for sure the size of any
484   // instructions in the inline assembly.
485   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
486     computeBlockSize(&*I);
487 
488   // Compute block offsets.
489   adjustBBOffsetsAfter(&MF->front());
490 
491   // Now go back through the instructions and build up our data structures.
492   for (MachineBasicBlock &MBB : *MF) {
493     // If this block doesn't fall through into the next MBB, then this is
494     // 'water' that a constant pool island could be placed.
495     if (!bbHasFallthrough(&MBB))
496       WaterList.push_back(&MBB);
497     for (MachineInstr &MI : MBB) {
498       if (MI.isDebugInstr())
499         continue;
500 
501       int Opc = MI.getOpcode();
502       if (MI.isBranch() && !MI.isIndirectBranch()) {
503         bool IsCond = MI.isConditionalBranch();
504         unsigned Bits = 0;
505         unsigned Scale = 1;
506         int UOpc = CSKY::BR32;
507 
508         switch (MI.getOpcode()) {
509         case CSKY::BR16:
510         case CSKY::BF16:
511         case CSKY::BT16:
512           Bits = 10;
513           Scale = 2;
514           break;
515         default:
516           Bits = 16;
517           Scale = 2;
518           break;
519         }
520 
521         // Record this immediate branch.
522         unsigned MaxOffs = ((1 << (Bits - 1)) - 1) * Scale;
523         ImmBranches.push_back(ImmBranch(&MI, MaxOffs, IsCond, UOpc));
524       }
525 
526       if (Opc == CSKY::CONSTPOOL_ENTRY)
527         continue;
528 
529       // Scan the instructions for constant pool operands.
530       for (unsigned Op = 0, E = MI.getNumOperands(); Op != E; ++Op)
531         if (MI.getOperand(Op).isCPI()) {
532           // We found one.  The addressing mode tells us the max displacement
533           // from the PC that this instruction permits.
534 
535           // Basic size info comes from the TSFlags field.
536           unsigned Bits = 0;
537           unsigned Scale = 1;
538           bool NegOk = false;
539 
540           switch (Opc) {
541           default:
542             llvm_unreachable("Unknown addressing mode for CP reference!");
543           case CSKY::MOVIH32:
544           case CSKY::ORI32:
545             continue;
546           case CSKY::PseudoTLSLA32:
547           case CSKY::JSRI32:
548           case CSKY::JMPI32:
549           case CSKY::LRW32:
550           case CSKY::LRW32_Gen:
551             Bits = 16;
552             Scale = 4;
553             break;
554           case CSKY::GRS32:
555             Bits = 17;
556             Scale = 2;
557             NegOk = true;
558             break;
559           }
560           // Remember that this is a user of a CP entry.
561           unsigned CPI = MI.getOperand(Op).getIndex();
562           MachineInstr *CPEMI = CPEMIs[CPI];
563           unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
564           CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk));
565 
566           // Increment corresponding CPEntry reference count.
567           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
568           assert(CPE && "Cannot find a corresponding CPEntry!");
569           CPE->RefCount++;
570 
571           // Instructions can only use one CP entry, don't bother scanning the
572           // rest of the operands.
573           break;
574         }
575     }
576   }
577 }
578 
579 /// computeBlockSize - Compute the size and some alignment information for MBB.
580 /// This function updates BBInfo directly.
581 void CSKYConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
582   BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
583   BBI.Size = 0;
584 
585   for (const MachineInstr &MI : *MBB)
586     BBI.Size += TII->getInstSizeInBytes(MI);
587 }
588 
589 /// getOffsetOf - Return the current offset of the specified machine instruction
590 /// from the start of the function.  This offset changes as stuff is moved
591 /// around inside the function.
592 unsigned CSKYConstantIslands::getOffsetOf(MachineInstr *MI) const {
593   MachineBasicBlock *MBB = MI->getParent();
594 
595   // The offset is composed of two things: the sum of the sizes of all MBB's
596   // before this instruction's block, and the offset from the start of the block
597   // it is in.
598   unsigned Offset = BBInfo[MBB->getNumber()].Offset;
599 
600   // Sum instructions before MI in MBB.
601   for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
602     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
603     Offset += TII->getInstSizeInBytes(*I);
604   }
605   return Offset;
606 }
607 
608 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
609 /// ID.
610 static bool compareMbbNumbers(const MachineBasicBlock *LHS,
611                               const MachineBasicBlock *RHS) {
612   return LHS->getNumber() < RHS->getNumber();
613 }
614 
615 /// updateForInsertedWaterBlock - When a block is newly inserted into the
616 /// machine function, it upsets all of the block numbers.  Renumber the blocks
617 /// and update the arrays that parallel this numbering.
618 void CSKYConstantIslands::updateForInsertedWaterBlock(
619     MachineBasicBlock *NewBB) {
620   // Renumber the MBB's to keep them consecutive.
621   NewBB->getParent()->RenumberBlocks(NewBB);
622 
623   // Insert an entry into BBInfo to align it properly with the (newly
624   // renumbered) block numbers.
625   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
626 
627   // Next, update WaterList.  Specifically, we need to add NewMBB as having
628   // available water after it.
629   water_iterator IP = llvm::lower_bound(WaterList, NewBB, compareMbbNumbers);
630   WaterList.insert(IP, NewBB);
631 }
632 
633 unsigned CSKYConstantIslands::getUserOffset(CPUser &U) const {
634   unsigned UserOffset = getOffsetOf(U.MI);
635 
636   UserOffset &= ~3u;
637 
638   return UserOffset;
639 }
640 
641 /// Split the basic block containing MI into two blocks, which are joined by
642 /// an unconditional branch.  Update data structures and renumber blocks to
643 /// account for this change and returns the newly created block.
644 MachineBasicBlock *
645 CSKYConstantIslands::splitBlockBeforeInstr(MachineInstr &MI) {
646   MachineBasicBlock *OrigBB = MI.getParent();
647 
648   // Create a new MBB for the code after the OrigBB.
649   MachineBasicBlock *NewBB =
650       MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
651   MachineFunction::iterator MBBI = ++OrigBB->getIterator();
652   MF->insert(MBBI, NewBB);
653 
654   // Splice the instructions starting with MI over to NewBB.
655   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
656 
657   // Add an unconditional branch from OrigBB to NewBB.
658   // Note the new unconditional branch is not being recorded.
659   // There doesn't seem to be meaningful DebugInfo available; this doesn't
660   // correspond to anything in the source.
661 
662   // TODO: Add support for 16bit instr.
663   BuildMI(OrigBB, DebugLoc(), TII->get(CSKY::BR32)).addMBB(NewBB);
664   ++NumSplit;
665 
666   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
667   NewBB->transferSuccessors(OrigBB);
668 
669   // OrigBB branches to NewBB.
670   OrigBB->addSuccessor(NewBB);
671 
672   // Update internal data structures to account for the newly inserted MBB.
673   // This is almost the same as updateForInsertedWaterBlock, except that
674   // the Water goes after OrigBB, not NewBB.
675   MF->RenumberBlocks(NewBB);
676 
677   // Insert an entry into BBInfo to align it properly with the (newly
678   // renumbered) block numbers.
679   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
680 
681   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
682   // available water after it (but not if it's already there, which happens
683   // when splitting before a conditional branch that is followed by an
684   // unconditional branch - in that case we want to insert NewBB).
685   water_iterator IP = llvm::lower_bound(WaterList, OrigBB, compareMbbNumbers);
686   MachineBasicBlock *WaterBB = *IP;
687   if (WaterBB == OrigBB)
688     WaterList.insert(std::next(IP), NewBB);
689   else
690     WaterList.insert(IP, OrigBB);
691   NewWaterList.insert(OrigBB);
692 
693   // Figure out how large the OrigBB is.  As the first half of the original
694   // block, it cannot contain a tablejump.  The size includes
695   // the new jump we added.  (It should be possible to do this without
696   // recounting everything, but it's very confusing, and this is rarely
697   // executed.)
698   computeBlockSize(OrigBB);
699 
700   // Figure out how large the NewMBB is.  As the second half of the original
701   // block, it may contain a tablejump.
702   computeBlockSize(NewBB);
703 
704   // All BBOffsets following these blocks must be modified.
705   adjustBBOffsetsAfter(OrigBB);
706 
707   return NewBB;
708 }
709 
710 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
711 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
712 /// constant pool entry).
713 bool CSKYConstantIslands::isOffsetInRange(unsigned UserOffset,
714                                           unsigned TrialOffset,
715                                           unsigned MaxDisp, bool NegativeOK) {
716   if (UserOffset <= TrialOffset) {
717     // User before the Trial.
718     if (TrialOffset - UserOffset <= MaxDisp)
719       return true;
720   } else if (NegativeOK) {
721     if (UserOffset - TrialOffset <= MaxDisp)
722       return true;
723   }
724   return false;
725 }
726 
727 /// isWaterInRange - Returns true if a CPE placed after the specified
728 /// Water (a basic block) will be in range for the specific MI.
729 ///
730 /// Compute how much the function will grow by inserting a CPE after Water.
731 bool CSKYConstantIslands::isWaterInRange(unsigned UserOffset,
732                                          MachineBasicBlock *Water, CPUser &U,
733                                          unsigned &Growth) {
734   unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
735   unsigned NextBlockOffset;
736   Align NextBlockAlignment;
737   MachineFunction::const_iterator NextBlock = ++Water->getIterator();
738   if (NextBlock == MF->end()) {
739     NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
740     NextBlockAlignment = Align(4);
741   } else {
742     NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
743     NextBlockAlignment = NextBlock->getAlignment();
744   }
745   unsigned Size = U.CPEMI->getOperand(2).getImm();
746   unsigned CPEEnd = CPEOffset + Size;
747 
748   // The CPE may be able to hide in the alignment padding before the next
749   // block. It may also cause more padding to be required if it is more aligned
750   // that the next block.
751   if (CPEEnd > NextBlockOffset) {
752     Growth = CPEEnd - NextBlockOffset;
753     // Compute the padding that would go at the end of the CPE to align the next
754     // block.
755     Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);
756 
757     // If the CPE is to be inserted before the instruction, that will raise
758     // the offset of the instruction. Also account for unknown alignment padding
759     // in blocks between CPE and the user.
760     if (CPEOffset < UserOffset)
761       UserOffset += Growth;
762   } else
763     // CPE fits in existing padding.
764     Growth = 0;
765 
766   return isOffsetInRange(UserOffset, CPEOffset, U);
767 }
768 
769 /// isCPEntryInRange - Returns true if the distance between specific MI and
770 /// specific ConstPool entry instruction can fit in MI's displacement field.
771 bool CSKYConstantIslands::isCPEntryInRange(MachineInstr *MI,
772                                            unsigned UserOffset,
773                                            MachineInstr *CPEMI,
774                                            unsigned MaxDisp, bool NegOk,
775                                            bool DoDump) {
776   unsigned CPEOffset = getOffsetOf(CPEMI);
777 
778   if (DoDump) {
779     LLVM_DEBUG({
780       unsigned Block = MI->getParent()->getNumber();
781       const BasicBlockInfo &BBI = BBInfo[Block];
782       dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
783              << " max delta=" << MaxDisp
784              << format(" insn address=%#x", UserOffset) << " in "
785              << printMBBReference(*MI->getParent()) << ": "
786              << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
787              << format("CPE address=%#x offset=%+d: ", CPEOffset,
788                        int(CPEOffset - UserOffset));
789     });
790   }
791 
792   return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
793 }
794 
795 #ifndef NDEBUG
796 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
797 /// unconditionally branches to its only successor.
798 static bool bbIsJumpedOver(MachineBasicBlock *MBB) {
799   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
800     return false;
801   MachineBasicBlock *Succ = *MBB->succ_begin();
802   MachineBasicBlock *Pred = *MBB->pred_begin();
803   MachineInstr *PredMI = &Pred->back();
804   if (PredMI->getOpcode() == CSKY::BR32 /*TODO: change to 16bit instr. */)
805     return PredMI->getOperand(0).getMBB() == Succ;
806   return false;
807 }
808 #endif
809 
810 void CSKYConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
811   unsigned BBNum = BB->getNumber();
812   for (unsigned I = BBNum + 1, E = MF->getNumBlockIDs(); I < E; ++I) {
813     // Get the offset and known bits at the end of the layout predecessor.
814     // Include the alignment of the current block.
815     unsigned Offset = BBInfo[I - 1].Offset + BBInfo[I - 1].Size;
816     BBInfo[I].Offset = Offset;
817   }
818 }
819 
820 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
821 /// and instruction CPEMI, and decrement its refcount.  If the refcount
822 /// becomes 0 remove the entry and instruction.  Returns true if we removed
823 /// the entry, false if we didn't.
824 bool CSKYConstantIslands::decrementCPEReferenceCount(unsigned CPI,
825                                                      MachineInstr *CPEMI) {
826   // Find the old entry. Eliminate it if it is no longer used.
827   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
828   assert(CPE && "Unexpected!");
829   if (--CPE->RefCount == 0) {
830     removeDeadCPEMI(CPEMI);
831     CPE->CPEMI = nullptr;
832     --NumCPEs;
833     return true;
834   }
835   return false;
836 }
837 
838 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
839 /// if not, see if an in-range clone of the CPE is in range, and if so,
840 /// change the data structures so the user references the clone.  Returns:
841 /// 0 = no existing entry found
842 /// 1 = entry found, and there were no code insertions or deletions
843 /// 2 = entry found, and there were code insertions or deletions
844 int CSKYConstantIslands::findInRangeCPEntry(CPUser &U, unsigned UserOffset) {
845   MachineInstr *UserMI = U.MI;
846   MachineInstr *CPEMI = U.CPEMI;
847 
848   // Check to see if the CPE is already in-range.
849   if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
850                        true)) {
851     LLVM_DEBUG(dbgs() << "In range\n");
852     return 1;
853   }
854 
855   // No.  Look for previously created clones of the CPE that are in range.
856   unsigned CPI = CPEMI->getOperand(1).getIndex();
857   std::vector<CPEntry> &CPEs = CPEntries[CPI];
858   for (unsigned I = 0, E = CPEs.size(); I != E; ++I) {
859     // We already tried this one
860     if (CPEs[I].CPEMI == CPEMI)
861       continue;
862     // Removing CPEs can leave empty entries, skip
863     if (CPEs[I].CPEMI == nullptr)
864       continue;
865     if (isCPEntryInRange(UserMI, UserOffset, CPEs[I].CPEMI, U.getMaxDisp(),
866                          U.NegOk)) {
867       LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
868                         << CPEs[I].CPI << "\n");
869       // Point the CPUser node to the replacement
870       U.CPEMI = CPEs[I].CPEMI;
871       // Change the CPI in the instruction operand to refer to the clone.
872       for (unsigned J = 0, E = UserMI->getNumOperands(); J != E; ++J)
873         if (UserMI->getOperand(J).isCPI()) {
874           UserMI->getOperand(J).setIndex(CPEs[I].CPI);
875           break;
876         }
877       // Adjust the refcount of the clone...
878       CPEs[I].RefCount++;
879       // ...and the original.  If we didn't remove the old entry, none of the
880       // addresses changed, so we don't need another pass.
881       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
882     }
883   }
884   return 0;
885 }
886 
887 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
888 /// the specific unconditional branch instruction.
889 static inline unsigned getUnconditionalBrDisp(int Opc) {
890   unsigned Bits, Scale;
891 
892   switch (Opc) {
893   case CSKY::BR16:
894     Bits = 10;
895     Scale = 2;
896     break;
897   case CSKY::BR32:
898     Bits = 16;
899     Scale = 2;
900     break;
901   default:
902     assert(0);
903     break;
904   }
905 
906   unsigned MaxOffs = ((1 << (Bits - 1)) - 1) * Scale;
907   return MaxOffs;
908 }
909 
910 /// findAvailableWater - Look for an existing entry in the WaterList in which
911 /// we can place the CPE referenced from U so it's within range of U's MI.
912 /// Returns true if found, false if not.  If it returns true, WaterIter
913 /// is set to the WaterList entry.
914 /// To ensure that this pass
915 /// terminates, the CPE location for a particular CPUser is only allowed to
916 /// move to a lower address, so search backward from the end of the list and
917 /// prefer the first water that is in range.
918 bool CSKYConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
919                                              water_iterator &WaterIter) {
920   if (WaterList.empty())
921     return false;
922 
923   unsigned BestGrowth = ~0u;
924   for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
925        --IP) {
926     MachineBasicBlock *WaterBB = *IP;
927     // Check if water is in range and is either at a lower address than the
928     // current "high water mark" or a new water block that was created since
929     // the previous iteration by inserting an unconditional branch.  In the
930     // latter case, we want to allow resetting the high water mark back to
931     // this new water since we haven't seen it before.  Inserting branches
932     // should be relatively uncommon and when it does happen, we want to be
933     // sure to take advantage of it for all the CPEs near that block, so that
934     // we don't insert more branches than necessary.
935     unsigned Growth;
936     if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
937         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
938          NewWaterList.count(WaterBB)) &&
939         Growth < BestGrowth) {
940       // This is the least amount of required padding seen so far.
941       BestGrowth = Growth;
942       WaterIter = IP;
943       LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
944                         << " Growth=" << Growth << '\n');
945 
946       // Keep looking unless it is perfect.
947       if (BestGrowth == 0)
948         return true;
949     }
950     if (IP == B)
951       break;
952   }
953   return BestGrowth != ~0u;
954 }
955 
956 /// createNewWater - No existing WaterList entry will work for
957 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
958 /// block is used if in range, and the conditional branch munged so control
959 /// flow is correct.  Otherwise the block is split to create a hole with an
960 /// unconditional branch around it.  In either case NewMBB is set to a
961 /// block following which the new island can be inserted (the WaterList
962 /// is not adjusted).
963 void CSKYConstantIslands::createNewWater(unsigned CPUserIndex,
964                                          unsigned UserOffset,
965                                          MachineBasicBlock *&NewMBB) {
966   CPUser &U = CPUsers[CPUserIndex];
967   MachineInstr *UserMI = U.MI;
968   MachineInstr *CPEMI = U.CPEMI;
969   MachineBasicBlock *UserMBB = UserMI->getParent();
970   const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
971 
972   // If the block does not end in an unconditional branch already, and if the
973   // end of the block is within range, make new water there.
974   if (bbHasFallthrough(UserMBB)) {
975     // Size of branch to insert.
976     unsigned Delta = 4;
977     // Compute the offset where the CPE will begin.
978     unsigned CPEOffset = UserBBI.postOffset() + Delta;
979 
980     if (isOffsetInRange(UserOffset, CPEOffset, U)) {
981       LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
982                         << format(", expected CPE offset %#x\n", CPEOffset));
983       NewMBB = &*++UserMBB->getIterator();
984       // Add an unconditional branch from UserMBB to fallthrough block.  Record
985       // it for branch lengthening; this new branch will not get out of range,
986       // but if the preceding conditional branch is out of range, the targets
987       // will be exchanged, and the altered branch may be out of range, so the
988       // machinery has to know about it.
989 
990       // TODO: Add support for 16bit instr.
991       int UncondBr = CSKY::BR32;
992       auto *NewMI = BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
993                         .addMBB(NewMBB)
994                         .getInstr();
995       unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
996       ImmBranches.push_back(
997           ImmBranch(&UserMBB->back(), MaxDisp, false, UncondBr));
998       BBInfo[UserMBB->getNumber()].Size += TII->getInstSizeInBytes(*NewMI);
999       adjustBBOffsetsAfter(UserMBB);
1000       return;
1001     }
1002   }
1003 
1004   // What a big block.  Find a place within the block to split it.
1005 
1006   // Try to split the block so it's fully aligned.  Compute the latest split
1007   // point where we can add a 4-byte branch instruction, and then align to
1008   // Align which is the largest possible alignment in the function.
1009   const Align Align = MF->getAlignment();
1010   unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1011   LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1012                               BaseInsertOffset));
1013 
1014   // The 4 in the following is for the unconditional branch we'll be inserting
1015   // Alignment of the island is handled
1016   // inside isOffsetInRange.
1017   BaseInsertOffset -= 4;
1018 
1019   LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1020                     << " la=" << Log2(Align) << '\n');
1021 
1022   // This could point off the end of the block if we've already got constant
1023   // pool entries following this block; only the last one is in the water list.
1024   // Back past any possible branches (allow for a conditional and a maximally
1025   // long unconditional).
1026   if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1027     BaseInsertOffset = UserBBI.postOffset() - 8;
1028     LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1029   }
1030   unsigned EndInsertOffset =
1031       BaseInsertOffset + 4 + CPEMI->getOperand(2).getImm();
1032   MachineBasicBlock::iterator MI = UserMI;
1033   ++MI;
1034   unsigned CPUIndex = CPUserIndex + 1;
1035   unsigned NumCPUsers = CPUsers.size();
1036   for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1037        Offset < BaseInsertOffset;
1038        Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1039     assert(MI != UserMBB->end() && "Fell off end of block");
1040     if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1041       CPUser &U = CPUsers[CPUIndex];
1042       if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1043         // Shift intertion point by one unit of alignment so it is within reach.
1044         BaseInsertOffset -= Align.value();
1045         EndInsertOffset -= Align.value();
1046       }
1047       // This is overly conservative, as we don't account for CPEMIs being
1048       // reused within the block, but it doesn't matter much.  Also assume CPEs
1049       // are added in order with alignment padding.  We may eventually be able
1050       // to pack the aligned CPEs better.
1051       EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1052       CPUIndex++;
1053     }
1054   }
1055 
1056   NewMBB = splitBlockBeforeInstr(*--MI);
1057 }
1058 
1059 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1060 /// is out-of-range.  If so, pick up the constant pool value and move it some
1061 /// place in-range.  Return true if we changed any addresses (thus must run
1062 /// another pass of branch lengthening), false otherwise.
1063 bool CSKYConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1064   CPUser &U = CPUsers[CPUserIndex];
1065   MachineInstr *UserMI = U.MI;
1066   MachineInstr *CPEMI = U.CPEMI;
1067   unsigned CPI = CPEMI->getOperand(1).getIndex();
1068   unsigned Size = CPEMI->getOperand(2).getImm();
1069   // Compute this only once, it's expensive.
1070   unsigned UserOffset = getUserOffset(U);
1071 
1072   // See if the current entry is within range, or there is a clone of it
1073   // in range.
1074   int result = findInRangeCPEntry(U, UserOffset);
1075   if (result == 1)
1076     return false;
1077   if (result == 2)
1078     return true;
1079 
1080   // Look for water where we can place this CPE.
1081   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1082   MachineBasicBlock *NewMBB;
1083   water_iterator IP;
1084   if (findAvailableWater(U, UserOffset, IP)) {
1085     LLVM_DEBUG(dbgs() << "Found water in range\n");
1086     MachineBasicBlock *WaterBB = *IP;
1087 
1088     // If the original WaterList entry was "new water" on this iteration,
1089     // propagate that to the new island.  This is just keeping NewWaterList
1090     // updated to match the WaterList, which will be updated below.
1091     if (NewWaterList.erase(WaterBB))
1092       NewWaterList.insert(NewIsland);
1093 
1094     // The new CPE goes before the following block (NewMBB).
1095     NewMBB = &*++WaterBB->getIterator();
1096   } else {
1097     LLVM_DEBUG(dbgs() << "No water found\n");
1098     createNewWater(CPUserIndex, UserOffset, NewMBB);
1099 
1100     // splitBlockBeforeInstr adds to WaterList, which is important when it is
1101     // called while handling branches so that the water will be seen on the
1102     // next iteration for constant pools, but in this context, we don't want
1103     // it.  Check for this so it will be removed from the WaterList.
1104     // Also remove any entry from NewWaterList.
1105     MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
1106     IP = llvm::find(WaterList, WaterBB);
1107     if (IP != WaterList.end())
1108       NewWaterList.erase(WaterBB);
1109 
1110     // We are adding new water.  Update NewWaterList.
1111     NewWaterList.insert(NewIsland);
1112   }
1113 
1114   // Remove the original WaterList entry; we want subsequent insertions in
1115   // this vicinity to go after the one we're about to insert.  This
1116   // considerably reduces the number of times we have to move the same CPE
1117   // more than once and is also important to ensure the algorithm terminates.
1118   if (IP != WaterList.end())
1119     WaterList.erase(IP);
1120 
1121   // Okay, we know we can put an island before NewMBB now, do it!
1122   MF->insert(NewMBB->getIterator(), NewIsland);
1123 
1124   // Update internal data structures to account for the newly inserted MBB.
1125   updateForInsertedWaterBlock(NewIsland);
1126 
1127   // Decrement the old entry, and remove it if refcount becomes 0.
1128   decrementCPEReferenceCount(CPI, CPEMI);
1129 
1130   // No existing clone of this CPE is within range.
1131   // We will be generating a new clone.  Get a UID for it.
1132   unsigned ID = createPICLabelUId();
1133 
1134   // Now that we have an island to add the CPE to, clone the original CPE and
1135   // add it to the island.
1136   U.HighWaterMark = NewIsland;
1137   U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(CSKY::CONSTPOOL_ENTRY))
1138                 .addImm(ID)
1139                 .addConstantPoolIndex(CPI)
1140                 .addImm(Size);
1141   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1142   ++NumCPEs;
1143 
1144   // Mark the basic block as aligned as required by the const-pool entry.
1145   NewIsland->setAlignment(getCPEAlign(*U.CPEMI));
1146 
1147   // Increase the size of the island block to account for the new entry.
1148   BBInfo[NewIsland->getNumber()].Size += Size;
1149   adjustBBOffsetsAfter(&*--NewIsland->getIterator());
1150 
1151   // Finally, change the CPI in the instruction operand to be ID.
1152   for (unsigned I = 0, E = UserMI->getNumOperands(); I != E; ++I)
1153     if (UserMI->getOperand(I).isCPI()) {
1154       UserMI->getOperand(I).setIndex(ID);
1155       break;
1156     }
1157 
1158   LLVM_DEBUG(
1159       dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1160              << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1161 
1162   return true;
1163 }
1164 
1165 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1166 /// sizes and offsets of impacted basic blocks.
1167 void CSKYConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1168   MachineBasicBlock *CPEBB = CPEMI->getParent();
1169   unsigned Size = CPEMI->getOperand(2).getImm();
1170   CPEMI->eraseFromParent();
1171   BBInfo[CPEBB->getNumber()].Size -= Size;
1172   // All succeeding offsets have the current size value added in, fix this.
1173   if (CPEBB->empty()) {
1174     BBInfo[CPEBB->getNumber()].Size = 0;
1175 
1176     // This block no longer needs to be aligned.
1177     CPEBB->setAlignment(Align(4));
1178   } else {
1179     // Entries are sorted by descending alignment, so realign from the front.
1180     CPEBB->setAlignment(getCPEAlign(*CPEBB->begin()));
1181   }
1182 
1183   adjustBBOffsetsAfter(CPEBB);
1184   // An island has only one predecessor BB and one successor BB. Check if
1185   // this BB's predecessor jumps directly to this BB's successor. This
1186   // shouldn't happen currently.
1187   assert(!bbIsJumpedOver(CPEBB) && "How did this happen?");
1188   // FIXME: remove the empty blocks after all the work is done?
1189 }
1190 
1191 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1192 /// are zero.
1193 bool CSKYConstantIslands::removeUnusedCPEntries() {
1194   unsigned MadeChange = false;
1195   for (unsigned I = 0, E = CPEntries.size(); I != E; ++I) {
1196     std::vector<CPEntry> &CPEs = CPEntries[I];
1197     for (unsigned J = 0, Ee = CPEs.size(); J != Ee; ++J) {
1198       if (CPEs[J].RefCount == 0 && CPEs[J].CPEMI) {
1199         removeDeadCPEMI(CPEs[J].CPEMI);
1200         CPEs[J].CPEMI = nullptr;
1201         MadeChange = true;
1202       }
1203     }
1204   }
1205   return MadeChange;
1206 }
1207 
1208 /// isBBInRange - Returns true if the distance between specific MI and
1209 /// specific BB can fit in MI's displacement field.
1210 bool CSKYConstantIslands::isBBInRange(MachineInstr *MI,
1211                                       MachineBasicBlock *DestBB,
1212                                       unsigned MaxDisp) {
1213   unsigned BrOffset = getOffsetOf(MI);
1214   unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1215 
1216   LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)
1217                     << " from " << printMBBReference(*MI->getParent())
1218                     << " max delta=" << MaxDisp << " from " << getOffsetOf(MI)
1219                     << " to " << DestOffset << " offset "
1220                     << int(DestOffset - BrOffset) << "\t" << *MI);
1221 
1222   if (BrOffset <= DestOffset) {
1223     // Branch before the Dest.
1224     if (DestOffset - BrOffset <= MaxDisp)
1225       return true;
1226   } else {
1227     if (BrOffset - DestOffset <= MaxDisp)
1228       return true;
1229   }
1230   return false;
1231 }
1232 
1233 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1234 /// away to fit in its displacement field.
1235 bool CSKYConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1236   MachineInstr *MI = Br.MI;
1237   MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);
1238 
1239   // Check to see if the DestBB is already in-range.
1240   if (isBBInRange(MI, DestBB, Br.MaxDisp))
1241     return false;
1242 
1243   if (!Br.IsCond)
1244     return fixupUnconditionalBr(Br);
1245   return fixupConditionalBr(Br);
1246 }
1247 
1248 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1249 /// too far away to fit in its displacement field. If the LR register has been
1250 /// spilled in the epilogue, then we can use BSR to implement a far jump.
1251 /// Otherwise, add an intermediate branch instruction to a branch.
1252 bool CSKYConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1253   MachineInstr *MI = Br.MI;
1254   MachineBasicBlock *MBB = MI->getParent();
1255 
1256   if (!MFI->isLRSpilled())
1257     report_fatal_error("underestimated function size");
1258 
1259   // Use BSR to implement far jump.
1260   Br.MaxDisp = ((1 << (26 - 1)) - 1) * 2;
1261   MI->setDesc(TII->get(CSKY::BSR32_BR));
1262   BBInfo[MBB->getNumber()].Size += 4;
1263   adjustBBOffsetsAfter(MBB);
1264   ++NumUBrFixed;
1265 
1266   LLVM_DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1267 
1268   return true;
1269 }
1270 
1271 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1272 /// far away to fit in its displacement field. It is converted to an inverse
1273 /// conditional branch + an unconditional branch to the destination.
1274 bool CSKYConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1275   MachineInstr *MI = Br.MI;
1276   MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);
1277 
1278   SmallVector<MachineOperand, 4> Cond;
1279   Cond.push_back(MachineOperand::CreateImm(MI->getOpcode()));
1280   Cond.push_back(MI->getOperand(0));
1281   TII->reverseBranchCondition(Cond);
1282 
1283   // Add an unconditional branch to the destination and invert the branch
1284   // condition to jump over it:
1285   // bteqz L1
1286   // =>
1287   // bnez L2
1288   // b   L1
1289   // L2:
1290 
1291   // If the branch is at the end of its MBB and that has a fall-through block,
1292   // direct the updated conditional branch to the fall-through block. Otherwise,
1293   // split the MBB before the next instruction.
1294   MachineBasicBlock *MBB = MI->getParent();
1295   MachineInstr *BMI = &MBB->back();
1296   bool NeedSplit = (BMI != MI) || !bbHasFallthrough(MBB);
1297 
1298   ++NumCBrFixed;
1299   if (BMI != MI) {
1300     if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1301         BMI->isUnconditionalBranch()) {
1302       // Last MI in the BB is an unconditional branch. Can we simply invert the
1303       // condition and swap destinations:
1304       // beqz L1
1305       // b   L2
1306       // =>
1307       // bnez L2
1308       // b   L1
1309       MachineBasicBlock *NewDest = TII->getBranchDestBlock(*BMI);
1310       if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1311         LLVM_DEBUG(
1312             dbgs() << "  Invert Bcc condition and swap its destination with "
1313                    << *BMI);
1314         BMI->getOperand(BMI->getNumExplicitOperands() - 1).setMBB(DestBB);
1315         MI->getOperand(MI->getNumExplicitOperands() - 1).setMBB(NewDest);
1316 
1317         MI->setDesc(TII->get(Cond[0].getImm()));
1318         return true;
1319       }
1320     }
1321   }
1322 
1323   if (NeedSplit) {
1324     splitBlockBeforeInstr(*MI);
1325     // No need for the branch to the next block. We're adding an unconditional
1326     // branch to the destination.
1327     int Delta = TII->getInstSizeInBytes(MBB->back());
1328     BBInfo[MBB->getNumber()].Size -= Delta;
1329     MBB->back().eraseFromParent();
1330     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1331 
1332     // The conditional successor will be swapped between the BBs after this, so
1333     // update CFG.
1334     MBB->addSuccessor(DestBB);
1335     std::next(MBB->getIterator())->removeSuccessor(DestBB);
1336   }
1337   MachineBasicBlock *NextBB = &*++MBB->getIterator();
1338 
1339   LLVM_DEBUG(dbgs() << "  Insert B to " << printMBBReference(*DestBB)
1340                     << " also invert condition and change dest. to "
1341                     << printMBBReference(*NextBB) << "\n");
1342 
1343   // Insert a new conditional branch and a new unconditional branch.
1344   // Also update the ImmBranch as well as adding a new entry for the new branch.
1345 
1346   BuildMI(MBB, DebugLoc(), TII->get(Cond[0].getImm()))
1347       .addReg(MI->getOperand(0).getReg())
1348       .addMBB(NextBB);
1349 
1350   Br.MI = &MBB->back();
1351   BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1352   BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1353   BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1354   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1355   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1356 
1357   // Remove the old conditional branch.  It may or may not still be in MBB.
1358   BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
1359   MI->eraseFromParent();
1360   adjustBBOffsetsAfter(MBB);
1361   return true;
1362 }
1363 
1364 /// Returns a pass that converts branches to long branches.
1365 FunctionPass *llvm::createCSKYConstantIslandPass() {
1366   return new CSKYConstantIslands();
1367 }
1368 
1369 INITIALIZE_PASS(CSKYConstantIslands, DEBUG_TYPE,
1370                 "CSKY constant island placement and branch shortening pass",
1371                 false, false)
1372