xref: /freebsd/contrib/llvm-project/llvm/lib/Target/CSKY/CSKYConstantIslandPass.cpp (revision 38a52bd3b5cac3da6f7f6eef3dd050e6aa08ebb3)
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::f2FLRW_S:
555           case CSKY::f2FLRW_D:
556             Bits = 8;
557             Scale = 4;
558             break;
559           case CSKY::GRS32:
560             Bits = 17;
561             Scale = 2;
562             NegOk = true;
563             break;
564           }
565           // Remember that this is a user of a CP entry.
566           unsigned CPI = MI.getOperand(Op).getIndex();
567           MachineInstr *CPEMI = CPEMIs[CPI];
568           unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
569           CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk));
570 
571           // Increment corresponding CPEntry reference count.
572           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
573           assert(CPE && "Cannot find a corresponding CPEntry!");
574           CPE->RefCount++;
575 
576           // Instructions can only use one CP entry, don't bother scanning the
577           // rest of the operands.
578           break;
579         }
580     }
581   }
582 }
583 
584 /// computeBlockSize - Compute the size and some alignment information for MBB.
585 /// This function updates BBInfo directly.
586 void CSKYConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
587   BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
588   BBI.Size = 0;
589 
590   for (const MachineInstr &MI : *MBB)
591     BBI.Size += TII->getInstSizeInBytes(MI);
592 }
593 
594 /// getOffsetOf - Return the current offset of the specified machine instruction
595 /// from the start of the function.  This offset changes as stuff is moved
596 /// around inside the function.
597 unsigned CSKYConstantIslands::getOffsetOf(MachineInstr *MI) const {
598   MachineBasicBlock *MBB = MI->getParent();
599 
600   // The offset is composed of two things: the sum of the sizes of all MBB's
601   // before this instruction's block, and the offset from the start of the block
602   // it is in.
603   unsigned Offset = BBInfo[MBB->getNumber()].Offset;
604 
605   // Sum instructions before MI in MBB.
606   for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
607     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
608     Offset += TII->getInstSizeInBytes(*I);
609   }
610   return Offset;
611 }
612 
613 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
614 /// ID.
615 static bool compareMbbNumbers(const MachineBasicBlock *LHS,
616                               const MachineBasicBlock *RHS) {
617   return LHS->getNumber() < RHS->getNumber();
618 }
619 
620 /// updateForInsertedWaterBlock - When a block is newly inserted into the
621 /// machine function, it upsets all of the block numbers.  Renumber the blocks
622 /// and update the arrays that parallel this numbering.
623 void CSKYConstantIslands::updateForInsertedWaterBlock(
624     MachineBasicBlock *NewBB) {
625   // Renumber the MBB's to keep them consecutive.
626   NewBB->getParent()->RenumberBlocks(NewBB);
627 
628   // Insert an entry into BBInfo to align it properly with the (newly
629   // renumbered) block numbers.
630   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
631 
632   // Next, update WaterList.  Specifically, we need to add NewMBB as having
633   // available water after it.
634   water_iterator IP = llvm::lower_bound(WaterList, NewBB, compareMbbNumbers);
635   WaterList.insert(IP, NewBB);
636 }
637 
638 unsigned CSKYConstantIslands::getUserOffset(CPUser &U) const {
639   unsigned UserOffset = getOffsetOf(U.MI);
640 
641   UserOffset &= ~3u;
642 
643   return UserOffset;
644 }
645 
646 /// Split the basic block containing MI into two blocks, which are joined by
647 /// an unconditional branch.  Update data structures and renumber blocks to
648 /// account for this change and returns the newly created block.
649 MachineBasicBlock *
650 CSKYConstantIslands::splitBlockBeforeInstr(MachineInstr &MI) {
651   MachineBasicBlock *OrigBB = MI.getParent();
652 
653   // Create a new MBB for the code after the OrigBB.
654   MachineBasicBlock *NewBB =
655       MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
656   MachineFunction::iterator MBBI = ++OrigBB->getIterator();
657   MF->insert(MBBI, NewBB);
658 
659   // Splice the instructions starting with MI over to NewBB.
660   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
661 
662   // Add an unconditional branch from OrigBB to NewBB.
663   // Note the new unconditional branch is not being recorded.
664   // There doesn't seem to be meaningful DebugInfo available; this doesn't
665   // correspond to anything in the source.
666 
667   // TODO: Add support for 16bit instr.
668   BuildMI(OrigBB, DebugLoc(), TII->get(CSKY::BR32)).addMBB(NewBB);
669   ++NumSplit;
670 
671   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
672   NewBB->transferSuccessors(OrigBB);
673 
674   // OrigBB branches to NewBB.
675   OrigBB->addSuccessor(NewBB);
676 
677   // Update internal data structures to account for the newly inserted MBB.
678   // This is almost the same as updateForInsertedWaterBlock, except that
679   // the Water goes after OrigBB, not NewBB.
680   MF->RenumberBlocks(NewBB);
681 
682   // Insert an entry into BBInfo to align it properly with the (newly
683   // renumbered) block numbers.
684   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
685 
686   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
687   // available water after it (but not if it's already there, which happens
688   // when splitting before a conditional branch that is followed by an
689   // unconditional branch - in that case we want to insert NewBB).
690   water_iterator IP = llvm::lower_bound(WaterList, OrigBB, compareMbbNumbers);
691   MachineBasicBlock *WaterBB = *IP;
692   if (WaterBB == OrigBB)
693     WaterList.insert(std::next(IP), NewBB);
694   else
695     WaterList.insert(IP, OrigBB);
696   NewWaterList.insert(OrigBB);
697 
698   // Figure out how large the OrigBB is.  As the first half of the original
699   // block, it cannot contain a tablejump.  The size includes
700   // the new jump we added.  (It should be possible to do this without
701   // recounting everything, but it's very confusing, and this is rarely
702   // executed.)
703   computeBlockSize(OrigBB);
704 
705   // Figure out how large the NewMBB is.  As the second half of the original
706   // block, it may contain a tablejump.
707   computeBlockSize(NewBB);
708 
709   // All BBOffsets following these blocks must be modified.
710   adjustBBOffsetsAfter(OrigBB);
711 
712   return NewBB;
713 }
714 
715 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
716 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
717 /// constant pool entry).
718 bool CSKYConstantIslands::isOffsetInRange(unsigned UserOffset,
719                                           unsigned TrialOffset,
720                                           unsigned MaxDisp, bool NegativeOK) {
721   if (UserOffset <= TrialOffset) {
722     // User before the Trial.
723     if (TrialOffset - UserOffset <= MaxDisp)
724       return true;
725   } else if (NegativeOK) {
726     if (UserOffset - TrialOffset <= MaxDisp)
727       return true;
728   }
729   return false;
730 }
731 
732 /// isWaterInRange - Returns true if a CPE placed after the specified
733 /// Water (a basic block) will be in range for the specific MI.
734 ///
735 /// Compute how much the function will grow by inserting a CPE after Water.
736 bool CSKYConstantIslands::isWaterInRange(unsigned UserOffset,
737                                          MachineBasicBlock *Water, CPUser &U,
738                                          unsigned &Growth) {
739   unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
740   unsigned NextBlockOffset;
741   Align NextBlockAlignment;
742   MachineFunction::const_iterator NextBlock = ++Water->getIterator();
743   if (NextBlock == MF->end()) {
744     NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
745     NextBlockAlignment = Align(4);
746   } else {
747     NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
748     NextBlockAlignment = NextBlock->getAlignment();
749   }
750   unsigned Size = U.CPEMI->getOperand(2).getImm();
751   unsigned CPEEnd = CPEOffset + Size;
752 
753   // The CPE may be able to hide in the alignment padding before the next
754   // block. It may also cause more padding to be required if it is more aligned
755   // that the next block.
756   if (CPEEnd > NextBlockOffset) {
757     Growth = CPEEnd - NextBlockOffset;
758     // Compute the padding that would go at the end of the CPE to align the next
759     // block.
760     Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);
761 
762     // If the CPE is to be inserted before the instruction, that will raise
763     // the offset of the instruction. Also account for unknown alignment padding
764     // in blocks between CPE and the user.
765     if (CPEOffset < UserOffset)
766       UserOffset += Growth;
767   } else
768     // CPE fits in existing padding.
769     Growth = 0;
770 
771   return isOffsetInRange(UserOffset, CPEOffset, U);
772 }
773 
774 /// isCPEntryInRange - Returns true if the distance between specific MI and
775 /// specific ConstPool entry instruction can fit in MI's displacement field.
776 bool CSKYConstantIslands::isCPEntryInRange(MachineInstr *MI,
777                                            unsigned UserOffset,
778                                            MachineInstr *CPEMI,
779                                            unsigned MaxDisp, bool NegOk,
780                                            bool DoDump) {
781   unsigned CPEOffset = getOffsetOf(CPEMI);
782 
783   if (DoDump) {
784     LLVM_DEBUG({
785       unsigned Block = MI->getParent()->getNumber();
786       const BasicBlockInfo &BBI = BBInfo[Block];
787       dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
788              << " max delta=" << MaxDisp
789              << format(" insn address=%#x", UserOffset) << " in "
790              << printMBBReference(*MI->getParent()) << ": "
791              << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
792              << format("CPE address=%#x offset=%+d: ", CPEOffset,
793                        int(CPEOffset - UserOffset));
794     });
795   }
796 
797   return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
798 }
799 
800 #ifndef NDEBUG
801 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
802 /// unconditionally branches to its only successor.
803 static bool bbIsJumpedOver(MachineBasicBlock *MBB) {
804   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
805     return false;
806   MachineBasicBlock *Succ = *MBB->succ_begin();
807   MachineBasicBlock *Pred = *MBB->pred_begin();
808   MachineInstr *PredMI = &Pred->back();
809   if (PredMI->getOpcode() == CSKY::BR32 /*TODO: change to 16bit instr. */)
810     return PredMI->getOperand(0).getMBB() == Succ;
811   return false;
812 }
813 #endif
814 
815 void CSKYConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
816   unsigned BBNum = BB->getNumber();
817   for (unsigned I = BBNum + 1, E = MF->getNumBlockIDs(); I < E; ++I) {
818     // Get the offset and known bits at the end of the layout predecessor.
819     // Include the alignment of the current block.
820     unsigned Offset = BBInfo[I - 1].Offset + BBInfo[I - 1].Size;
821     BBInfo[I].Offset = Offset;
822   }
823 }
824 
825 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
826 /// and instruction CPEMI, and decrement its refcount.  If the refcount
827 /// becomes 0 remove the entry and instruction.  Returns true if we removed
828 /// the entry, false if we didn't.
829 bool CSKYConstantIslands::decrementCPEReferenceCount(unsigned CPI,
830                                                      MachineInstr *CPEMI) {
831   // Find the old entry. Eliminate it if it is no longer used.
832   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
833   assert(CPE && "Unexpected!");
834   if (--CPE->RefCount == 0) {
835     removeDeadCPEMI(CPEMI);
836     CPE->CPEMI = nullptr;
837     --NumCPEs;
838     return true;
839   }
840   return false;
841 }
842 
843 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
844 /// if not, see if an in-range clone of the CPE is in range, and if so,
845 /// change the data structures so the user references the clone.  Returns:
846 /// 0 = no existing entry found
847 /// 1 = entry found, and there were no code insertions or deletions
848 /// 2 = entry found, and there were code insertions or deletions
849 int CSKYConstantIslands::findInRangeCPEntry(CPUser &U, unsigned UserOffset) {
850   MachineInstr *UserMI = U.MI;
851   MachineInstr *CPEMI = U.CPEMI;
852 
853   // Check to see if the CPE is already in-range.
854   if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
855                        true)) {
856     LLVM_DEBUG(dbgs() << "In range\n");
857     return 1;
858   }
859 
860   // No.  Look for previously created clones of the CPE that are in range.
861   unsigned CPI = CPEMI->getOperand(1).getIndex();
862   std::vector<CPEntry> &CPEs = CPEntries[CPI];
863   for (unsigned I = 0, E = CPEs.size(); I != E; ++I) {
864     // We already tried this one
865     if (CPEs[I].CPEMI == CPEMI)
866       continue;
867     // Removing CPEs can leave empty entries, skip
868     if (CPEs[I].CPEMI == nullptr)
869       continue;
870     if (isCPEntryInRange(UserMI, UserOffset, CPEs[I].CPEMI, U.getMaxDisp(),
871                          U.NegOk)) {
872       LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
873                         << CPEs[I].CPI << "\n");
874       // Point the CPUser node to the replacement
875       U.CPEMI = CPEs[I].CPEMI;
876       // Change the CPI in the instruction operand to refer to the clone.
877       for (unsigned J = 0, E = UserMI->getNumOperands(); J != E; ++J)
878         if (UserMI->getOperand(J).isCPI()) {
879           UserMI->getOperand(J).setIndex(CPEs[I].CPI);
880           break;
881         }
882       // Adjust the refcount of the clone...
883       CPEs[I].RefCount++;
884       // ...and the original.  If we didn't remove the old entry, none of the
885       // addresses changed, so we don't need another pass.
886       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
887     }
888   }
889   return 0;
890 }
891 
892 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
893 /// the specific unconditional branch instruction.
894 static inline unsigned getUnconditionalBrDisp(int Opc) {
895   unsigned Bits, Scale;
896 
897   switch (Opc) {
898   case CSKY::BR16:
899     Bits = 10;
900     Scale = 2;
901     break;
902   case CSKY::BR32:
903     Bits = 16;
904     Scale = 2;
905     break;
906   default:
907     assert(0);
908     break;
909   }
910 
911   unsigned MaxOffs = ((1 << (Bits - 1)) - 1) * Scale;
912   return MaxOffs;
913 }
914 
915 /// findAvailableWater - Look for an existing entry in the WaterList in which
916 /// we can place the CPE referenced from U so it's within range of U's MI.
917 /// Returns true if found, false if not.  If it returns true, WaterIter
918 /// is set to the WaterList entry.
919 /// To ensure that this pass
920 /// terminates, the CPE location for a particular CPUser is only allowed to
921 /// move to a lower address, so search backward from the end of the list and
922 /// prefer the first water that is in range.
923 bool CSKYConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
924                                              water_iterator &WaterIter) {
925   if (WaterList.empty())
926     return false;
927 
928   unsigned BestGrowth = ~0u;
929   for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
930        --IP) {
931     MachineBasicBlock *WaterBB = *IP;
932     // Check if water is in range and is either at a lower address than the
933     // current "high water mark" or a new water block that was created since
934     // the previous iteration by inserting an unconditional branch.  In the
935     // latter case, we want to allow resetting the high water mark back to
936     // this new water since we haven't seen it before.  Inserting branches
937     // should be relatively uncommon and when it does happen, we want to be
938     // sure to take advantage of it for all the CPEs near that block, so that
939     // we don't insert more branches than necessary.
940     unsigned Growth;
941     if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
942         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
943          NewWaterList.count(WaterBB)) &&
944         Growth < BestGrowth) {
945       // This is the least amount of required padding seen so far.
946       BestGrowth = Growth;
947       WaterIter = IP;
948       LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
949                         << " Growth=" << Growth << '\n');
950 
951       // Keep looking unless it is perfect.
952       if (BestGrowth == 0)
953         return true;
954     }
955     if (IP == B)
956       break;
957   }
958   return BestGrowth != ~0u;
959 }
960 
961 /// createNewWater - No existing WaterList entry will work for
962 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
963 /// block is used if in range, and the conditional branch munged so control
964 /// flow is correct.  Otherwise the block is split to create a hole with an
965 /// unconditional branch around it.  In either case NewMBB is set to a
966 /// block following which the new island can be inserted (the WaterList
967 /// is not adjusted).
968 void CSKYConstantIslands::createNewWater(unsigned CPUserIndex,
969                                          unsigned UserOffset,
970                                          MachineBasicBlock *&NewMBB) {
971   CPUser &U = CPUsers[CPUserIndex];
972   MachineInstr *UserMI = U.MI;
973   MachineInstr *CPEMI = U.CPEMI;
974   MachineBasicBlock *UserMBB = UserMI->getParent();
975   const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
976 
977   // If the block does not end in an unconditional branch already, and if the
978   // end of the block is within range, make new water there.
979   if (bbHasFallthrough(UserMBB)) {
980     // Size of branch to insert.
981     unsigned Delta = 4;
982     // Compute the offset where the CPE will begin.
983     unsigned CPEOffset = UserBBI.postOffset() + Delta;
984 
985     if (isOffsetInRange(UserOffset, CPEOffset, U)) {
986       LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
987                         << format(", expected CPE offset %#x\n", CPEOffset));
988       NewMBB = &*++UserMBB->getIterator();
989       // Add an unconditional branch from UserMBB to fallthrough block.  Record
990       // it for branch lengthening; this new branch will not get out of range,
991       // but if the preceding conditional branch is out of range, the targets
992       // will be exchanged, and the altered branch may be out of range, so the
993       // machinery has to know about it.
994 
995       // TODO: Add support for 16bit instr.
996       int UncondBr = CSKY::BR32;
997       auto *NewMI = BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
998                         .addMBB(NewMBB)
999                         .getInstr();
1000       unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1001       ImmBranches.push_back(
1002           ImmBranch(&UserMBB->back(), MaxDisp, false, UncondBr));
1003       BBInfo[UserMBB->getNumber()].Size += TII->getInstSizeInBytes(*NewMI);
1004       adjustBBOffsetsAfter(UserMBB);
1005       return;
1006     }
1007   }
1008 
1009   // What a big block.  Find a place within the block to split it.
1010 
1011   // Try to split the block so it's fully aligned.  Compute the latest split
1012   // point where we can add a 4-byte branch instruction, and then align to
1013   // Align which is the largest possible alignment in the function.
1014   const Align Align = MF->getAlignment();
1015   unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1016   LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1017                               BaseInsertOffset));
1018 
1019   // The 4 in the following is for the unconditional branch we'll be inserting
1020   // Alignment of the island is handled
1021   // inside isOffsetInRange.
1022   BaseInsertOffset -= 4;
1023 
1024   LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1025                     << " la=" << Log2(Align) << '\n');
1026 
1027   // This could point off the end of the block if we've already got constant
1028   // pool entries following this block; only the last one is in the water list.
1029   // Back past any possible branches (allow for a conditional and a maximally
1030   // long unconditional).
1031   if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1032     BaseInsertOffset = UserBBI.postOffset() - 8;
1033     LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1034   }
1035   unsigned EndInsertOffset =
1036       BaseInsertOffset + 4 + CPEMI->getOperand(2).getImm();
1037   MachineBasicBlock::iterator MI = UserMI;
1038   ++MI;
1039   unsigned CPUIndex = CPUserIndex + 1;
1040   unsigned NumCPUsers = CPUsers.size();
1041   for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1042        Offset < BaseInsertOffset;
1043        Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1044     assert(MI != UserMBB->end() && "Fell off end of block");
1045     if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1046       CPUser &U = CPUsers[CPUIndex];
1047       if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1048         // Shift intertion point by one unit of alignment so it is within reach.
1049         BaseInsertOffset -= Align.value();
1050         EndInsertOffset -= Align.value();
1051       }
1052       // This is overly conservative, as we don't account for CPEMIs being
1053       // reused within the block, but it doesn't matter much.  Also assume CPEs
1054       // are added in order with alignment padding.  We may eventually be able
1055       // to pack the aligned CPEs better.
1056       EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1057       CPUIndex++;
1058     }
1059   }
1060 
1061   NewMBB = splitBlockBeforeInstr(*--MI);
1062 }
1063 
1064 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1065 /// is out-of-range.  If so, pick up the constant pool value and move it some
1066 /// place in-range.  Return true if we changed any addresses (thus must run
1067 /// another pass of branch lengthening), false otherwise.
1068 bool CSKYConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1069   CPUser &U = CPUsers[CPUserIndex];
1070   MachineInstr *UserMI = U.MI;
1071   MachineInstr *CPEMI = U.CPEMI;
1072   unsigned CPI = CPEMI->getOperand(1).getIndex();
1073   unsigned Size = CPEMI->getOperand(2).getImm();
1074   // Compute this only once, it's expensive.
1075   unsigned UserOffset = getUserOffset(U);
1076 
1077   // See if the current entry is within range, or there is a clone of it
1078   // in range.
1079   int result = findInRangeCPEntry(U, UserOffset);
1080   if (result == 1)
1081     return false;
1082   if (result == 2)
1083     return true;
1084 
1085   // Look for water where we can place this CPE.
1086   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1087   MachineBasicBlock *NewMBB;
1088   water_iterator IP;
1089   if (findAvailableWater(U, UserOffset, IP)) {
1090     LLVM_DEBUG(dbgs() << "Found water in range\n");
1091     MachineBasicBlock *WaterBB = *IP;
1092 
1093     // If the original WaterList entry was "new water" on this iteration,
1094     // propagate that to the new island.  This is just keeping NewWaterList
1095     // updated to match the WaterList, which will be updated below.
1096     if (NewWaterList.erase(WaterBB))
1097       NewWaterList.insert(NewIsland);
1098 
1099     // The new CPE goes before the following block (NewMBB).
1100     NewMBB = &*++WaterBB->getIterator();
1101   } else {
1102     LLVM_DEBUG(dbgs() << "No water found\n");
1103     createNewWater(CPUserIndex, UserOffset, NewMBB);
1104 
1105     // splitBlockBeforeInstr adds to WaterList, which is important when it is
1106     // called while handling branches so that the water will be seen on the
1107     // next iteration for constant pools, but in this context, we don't want
1108     // it.  Check for this so it will be removed from the WaterList.
1109     // Also remove any entry from NewWaterList.
1110     MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
1111     IP = llvm::find(WaterList, WaterBB);
1112     if (IP != WaterList.end())
1113       NewWaterList.erase(WaterBB);
1114 
1115     // We are adding new water.  Update NewWaterList.
1116     NewWaterList.insert(NewIsland);
1117   }
1118 
1119   // Remove the original WaterList entry; we want subsequent insertions in
1120   // this vicinity to go after the one we're about to insert.  This
1121   // considerably reduces the number of times we have to move the same CPE
1122   // more than once and is also important to ensure the algorithm terminates.
1123   if (IP != WaterList.end())
1124     WaterList.erase(IP);
1125 
1126   // Okay, we know we can put an island before NewMBB now, do it!
1127   MF->insert(NewMBB->getIterator(), NewIsland);
1128 
1129   // Update internal data structures to account for the newly inserted MBB.
1130   updateForInsertedWaterBlock(NewIsland);
1131 
1132   // Decrement the old entry, and remove it if refcount becomes 0.
1133   decrementCPEReferenceCount(CPI, CPEMI);
1134 
1135   // No existing clone of this CPE is within range.
1136   // We will be generating a new clone.  Get a UID for it.
1137   unsigned ID = createPICLabelUId();
1138 
1139   // Now that we have an island to add the CPE to, clone the original CPE and
1140   // add it to the island.
1141   U.HighWaterMark = NewIsland;
1142   U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(CSKY::CONSTPOOL_ENTRY))
1143                 .addImm(ID)
1144                 .addConstantPoolIndex(CPI)
1145                 .addImm(Size);
1146   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1147   ++NumCPEs;
1148 
1149   // Mark the basic block as aligned as required by the const-pool entry.
1150   NewIsland->setAlignment(getCPEAlign(*U.CPEMI));
1151 
1152   // Increase the size of the island block to account for the new entry.
1153   BBInfo[NewIsland->getNumber()].Size += Size;
1154   adjustBBOffsetsAfter(&*--NewIsland->getIterator());
1155 
1156   // Finally, change the CPI in the instruction operand to be ID.
1157   for (unsigned I = 0, E = UserMI->getNumOperands(); I != E; ++I)
1158     if (UserMI->getOperand(I).isCPI()) {
1159       UserMI->getOperand(I).setIndex(ID);
1160       break;
1161     }
1162 
1163   LLVM_DEBUG(
1164       dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1165              << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1166 
1167   return true;
1168 }
1169 
1170 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1171 /// sizes and offsets of impacted basic blocks.
1172 void CSKYConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1173   MachineBasicBlock *CPEBB = CPEMI->getParent();
1174   unsigned Size = CPEMI->getOperand(2).getImm();
1175   CPEMI->eraseFromParent();
1176   BBInfo[CPEBB->getNumber()].Size -= Size;
1177   // All succeeding offsets have the current size value added in, fix this.
1178   if (CPEBB->empty()) {
1179     BBInfo[CPEBB->getNumber()].Size = 0;
1180 
1181     // This block no longer needs to be aligned.
1182     CPEBB->setAlignment(Align(4));
1183   } else {
1184     // Entries are sorted by descending alignment, so realign from the front.
1185     CPEBB->setAlignment(getCPEAlign(*CPEBB->begin()));
1186   }
1187 
1188   adjustBBOffsetsAfter(CPEBB);
1189   // An island has only one predecessor BB and one successor BB. Check if
1190   // this BB's predecessor jumps directly to this BB's successor. This
1191   // shouldn't happen currently.
1192   assert(!bbIsJumpedOver(CPEBB) && "How did this happen?");
1193   // FIXME: remove the empty blocks after all the work is done?
1194 }
1195 
1196 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1197 /// are zero.
1198 bool CSKYConstantIslands::removeUnusedCPEntries() {
1199   unsigned MadeChange = false;
1200   for (unsigned I = 0, E = CPEntries.size(); I != E; ++I) {
1201     std::vector<CPEntry> &CPEs = CPEntries[I];
1202     for (unsigned J = 0, Ee = CPEs.size(); J != Ee; ++J) {
1203       if (CPEs[J].RefCount == 0 && CPEs[J].CPEMI) {
1204         removeDeadCPEMI(CPEs[J].CPEMI);
1205         CPEs[J].CPEMI = nullptr;
1206         MadeChange = true;
1207       }
1208     }
1209   }
1210   return MadeChange;
1211 }
1212 
1213 /// isBBInRange - Returns true if the distance between specific MI and
1214 /// specific BB can fit in MI's displacement field.
1215 bool CSKYConstantIslands::isBBInRange(MachineInstr *MI,
1216                                       MachineBasicBlock *DestBB,
1217                                       unsigned MaxDisp) {
1218   unsigned BrOffset = getOffsetOf(MI);
1219   unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1220 
1221   LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)
1222                     << " from " << printMBBReference(*MI->getParent())
1223                     << " max delta=" << MaxDisp << " from " << getOffsetOf(MI)
1224                     << " to " << DestOffset << " offset "
1225                     << int(DestOffset - BrOffset) << "\t" << *MI);
1226 
1227   if (BrOffset <= DestOffset) {
1228     // Branch before the Dest.
1229     if (DestOffset - BrOffset <= MaxDisp)
1230       return true;
1231   } else {
1232     if (BrOffset - DestOffset <= MaxDisp)
1233       return true;
1234   }
1235   return false;
1236 }
1237 
1238 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1239 /// away to fit in its displacement field.
1240 bool CSKYConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1241   MachineInstr *MI = Br.MI;
1242   MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);
1243 
1244   // Check to see if the DestBB is already in-range.
1245   if (isBBInRange(MI, DestBB, Br.MaxDisp))
1246     return false;
1247 
1248   if (!Br.IsCond)
1249     return fixupUnconditionalBr(Br);
1250   return fixupConditionalBr(Br);
1251 }
1252 
1253 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1254 /// too far away to fit in its displacement field. If the LR register has been
1255 /// spilled in the epilogue, then we can use BSR to implement a far jump.
1256 /// Otherwise, add an intermediate branch instruction to a branch.
1257 bool CSKYConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1258   MachineInstr *MI = Br.MI;
1259   MachineBasicBlock *MBB = MI->getParent();
1260 
1261   if (!MFI->isLRSpilled())
1262     report_fatal_error("underestimated function size");
1263 
1264   // Use BSR to implement far jump.
1265   Br.MaxDisp = ((1 << (26 - 1)) - 1) * 2;
1266   MI->setDesc(TII->get(CSKY::BSR32_BR));
1267   BBInfo[MBB->getNumber()].Size += 4;
1268   adjustBBOffsetsAfter(MBB);
1269   ++NumUBrFixed;
1270 
1271   LLVM_DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1272 
1273   return true;
1274 }
1275 
1276 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1277 /// far away to fit in its displacement field. It is converted to an inverse
1278 /// conditional branch + an unconditional branch to the destination.
1279 bool CSKYConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1280   MachineInstr *MI = Br.MI;
1281   MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);
1282 
1283   SmallVector<MachineOperand, 4> Cond;
1284   Cond.push_back(MachineOperand::CreateImm(MI->getOpcode()));
1285   Cond.push_back(MI->getOperand(0));
1286   TII->reverseBranchCondition(Cond);
1287 
1288   // Add an unconditional branch to the destination and invert the branch
1289   // condition to jump over it:
1290   // bteqz L1
1291   // =>
1292   // bnez L2
1293   // b   L1
1294   // L2:
1295 
1296   // If the branch is at the end of its MBB and that has a fall-through block,
1297   // direct the updated conditional branch to the fall-through block. Otherwise,
1298   // split the MBB before the next instruction.
1299   MachineBasicBlock *MBB = MI->getParent();
1300   MachineInstr *BMI = &MBB->back();
1301   bool NeedSplit = (BMI != MI) || !bbHasFallthrough(MBB);
1302 
1303   ++NumCBrFixed;
1304   if (BMI != MI) {
1305     if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1306         BMI->isUnconditionalBranch()) {
1307       // Last MI in the BB is an unconditional branch. Can we simply invert the
1308       // condition and swap destinations:
1309       // beqz L1
1310       // b   L2
1311       // =>
1312       // bnez L2
1313       // b   L1
1314       MachineBasicBlock *NewDest = TII->getBranchDestBlock(*BMI);
1315       if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1316         LLVM_DEBUG(
1317             dbgs() << "  Invert Bcc condition and swap its destination with "
1318                    << *BMI);
1319         BMI->getOperand(BMI->getNumExplicitOperands() - 1).setMBB(DestBB);
1320         MI->getOperand(MI->getNumExplicitOperands() - 1).setMBB(NewDest);
1321 
1322         MI->setDesc(TII->get(Cond[0].getImm()));
1323         return true;
1324       }
1325     }
1326   }
1327 
1328   if (NeedSplit) {
1329     splitBlockBeforeInstr(*MI);
1330     // No need for the branch to the next block. We're adding an unconditional
1331     // branch to the destination.
1332     int Delta = TII->getInstSizeInBytes(MBB->back());
1333     BBInfo[MBB->getNumber()].Size -= Delta;
1334     MBB->back().eraseFromParent();
1335     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1336 
1337     // The conditional successor will be swapped between the BBs after this, so
1338     // update CFG.
1339     MBB->addSuccessor(DestBB);
1340     std::next(MBB->getIterator())->removeSuccessor(DestBB);
1341   }
1342   MachineBasicBlock *NextBB = &*++MBB->getIterator();
1343 
1344   LLVM_DEBUG(dbgs() << "  Insert B to " << printMBBReference(*DestBB)
1345                     << " also invert condition and change dest. to "
1346                     << printMBBReference(*NextBB) << "\n");
1347 
1348   // Insert a new conditional branch and a new unconditional branch.
1349   // Also update the ImmBranch as well as adding a new entry for the new branch.
1350 
1351   BuildMI(MBB, DebugLoc(), TII->get(Cond[0].getImm()))
1352       .addReg(MI->getOperand(0).getReg())
1353       .addMBB(NextBB);
1354 
1355   Br.MI = &MBB->back();
1356   BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1357   BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1358   BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1359   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1360   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1361 
1362   // Remove the old conditional branch.  It may or may not still be in MBB.
1363   BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
1364   MI->eraseFromParent();
1365   adjustBBOffsetsAfter(MBB);
1366   return true;
1367 }
1368 
1369 /// Returns a pass that converts branches to long branches.
1370 FunctionPass *llvm::createCSKYConstantIslandPass() {
1371   return new CSKYConstantIslands();
1372 }
1373 
1374 INITIALIZE_PASS(CSKYConstantIslands, DEBUG_TYPE,
1375                 "CSKY constant island placement and branch shortening pass",
1376                 false, false)
1377