1065e0324SZi Xuan Wu //===- CSKYConstantIslandPass.cpp - Emit PC Relative loads ----------------===//
2065e0324SZi Xuan Wu //
3065e0324SZi Xuan Wu // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4065e0324SZi Xuan Wu // See https://llvm.org/LICENSE.txt for license information.
5065e0324SZi Xuan Wu // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6065e0324SZi Xuan Wu //
7065e0324SZi Xuan Wu //===----------------------------------------------------------------------===//
8065e0324SZi Xuan Wu //
9065e0324SZi Xuan Wu //
10065e0324SZi Xuan Wu // Loading constants inline is expensive on CSKY and it's in general better
11065e0324SZi Xuan Wu // to place the constant nearby in code space and then it can be loaded with a
12065e0324SZi Xuan Wu // simple 16/32 bit load instruction like lrw.
13065e0324SZi Xuan Wu //
14065e0324SZi Xuan Wu // The constants can be not just numbers but addresses of functions and labels.
15065e0324SZi Xuan Wu // This can be particularly helpful in static relocation mode for embedded
16065e0324SZi Xuan Wu // non-linux targets.
17065e0324SZi Xuan Wu //
18065e0324SZi Xuan Wu //===----------------------------------------------------------------------===//
19065e0324SZi Xuan Wu 
20065e0324SZi Xuan Wu #include "CSKY.h"
21065e0324SZi Xuan Wu #include "CSKYConstantPoolValue.h"
22065e0324SZi Xuan Wu #include "CSKYMachineFunctionInfo.h"
23065e0324SZi Xuan Wu #include "CSKYSubtarget.h"
24065e0324SZi Xuan Wu #include "llvm/ADT/STLExtras.h"
25065e0324SZi Xuan Wu #include "llvm/ADT/SmallSet.h"
26065e0324SZi Xuan Wu #include "llvm/ADT/SmallVector.h"
27065e0324SZi Xuan Wu #include "llvm/ADT/Statistic.h"
28065e0324SZi Xuan Wu #include "llvm/ADT/StringRef.h"
29065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineBasicBlock.h"
30065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineConstantPool.h"
31065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineDominators.h"
32989f1c72Sserge-sans-paille #include "llvm/CodeGen/MachineFrameInfo.h"
33065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineFunction.h"
34065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineFunctionPass.h"
35065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineInstr.h"
36065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineInstrBuilder.h"
37065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineOperand.h"
38065e0324SZi Xuan Wu #include "llvm/CodeGen/MachineRegisterInfo.h"
39065e0324SZi Xuan Wu #include "llvm/Config/llvm-config.h"
40065e0324SZi Xuan Wu #include "llvm/IR/Constants.h"
41065e0324SZi Xuan Wu #include "llvm/IR/DataLayout.h"
42065e0324SZi Xuan Wu #include "llvm/IR/DebugLoc.h"
43065e0324SZi Xuan Wu #include "llvm/IR/Function.h"
44065e0324SZi Xuan Wu #include "llvm/IR/Type.h"
45065e0324SZi Xuan Wu #include "llvm/Support/CommandLine.h"
46065e0324SZi Xuan Wu #include "llvm/Support/Compiler.h"
47065e0324SZi Xuan Wu #include "llvm/Support/Debug.h"
48065e0324SZi Xuan Wu #include "llvm/Support/ErrorHandling.h"
49065e0324SZi Xuan Wu #include "llvm/Support/Format.h"
50065e0324SZi Xuan Wu #include "llvm/Support/MathExtras.h"
51065e0324SZi Xuan Wu #include "llvm/Support/raw_ostream.h"
52065e0324SZi Xuan Wu #include <algorithm>
53065e0324SZi Xuan Wu #include <cassert>
54065e0324SZi Xuan Wu #include <cstdint>
55065e0324SZi Xuan Wu #include <iterator>
56065e0324SZi Xuan Wu #include <vector>
57065e0324SZi Xuan Wu 
58065e0324SZi Xuan Wu using namespace llvm;
59065e0324SZi Xuan Wu 
60065e0324SZi Xuan Wu #define DEBUG_TYPE "CSKY-constant-islands"
61065e0324SZi Xuan Wu 
62065e0324SZi Xuan Wu STATISTIC(NumCPEs, "Number of constpool entries");
63065e0324SZi Xuan Wu STATISTIC(NumSplit, "Number of uncond branches inserted");
64065e0324SZi Xuan Wu STATISTIC(NumCBrFixed, "Number of cond branches fixed");
65065e0324SZi Xuan Wu STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
66065e0324SZi Xuan Wu 
67065e0324SZi Xuan Wu namespace {
68065e0324SZi Xuan Wu 
69065e0324SZi Xuan Wu using Iter = MachineBasicBlock::iterator;
70065e0324SZi Xuan Wu using ReverseIter = MachineBasicBlock::reverse_iterator;
71065e0324SZi Xuan Wu 
72065e0324SZi Xuan Wu /// CSKYConstantIslands - Due to limited PC-relative displacements, CSKY
73065e0324SZi Xuan Wu /// requires constant pool entries to be scattered among the instructions
74065e0324SZi Xuan Wu /// inside a function.  To do this, it completely ignores the normal LLVM
75065e0324SZi Xuan Wu /// constant pool; instead, it places constants wherever it feels like with
76065e0324SZi Xuan Wu /// special instructions.
77065e0324SZi Xuan Wu ///
78065e0324SZi Xuan Wu /// The terminology used in this pass includes:
79065e0324SZi Xuan Wu ///   Islands - Clumps of constants placed in the function.
80065e0324SZi Xuan Wu ///   Water   - Potential places where an island could be formed.
81065e0324SZi Xuan Wu ///   CPE     - A constant pool entry that has been placed somewhere, which
82065e0324SZi Xuan Wu ///             tracks a list of users.
83065e0324SZi Xuan Wu 
84065e0324SZi Xuan Wu class CSKYConstantIslands : public MachineFunctionPass {
85065e0324SZi Xuan Wu   /// BasicBlockInfo - Information about the offset and size of a single
86065e0324SZi Xuan Wu   /// basic block.
87065e0324SZi Xuan Wu   struct BasicBlockInfo {
88065e0324SZi Xuan Wu     /// Offset - Distance from the beginning of the function to the beginning
89065e0324SZi Xuan Wu     /// of this basic block.
90065e0324SZi Xuan Wu     ///
91065e0324SZi Xuan Wu     /// Offsets are computed assuming worst case padding before an aligned
92065e0324SZi Xuan Wu     /// block. This means that subtracting basic block offsets always gives a
93065e0324SZi Xuan Wu     /// conservative estimate of the real distance which may be smaller.
94065e0324SZi Xuan Wu     ///
95065e0324SZi Xuan Wu     /// Because worst case padding is used, the computed offset of an aligned
96065e0324SZi Xuan Wu     /// block may not actually be aligned.
97065e0324SZi Xuan Wu     unsigned Offset = 0;
98065e0324SZi Xuan Wu 
99065e0324SZi Xuan Wu     /// Size - Size of the basic block in bytes.  If the block contains
100065e0324SZi Xuan Wu     /// inline assembly, this is a worst case estimate.
101065e0324SZi Xuan Wu     ///
102065e0324SZi Xuan Wu     /// The size does not include any alignment padding whether from the
103065e0324SZi Xuan Wu     /// beginning of the block, or from an aligned jump table at the end.
104065e0324SZi Xuan Wu     unsigned Size = 0;
105065e0324SZi Xuan Wu 
106065e0324SZi Xuan Wu     BasicBlockInfo() = default;
107065e0324SZi Xuan Wu 
postOffset__anona1ac4df50111::CSKYConstantIslands::BasicBlockInfo108065e0324SZi Xuan Wu     unsigned postOffset() const { return Offset + Size; }
109065e0324SZi Xuan Wu   };
110065e0324SZi Xuan Wu 
111065e0324SZi Xuan Wu   std::vector<BasicBlockInfo> BBInfo;
112065e0324SZi Xuan Wu 
113065e0324SZi Xuan Wu   /// WaterList - A sorted list of basic blocks where islands could be placed
114065e0324SZi Xuan Wu   /// (i.e. blocks that don't fall through to the following block, due
115065e0324SZi Xuan Wu   /// to a return, unreachable, or unconditional branch).
116065e0324SZi Xuan Wu   std::vector<MachineBasicBlock *> WaterList;
117065e0324SZi Xuan Wu 
118065e0324SZi Xuan Wu   /// NewWaterList - The subset of WaterList that was created since the
119065e0324SZi Xuan Wu   /// previous iteration by inserting unconditional branches.
120065e0324SZi Xuan Wu   SmallSet<MachineBasicBlock *, 4> NewWaterList;
121065e0324SZi Xuan Wu 
122065e0324SZi Xuan Wu   using water_iterator = std::vector<MachineBasicBlock *>::iterator;
123065e0324SZi Xuan Wu 
124065e0324SZi Xuan Wu   /// CPUser - One user of a constant pool, keeping the machine instruction
125065e0324SZi Xuan Wu   /// pointer, the constant pool being referenced, and the max displacement
126065e0324SZi Xuan Wu   /// allowed from the instruction to the CP.  The HighWaterMark records the
127065e0324SZi Xuan Wu   /// highest basic block where a new CPEntry can be placed.  To ensure this
128065e0324SZi Xuan Wu   /// pass terminates, the CP entries are initially placed at the end of the
129065e0324SZi Xuan Wu   /// function and then move monotonically to lower addresses.  The
130065e0324SZi Xuan Wu   /// exception to this rule is when the current CP entry for a particular
131065e0324SZi Xuan Wu   /// CPUser is out of range, but there is another CP entry for the same
132065e0324SZi Xuan Wu   /// constant value in range.  We want to use the existing in-range CP
133065e0324SZi Xuan Wu   /// entry, but if it later moves out of range, the search for new water
134065e0324SZi Xuan Wu   /// should resume where it left off.  The HighWaterMark is used to record
135065e0324SZi Xuan Wu   /// that point.
136065e0324SZi Xuan Wu   struct CPUser {
137065e0324SZi Xuan Wu     MachineInstr *MI;
138065e0324SZi Xuan Wu     MachineInstr *CPEMI;
139065e0324SZi Xuan Wu     MachineBasicBlock *HighWaterMark;
140065e0324SZi Xuan Wu 
141065e0324SZi Xuan Wu   private:
142065e0324SZi Xuan Wu     unsigned MaxDisp;
143065e0324SZi Xuan Wu 
144065e0324SZi Xuan Wu   public:
145065e0324SZi Xuan Wu     bool NegOk;
146065e0324SZi Xuan Wu 
CPUser__anona1ac4df50111::CSKYConstantIslands::CPUser147065e0324SZi Xuan Wu     CPUser(MachineInstr *Mi, MachineInstr *Cpemi, unsigned Maxdisp, bool Neg)
148065e0324SZi Xuan Wu         : MI(Mi), CPEMI(Cpemi), MaxDisp(Maxdisp), NegOk(Neg) {
149065e0324SZi Xuan Wu       HighWaterMark = CPEMI->getParent();
150065e0324SZi Xuan Wu     }
151065e0324SZi Xuan Wu 
152065e0324SZi Xuan Wu     /// getMaxDisp - Returns the maximum displacement supported by MI.
getMaxDisp__anona1ac4df50111::CSKYConstantIslands::CPUser153065e0324SZi Xuan Wu     unsigned getMaxDisp() const { return MaxDisp - 16; }
154065e0324SZi Xuan Wu 
setMaxDisp__anona1ac4df50111::CSKYConstantIslands::CPUser155065e0324SZi Xuan Wu     void setMaxDisp(unsigned Val) { MaxDisp = Val; }
156065e0324SZi Xuan Wu   };
157065e0324SZi Xuan Wu 
158065e0324SZi Xuan Wu   /// CPUsers - Keep track of all of the machine instructions that use various
159065e0324SZi Xuan Wu   /// constant pools and their max displacement.
160065e0324SZi Xuan Wu   std::vector<CPUser> CPUsers;
161065e0324SZi Xuan Wu 
162065e0324SZi Xuan Wu   /// CPEntry - One per constant pool entry, keeping the machine instruction
163065e0324SZi Xuan Wu   /// pointer, the constpool index, and the number of CPUser's which
164065e0324SZi Xuan Wu   /// reference this entry.
165065e0324SZi Xuan Wu   struct CPEntry {
166065e0324SZi Xuan Wu     MachineInstr *CPEMI;
167065e0324SZi Xuan Wu     unsigned CPI;
168065e0324SZi Xuan Wu     unsigned RefCount;
169065e0324SZi Xuan Wu 
CPEntry__anona1ac4df50111::CSKYConstantIslands::CPEntry170065e0324SZi Xuan Wu     CPEntry(MachineInstr *Cpemi, unsigned Cpi, unsigned Rc = 0)
171065e0324SZi Xuan Wu         : CPEMI(Cpemi), CPI(Cpi), RefCount(Rc) {}
172065e0324SZi Xuan Wu   };
173065e0324SZi Xuan Wu 
174065e0324SZi Xuan Wu   /// CPEntries - Keep track of all of the constant pool entry machine
175065e0324SZi Xuan Wu   /// instructions. For each original constpool index (i.e. those that
176065e0324SZi Xuan Wu   /// existed upon entry to this pass), it keeps a vector of entries.
177065e0324SZi Xuan Wu   /// Original elements are cloned as we go along; the clones are
178065e0324SZi Xuan Wu   /// put in the vector of the original element, but have distinct CPIs.
179065e0324SZi Xuan Wu   std::vector<std::vector<CPEntry>> CPEntries;
180065e0324SZi Xuan Wu 
181065e0324SZi Xuan Wu   /// ImmBranch - One per immediate branch, keeping the machine instruction
182065e0324SZi Xuan Wu   /// pointer, conditional or unconditional, the max displacement,
183065e0324SZi Xuan Wu   /// and (if isCond is true) the corresponding unconditional branch
184065e0324SZi Xuan Wu   /// opcode.
185065e0324SZi Xuan Wu   struct ImmBranch {
186065e0324SZi Xuan Wu     MachineInstr *MI;
187065e0324SZi Xuan Wu     unsigned MaxDisp : 31;
188065e0324SZi Xuan Wu     bool IsCond : 1;
189065e0324SZi Xuan Wu     int UncondBr;
190065e0324SZi Xuan Wu 
ImmBranch__anona1ac4df50111::CSKYConstantIslands::ImmBranch191065e0324SZi Xuan Wu     ImmBranch(MachineInstr *Mi, unsigned Maxdisp, bool Cond, int Ubr)
192065e0324SZi Xuan Wu         : MI(Mi), MaxDisp(Maxdisp), IsCond(Cond), UncondBr(Ubr) {}
193065e0324SZi Xuan Wu   };
194065e0324SZi Xuan Wu 
195065e0324SZi Xuan Wu   /// ImmBranches - Keep track of all the immediate branch instructions.
196065e0324SZi Xuan Wu   ///
197065e0324SZi Xuan Wu   std::vector<ImmBranch> ImmBranches;
198065e0324SZi Xuan Wu 
199065e0324SZi Xuan Wu   const CSKYSubtarget *STI = nullptr;
200065e0324SZi Xuan Wu   const CSKYInstrInfo *TII;
201065e0324SZi Xuan Wu   CSKYMachineFunctionInfo *MFI;
202065e0324SZi Xuan Wu   MachineFunction *MF = nullptr;
203065e0324SZi Xuan Wu   MachineConstantPool *MCP = nullptr;
204065e0324SZi Xuan Wu 
205065e0324SZi Xuan Wu   unsigned PICLabelUId;
206065e0324SZi Xuan Wu 
initPICLabelUId(unsigned UId)207065e0324SZi Xuan Wu   void initPICLabelUId(unsigned UId) { PICLabelUId = UId; }
208065e0324SZi Xuan Wu 
createPICLabelUId()209065e0324SZi Xuan Wu   unsigned createPICLabelUId() { return PICLabelUId++; }
210065e0324SZi Xuan Wu 
211065e0324SZi Xuan Wu public:
212065e0324SZi Xuan Wu   static char ID;
213065e0324SZi Xuan Wu 
CSKYConstantIslands()214065e0324SZi Xuan Wu   CSKYConstantIslands() : MachineFunctionPass(ID) {}
215065e0324SZi Xuan Wu 
getPassName() const216065e0324SZi Xuan Wu   StringRef getPassName() const override { return "CSKY Constant Islands"; }
217065e0324SZi Xuan Wu 
218065e0324SZi Xuan Wu   bool runOnMachineFunction(MachineFunction &F) override;
219065e0324SZi Xuan Wu 
getAnalysisUsage(AnalysisUsage & AU) const220065e0324SZi Xuan Wu   void getAnalysisUsage(AnalysisUsage &AU) const override {
221065e0324SZi Xuan Wu     AU.addRequired<MachineDominatorTree>();
222065e0324SZi Xuan Wu     MachineFunctionPass::getAnalysisUsage(AU);
223065e0324SZi Xuan Wu   }
224065e0324SZi Xuan Wu 
getRequiredProperties() const225065e0324SZi Xuan Wu   MachineFunctionProperties getRequiredProperties() const override {
226065e0324SZi Xuan Wu     return MachineFunctionProperties().set(
227065e0324SZi Xuan Wu         MachineFunctionProperties::Property::NoVRegs);
228065e0324SZi Xuan Wu   }
229065e0324SZi Xuan Wu 
230065e0324SZi Xuan Wu   void doInitialPlacement(std::vector<MachineInstr *> &CPEMIs);
231065e0324SZi Xuan Wu   CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
232065e0324SZi Xuan Wu   Align getCPEAlign(const MachineInstr &CPEMI);
233065e0324SZi Xuan Wu   void initializeFunctionInfo(const std::vector<MachineInstr *> &CPEMIs);
234065e0324SZi Xuan Wu   unsigned getOffsetOf(MachineInstr *MI) const;
235065e0324SZi Xuan Wu   unsigned getUserOffset(CPUser &) const;
236065e0324SZi Xuan Wu   void dumpBBs();
237065e0324SZi Xuan Wu 
238065e0324SZi Xuan Wu   bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, unsigned Disp,
239065e0324SZi Xuan Wu                        bool NegativeOK);
240065e0324SZi Xuan Wu   bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
241065e0324SZi Xuan Wu                        const CPUser &U);
242065e0324SZi Xuan Wu 
243065e0324SZi Xuan Wu   void computeBlockSize(MachineBasicBlock *MBB);
244065e0324SZi Xuan Wu   MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);
245065e0324SZi Xuan Wu   void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
246065e0324SZi Xuan Wu   void adjustBBOffsetsAfter(MachineBasicBlock *BB);
247065e0324SZi Xuan Wu   bool decrementCPEReferenceCount(unsigned CPI, MachineInstr *CPEMI);
248065e0324SZi Xuan Wu   int findInRangeCPEntry(CPUser &U, unsigned UserOffset);
249065e0324SZi Xuan Wu   bool findAvailableWater(CPUser &U, unsigned UserOffset,
250065e0324SZi Xuan Wu                           water_iterator &WaterIter);
251065e0324SZi Xuan Wu   void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
252065e0324SZi Xuan Wu                       MachineBasicBlock *&NewMBB);
253065e0324SZi Xuan Wu   bool handleConstantPoolUser(unsigned CPUserIndex);
254065e0324SZi Xuan Wu   void removeDeadCPEMI(MachineInstr *CPEMI);
255065e0324SZi Xuan Wu   bool removeUnusedCPEntries();
256065e0324SZi Xuan Wu   bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
257065e0324SZi Xuan Wu                         MachineInstr *CPEMI, unsigned Disp, bool NegOk,
258065e0324SZi Xuan Wu                         bool DoDump = false);
259065e0324SZi Xuan Wu   bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water, CPUser &U,
260065e0324SZi Xuan Wu                       unsigned &Growth);
261065e0324SZi Xuan Wu   bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
262065e0324SZi Xuan Wu   bool fixupImmediateBr(ImmBranch &Br);
263065e0324SZi Xuan Wu   bool fixupConditionalBr(ImmBranch &Br);
264065e0324SZi Xuan Wu   bool fixupUnconditionalBr(ImmBranch &Br);
265065e0324SZi Xuan Wu };
266065e0324SZi Xuan Wu } // end anonymous namespace
267065e0324SZi Xuan Wu 
268065e0324SZi Xuan Wu char CSKYConstantIslands::ID = 0;
269065e0324SZi Xuan Wu 
isOffsetInRange(unsigned UserOffset,unsigned TrialOffset,const CPUser & U)270065e0324SZi Xuan Wu bool CSKYConstantIslands::isOffsetInRange(unsigned UserOffset,
271065e0324SZi Xuan Wu                                           unsigned TrialOffset,
272065e0324SZi Xuan Wu                                           const CPUser &U) {
273065e0324SZi Xuan Wu   return isOffsetInRange(UserOffset, TrialOffset, U.getMaxDisp(), U.NegOk);
274065e0324SZi Xuan Wu }
275065e0324SZi Xuan Wu 
276065e0324SZi Xuan Wu #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
277065e0324SZi Xuan Wu /// print block size and offset information - debugging
dumpBBs()278065e0324SZi Xuan Wu LLVM_DUMP_METHOD void CSKYConstantIslands::dumpBBs() {
279065e0324SZi Xuan Wu   for (unsigned J = 0, E = BBInfo.size(); J != E; ++J) {
280065e0324SZi Xuan Wu     const BasicBlockInfo &BBI = BBInfo[J];
281065e0324SZi Xuan Wu     dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
282065e0324SZi Xuan Wu            << format(" size=%#x\n", BBInfo[J].Size);
283065e0324SZi Xuan Wu   }
284065e0324SZi Xuan Wu }
285065e0324SZi Xuan Wu #endif
286065e0324SZi Xuan Wu 
runOnMachineFunction(MachineFunction & Mf)287065e0324SZi Xuan Wu bool CSKYConstantIslands::runOnMachineFunction(MachineFunction &Mf) {
288065e0324SZi Xuan Wu   MF = &Mf;
289065e0324SZi Xuan Wu   MCP = Mf.getConstantPool();
290*ad73ce31SZongwei Lan   STI = &Mf.getSubtarget<CSKYSubtarget>();
291065e0324SZi Xuan Wu 
292065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << "***** CSKYConstantIslands: "
293065e0324SZi Xuan Wu                     << MCP->getConstants().size() << " CP entries, aligned to "
294065e0324SZi Xuan Wu                     << MCP->getConstantPoolAlign().value() << " bytes *****\n");
295065e0324SZi Xuan Wu 
296065e0324SZi Xuan Wu   TII = STI->getInstrInfo();
297065e0324SZi Xuan Wu   MFI = MF->getInfo<CSKYMachineFunctionInfo>();
298065e0324SZi Xuan Wu 
299065e0324SZi Xuan Wu   // This pass invalidates liveness information when it splits basic blocks.
300065e0324SZi Xuan Wu   MF->getRegInfo().invalidateLiveness();
301065e0324SZi Xuan Wu 
302065e0324SZi Xuan Wu   // Renumber all of the machine basic blocks in the function, guaranteeing that
303065e0324SZi Xuan Wu   // the numbers agree with the position of the block in the function.
304065e0324SZi Xuan Wu   MF->RenumberBlocks();
305065e0324SZi Xuan Wu 
306065e0324SZi Xuan Wu   bool MadeChange = false;
307065e0324SZi Xuan Wu 
308065e0324SZi Xuan Wu   // Perform the initial placement of the constant pool entries.  To start with,
309065e0324SZi Xuan Wu   // we put them all at the end of the function.
310065e0324SZi Xuan Wu   std::vector<MachineInstr *> CPEMIs;
311065e0324SZi Xuan Wu   if (!MCP->isEmpty())
312065e0324SZi Xuan Wu     doInitialPlacement(CPEMIs);
313065e0324SZi Xuan Wu 
314065e0324SZi Xuan Wu   /// The next UID to take is the first unused one.
315065e0324SZi Xuan Wu   initPICLabelUId(CPEMIs.size());
316065e0324SZi Xuan Wu 
317065e0324SZi Xuan Wu   // Do the initial scan of the function, building up information about the
318065e0324SZi Xuan Wu   // sizes of each block, the location of all the water, and finding all of the
319065e0324SZi Xuan Wu   // constant pool users.
320065e0324SZi Xuan Wu   initializeFunctionInfo(CPEMIs);
321065e0324SZi Xuan Wu   CPEMIs.clear();
322065e0324SZi Xuan Wu   LLVM_DEBUG(dumpBBs());
323065e0324SZi Xuan Wu 
324065e0324SZi Xuan Wu   /// Remove dead constant pool entries.
325065e0324SZi Xuan Wu   MadeChange |= removeUnusedCPEntries();
326065e0324SZi Xuan Wu 
327065e0324SZi Xuan Wu   // Iteratively place constant pool entries and fix up branches until there
328065e0324SZi Xuan Wu   // is no change.
329065e0324SZi Xuan Wu   unsigned NoCPIters = 0, NoBRIters = 0;
330065e0324SZi Xuan Wu   (void)NoBRIters;
331065e0324SZi Xuan Wu   while (true) {
332065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
333065e0324SZi Xuan Wu     bool CPChange = false;
334065e0324SZi Xuan Wu     for (unsigned I = 0, E = CPUsers.size(); I != E; ++I)
335065e0324SZi Xuan Wu       CPChange |= handleConstantPoolUser(I);
336065e0324SZi Xuan Wu     if (CPChange && ++NoCPIters > 30)
337065e0324SZi Xuan Wu       report_fatal_error("Constant Island pass failed to converge!");
338065e0324SZi Xuan Wu     LLVM_DEBUG(dumpBBs());
339065e0324SZi Xuan Wu 
340065e0324SZi Xuan Wu     // Clear NewWaterList now.  If we split a block for branches, it should
341065e0324SZi Xuan Wu     // appear as "new water" for the next iteration of constant pool placement.
342065e0324SZi Xuan Wu     NewWaterList.clear();
343065e0324SZi Xuan Wu 
344065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
345065e0324SZi Xuan Wu     bool BRChange = false;
346065e0324SZi Xuan Wu     for (unsigned I = 0, E = ImmBranches.size(); I != E; ++I)
347065e0324SZi Xuan Wu       BRChange |= fixupImmediateBr(ImmBranches[I]);
348065e0324SZi Xuan Wu     if (BRChange && ++NoBRIters > 30)
349065e0324SZi Xuan Wu       report_fatal_error("Branch Fix Up pass failed to converge!");
350065e0324SZi Xuan Wu     LLVM_DEBUG(dumpBBs());
351065e0324SZi Xuan Wu     if (!CPChange && !BRChange)
352065e0324SZi Xuan Wu       break;
353065e0324SZi Xuan Wu     MadeChange = true;
354065e0324SZi Xuan Wu   }
355065e0324SZi Xuan Wu 
356065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
357065e0324SZi Xuan Wu 
358065e0324SZi Xuan Wu   BBInfo.clear();
359065e0324SZi Xuan Wu   WaterList.clear();
360065e0324SZi Xuan Wu   CPUsers.clear();
361065e0324SZi Xuan Wu   CPEntries.clear();
362065e0324SZi Xuan Wu   ImmBranches.clear();
363065e0324SZi Xuan Wu   return MadeChange;
364065e0324SZi Xuan Wu }
365065e0324SZi Xuan Wu 
366065e0324SZi Xuan Wu /// doInitialPlacement - Perform the initial placement of the constant pool
367065e0324SZi Xuan Wu /// entries.  To start with, we put them all at the end of the function.
doInitialPlacement(std::vector<MachineInstr * > & CPEMIs)368065e0324SZi Xuan Wu void CSKYConstantIslands::doInitialPlacement(
369065e0324SZi Xuan Wu     std::vector<MachineInstr *> &CPEMIs) {
370065e0324SZi Xuan Wu   // Create the basic block to hold the CPE's.
371065e0324SZi Xuan Wu   MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
372065e0324SZi Xuan Wu   MF->push_back(BB);
373065e0324SZi Xuan Wu 
374065e0324SZi Xuan Wu   // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
375065e0324SZi Xuan Wu   const Align MaxAlign = MCP->getConstantPoolAlign();
376065e0324SZi Xuan Wu 
377065e0324SZi Xuan Wu   // Mark the basic block as required by the const-pool.
378065e0324SZi Xuan Wu   BB->setAlignment(Align(2));
379065e0324SZi Xuan Wu 
380065e0324SZi Xuan Wu   // The function needs to be as aligned as the basic blocks. The linker may
381065e0324SZi Xuan Wu   // move functions around based on their alignment.
382065e0324SZi Xuan Wu   MF->ensureAlignment(BB->getAlignment());
383065e0324SZi Xuan Wu 
384065e0324SZi Xuan Wu   // Order the entries in BB by descending alignment.  That ensures correct
385065e0324SZi Xuan Wu   // alignment of all entries as long as BB is sufficiently aligned.  Keep
386065e0324SZi Xuan Wu   // track of the insertion point for each alignment.  We are going to bucket
387065e0324SZi Xuan Wu   // sort the entries as they are created.
388065e0324SZi Xuan Wu   SmallVector<MachineBasicBlock::iterator, 8> InsPoint(Log2(MaxAlign) + 1,
389065e0324SZi Xuan Wu                                                        BB->end());
390065e0324SZi Xuan Wu 
391065e0324SZi Xuan Wu   // Add all of the constants from the constant pool to the end block, use an
392065e0324SZi Xuan Wu   // identity mapping of CPI's to CPE's.
393065e0324SZi Xuan Wu   const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
394065e0324SZi Xuan Wu 
395065e0324SZi Xuan Wu   const DataLayout &TD = MF->getDataLayout();
396065e0324SZi Xuan Wu   for (unsigned I = 0, E = CPs.size(); I != E; ++I) {
397065e0324SZi Xuan Wu     unsigned Size = CPs[I].getSizeInBytes(TD);
398065e0324SZi Xuan Wu     assert(Size >= 4 && "Too small constant pool entry");
399065e0324SZi Xuan Wu     Align Alignment = CPs[I].getAlign();
400065e0324SZi Xuan Wu     // Verify that all constant pool entries are a multiple of their alignment.
401065e0324SZi Xuan Wu     // If not, we would have to pad them out so that instructions stay aligned.
402065e0324SZi Xuan Wu     assert(isAligned(Alignment, Size) && "CP Entry not multiple of 4 bytes!");
403065e0324SZi Xuan Wu 
404065e0324SZi Xuan Wu     // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
405065e0324SZi Xuan Wu     unsigned LogAlign = Log2(Alignment);
406065e0324SZi Xuan Wu     MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
407065e0324SZi Xuan Wu 
408065e0324SZi Xuan Wu     MachineInstr *CPEMI =
409065e0324SZi Xuan Wu         BuildMI(*BB, InsAt, DebugLoc(), TII->get(CSKY::CONSTPOOL_ENTRY))
410065e0324SZi Xuan Wu             .addImm(I)
411065e0324SZi Xuan Wu             .addConstantPoolIndex(I)
412065e0324SZi Xuan Wu             .addImm(Size);
413065e0324SZi Xuan Wu 
414065e0324SZi Xuan Wu     CPEMIs.push_back(CPEMI);
415065e0324SZi Xuan Wu 
416065e0324SZi Xuan Wu     // Ensure that future entries with higher alignment get inserted before
417065e0324SZi Xuan Wu     // CPEMI. This is bucket sort with iterators.
418065e0324SZi Xuan Wu     for (unsigned A = LogAlign + 1; A <= Log2(MaxAlign); ++A)
419065e0324SZi Xuan Wu       if (InsPoint[A] == InsAt)
420065e0324SZi Xuan Wu         InsPoint[A] = CPEMI;
421065e0324SZi Xuan Wu     // Add a new CPEntry, but no corresponding CPUser yet.
422065e0324SZi Xuan Wu     CPEntries.emplace_back(1, CPEntry(CPEMI, I));
423065e0324SZi Xuan Wu     ++NumCPEs;
424065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "Moved CPI#" << I << " to end of function, size = "
425065e0324SZi Xuan Wu                       << Size << ", align = " << Alignment.value() << '\n');
426065e0324SZi Xuan Wu   }
427065e0324SZi Xuan Wu   LLVM_DEBUG(BB->dump());
428065e0324SZi Xuan Wu }
429065e0324SZi Xuan Wu 
430065e0324SZi Xuan Wu /// BBHasFallthrough - Return true if the specified basic block can fallthrough
431065e0324SZi Xuan Wu /// into the block immediately after it.
bbHasFallthrough(MachineBasicBlock * MBB)432065e0324SZi Xuan Wu static bool bbHasFallthrough(MachineBasicBlock *MBB) {
433065e0324SZi Xuan Wu   // Get the next machine basic block in the function.
434065e0324SZi Xuan Wu   MachineFunction::iterator MBBI = MBB->getIterator();
435065e0324SZi Xuan Wu   // Can't fall off end of function.
436065e0324SZi Xuan Wu   if (std::next(MBBI) == MBB->getParent()->end())
437065e0324SZi Xuan Wu     return false;
438065e0324SZi Xuan Wu 
439065e0324SZi Xuan Wu   MachineBasicBlock *NextBB = &*std::next(MBBI);
440065e0324SZi Xuan Wu   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
441065e0324SZi Xuan Wu                                         E = MBB->succ_end();
442065e0324SZi Xuan Wu        I != E; ++I)
443065e0324SZi Xuan Wu     if (*I == NextBB)
444065e0324SZi Xuan Wu       return true;
445065e0324SZi Xuan Wu 
446065e0324SZi Xuan Wu   return false;
447065e0324SZi Xuan Wu }
448065e0324SZi Xuan Wu 
449065e0324SZi Xuan Wu /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
450065e0324SZi Xuan Wu /// look up the corresponding CPEntry.
451065e0324SZi Xuan Wu CSKYConstantIslands::CPEntry *
findConstPoolEntry(unsigned CPI,const MachineInstr * CPEMI)452065e0324SZi Xuan Wu CSKYConstantIslands::findConstPoolEntry(unsigned CPI,
453065e0324SZi Xuan Wu                                         const MachineInstr *CPEMI) {
454065e0324SZi Xuan Wu   std::vector<CPEntry> &CPEs = CPEntries[CPI];
455065e0324SZi Xuan Wu   // Number of entries per constpool index should be small, just do a
456065e0324SZi Xuan Wu   // linear search.
457065e0324SZi Xuan Wu   for (unsigned I = 0, E = CPEs.size(); I != E; ++I) {
458065e0324SZi Xuan Wu     if (CPEs[I].CPEMI == CPEMI)
459065e0324SZi Xuan Wu       return &CPEs[I];
460065e0324SZi Xuan Wu   }
461065e0324SZi Xuan Wu   return nullptr;
462065e0324SZi Xuan Wu }
463065e0324SZi Xuan Wu 
464065e0324SZi Xuan Wu /// getCPEAlign - Returns the required alignment of the constant pool entry
465065e0324SZi Xuan Wu /// represented by CPEMI.  Alignment is measured in log2(bytes) units.
getCPEAlign(const MachineInstr & CPEMI)466065e0324SZi Xuan Wu Align CSKYConstantIslands::getCPEAlign(const MachineInstr &CPEMI) {
467065e0324SZi Xuan Wu   assert(CPEMI.getOpcode() == CSKY::CONSTPOOL_ENTRY);
468065e0324SZi Xuan Wu 
469065e0324SZi Xuan Wu   unsigned CPI = CPEMI.getOperand(1).getIndex();
470065e0324SZi Xuan Wu   assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
471065e0324SZi Xuan Wu   return MCP->getConstants()[CPI].getAlign();
472065e0324SZi Xuan Wu }
473065e0324SZi Xuan Wu 
474065e0324SZi Xuan Wu /// initializeFunctionInfo - Do the initial scan of the function, building up
475065e0324SZi Xuan Wu /// information about the sizes of each block, the location of all the water,
476065e0324SZi Xuan Wu /// and finding all of the constant pool users.
initializeFunctionInfo(const std::vector<MachineInstr * > & CPEMIs)477065e0324SZi Xuan Wu void CSKYConstantIslands::initializeFunctionInfo(
478065e0324SZi Xuan Wu     const std::vector<MachineInstr *> &CPEMIs) {
479065e0324SZi Xuan Wu   BBInfo.clear();
480065e0324SZi Xuan Wu   BBInfo.resize(MF->getNumBlockIDs());
481065e0324SZi Xuan Wu 
482065e0324SZi Xuan Wu   // First thing, compute the size of all basic blocks, and see if the function
483065e0324SZi Xuan Wu   // has any inline assembly in it. If so, we have to be conservative about
484065e0324SZi Xuan Wu   // alignment assumptions, as we don't know for sure the size of any
485065e0324SZi Xuan Wu   // instructions in the inline assembly.
486065e0324SZi Xuan Wu   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
487065e0324SZi Xuan Wu     computeBlockSize(&*I);
488065e0324SZi Xuan Wu 
489065e0324SZi Xuan Wu   // Compute block offsets.
490065e0324SZi Xuan Wu   adjustBBOffsetsAfter(&MF->front());
491065e0324SZi Xuan Wu 
492065e0324SZi Xuan Wu   // Now go back through the instructions and build up our data structures.
493065e0324SZi Xuan Wu   for (MachineBasicBlock &MBB : *MF) {
494065e0324SZi Xuan Wu     // If this block doesn't fall through into the next MBB, then this is
495065e0324SZi Xuan Wu     // 'water' that a constant pool island could be placed.
496065e0324SZi Xuan Wu     if (!bbHasFallthrough(&MBB))
497065e0324SZi Xuan Wu       WaterList.push_back(&MBB);
498065e0324SZi Xuan Wu     for (MachineInstr &MI : MBB) {
499065e0324SZi Xuan Wu       if (MI.isDebugInstr())
500065e0324SZi Xuan Wu         continue;
501065e0324SZi Xuan Wu 
502065e0324SZi Xuan Wu       int Opc = MI.getOpcode();
503065e0324SZi Xuan Wu       if (MI.isBranch() && !MI.isIndirectBranch()) {
504065e0324SZi Xuan Wu         bool IsCond = MI.isConditionalBranch();
505065e0324SZi Xuan Wu         unsigned Bits = 0;
506065e0324SZi Xuan Wu         unsigned Scale = 1;
507065e0324SZi Xuan Wu         int UOpc = CSKY::BR32;
508065e0324SZi Xuan Wu 
509065e0324SZi Xuan Wu         switch (MI.getOpcode()) {
510065e0324SZi Xuan Wu         case CSKY::BR16:
511065e0324SZi Xuan Wu         case CSKY::BF16:
512065e0324SZi Xuan Wu         case CSKY::BT16:
513065e0324SZi Xuan Wu           Bits = 10;
514065e0324SZi Xuan Wu           Scale = 2;
515065e0324SZi Xuan Wu           break;
516065e0324SZi Xuan Wu         default:
517065e0324SZi Xuan Wu           Bits = 16;
518065e0324SZi Xuan Wu           Scale = 2;
519065e0324SZi Xuan Wu           break;
520065e0324SZi Xuan Wu         }
521065e0324SZi Xuan Wu 
522065e0324SZi Xuan Wu         // Record this immediate branch.
523065e0324SZi Xuan Wu         unsigned MaxOffs = ((1 << (Bits - 1)) - 1) * Scale;
524065e0324SZi Xuan Wu         ImmBranches.push_back(ImmBranch(&MI, MaxOffs, IsCond, UOpc));
525065e0324SZi Xuan Wu       }
526065e0324SZi Xuan Wu 
527065e0324SZi Xuan Wu       if (Opc == CSKY::CONSTPOOL_ENTRY)
528065e0324SZi Xuan Wu         continue;
529065e0324SZi Xuan Wu 
530065e0324SZi Xuan Wu       // Scan the instructions for constant pool operands.
531065e0324SZi Xuan Wu       for (unsigned Op = 0, E = MI.getNumOperands(); Op != E; ++Op)
532065e0324SZi Xuan Wu         if (MI.getOperand(Op).isCPI()) {
533065e0324SZi Xuan Wu           // We found one.  The addressing mode tells us the max displacement
534065e0324SZi Xuan Wu           // from the PC that this instruction permits.
535065e0324SZi Xuan Wu 
536065e0324SZi Xuan Wu           // Basic size info comes from the TSFlags field.
537065e0324SZi Xuan Wu           unsigned Bits = 0;
538065e0324SZi Xuan Wu           unsigned Scale = 1;
539065e0324SZi Xuan Wu           bool NegOk = false;
540065e0324SZi Xuan Wu 
541065e0324SZi Xuan Wu           switch (Opc) {
542065e0324SZi Xuan Wu           default:
543065e0324SZi Xuan Wu             llvm_unreachable("Unknown addressing mode for CP reference!");
544065e0324SZi Xuan Wu           case CSKY::MOVIH32:
545065e0324SZi Xuan Wu           case CSKY::ORI32:
546065e0324SZi Xuan Wu             continue;
547065e0324SZi Xuan Wu           case CSKY::PseudoTLSLA32:
548065e0324SZi Xuan Wu           case CSKY::JSRI32:
549065e0324SZi Xuan Wu           case CSKY::JMPI32:
550065e0324SZi Xuan Wu           case CSKY::LRW32:
551065e0324SZi Xuan Wu           case CSKY::LRW32_Gen:
552065e0324SZi Xuan Wu             Bits = 16;
553065e0324SZi Xuan Wu             Scale = 4;
554065e0324SZi Xuan Wu             break;
5554ad517e6SZi Xuan Wu           case CSKY::f2FLRW_S:
5564ad517e6SZi Xuan Wu           case CSKY::f2FLRW_D:
5574ad517e6SZi Xuan Wu             Bits = 8;
5584ad517e6SZi Xuan Wu             Scale = 4;
5594ad517e6SZi Xuan Wu             break;
560065e0324SZi Xuan Wu           case CSKY::GRS32:
561065e0324SZi Xuan Wu             Bits = 17;
562065e0324SZi Xuan Wu             Scale = 2;
563065e0324SZi Xuan Wu             NegOk = true;
564065e0324SZi Xuan Wu             break;
565065e0324SZi Xuan Wu           }
566065e0324SZi Xuan Wu           // Remember that this is a user of a CP entry.
567065e0324SZi Xuan Wu           unsigned CPI = MI.getOperand(Op).getIndex();
568065e0324SZi Xuan Wu           MachineInstr *CPEMI = CPEMIs[CPI];
569065e0324SZi Xuan Wu           unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
570065e0324SZi Xuan Wu           CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk));
571065e0324SZi Xuan Wu 
572065e0324SZi Xuan Wu           // Increment corresponding CPEntry reference count.
573065e0324SZi Xuan Wu           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
574065e0324SZi Xuan Wu           assert(CPE && "Cannot find a corresponding CPEntry!");
575065e0324SZi Xuan Wu           CPE->RefCount++;
576065e0324SZi Xuan Wu 
577065e0324SZi Xuan Wu           // Instructions can only use one CP entry, don't bother scanning the
578065e0324SZi Xuan Wu           // rest of the operands.
579065e0324SZi Xuan Wu           break;
580065e0324SZi Xuan Wu         }
581065e0324SZi Xuan Wu     }
582065e0324SZi Xuan Wu   }
583065e0324SZi Xuan Wu }
584065e0324SZi Xuan Wu 
585065e0324SZi Xuan Wu /// computeBlockSize - Compute the size and some alignment information for MBB.
586065e0324SZi Xuan Wu /// This function updates BBInfo directly.
computeBlockSize(MachineBasicBlock * MBB)587065e0324SZi Xuan Wu void CSKYConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
588065e0324SZi Xuan Wu   BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
589065e0324SZi Xuan Wu   BBI.Size = 0;
590065e0324SZi Xuan Wu 
591065e0324SZi Xuan Wu   for (const MachineInstr &MI : *MBB)
592065e0324SZi Xuan Wu     BBI.Size += TII->getInstSizeInBytes(MI);
593065e0324SZi Xuan Wu }
594065e0324SZi Xuan Wu 
595065e0324SZi Xuan Wu /// getOffsetOf - Return the current offset of the specified machine instruction
596065e0324SZi Xuan Wu /// from the start of the function.  This offset changes as stuff is moved
597065e0324SZi Xuan Wu /// around inside the function.
getOffsetOf(MachineInstr * MI) const598065e0324SZi Xuan Wu unsigned CSKYConstantIslands::getOffsetOf(MachineInstr *MI) const {
599065e0324SZi Xuan Wu   MachineBasicBlock *MBB = MI->getParent();
600065e0324SZi Xuan Wu 
601065e0324SZi Xuan Wu   // The offset is composed of two things: the sum of the sizes of all MBB's
602065e0324SZi Xuan Wu   // before this instruction's block, and the offset from the start of the block
603065e0324SZi Xuan Wu   // it is in.
604065e0324SZi Xuan Wu   unsigned Offset = BBInfo[MBB->getNumber()].Offset;
605065e0324SZi Xuan Wu 
606065e0324SZi Xuan Wu   // Sum instructions before MI in MBB.
607065e0324SZi Xuan Wu   for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
608065e0324SZi Xuan Wu     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
609065e0324SZi Xuan Wu     Offset += TII->getInstSizeInBytes(*I);
610065e0324SZi Xuan Wu   }
611065e0324SZi Xuan Wu   return Offset;
612065e0324SZi Xuan Wu }
613065e0324SZi Xuan Wu 
614065e0324SZi Xuan Wu /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
615065e0324SZi Xuan Wu /// ID.
compareMbbNumbers(const MachineBasicBlock * LHS,const MachineBasicBlock * RHS)616065e0324SZi Xuan Wu static bool compareMbbNumbers(const MachineBasicBlock *LHS,
617065e0324SZi Xuan Wu                               const MachineBasicBlock *RHS) {
618065e0324SZi Xuan Wu   return LHS->getNumber() < RHS->getNumber();
619065e0324SZi Xuan Wu }
620065e0324SZi Xuan Wu 
621065e0324SZi Xuan Wu /// updateForInsertedWaterBlock - When a block is newly inserted into the
622065e0324SZi Xuan Wu /// machine function, it upsets all of the block numbers.  Renumber the blocks
623065e0324SZi Xuan Wu /// and update the arrays that parallel this numbering.
updateForInsertedWaterBlock(MachineBasicBlock * NewBB)624065e0324SZi Xuan Wu void CSKYConstantIslands::updateForInsertedWaterBlock(
625065e0324SZi Xuan Wu     MachineBasicBlock *NewBB) {
626065e0324SZi Xuan Wu   // Renumber the MBB's to keep them consecutive.
627065e0324SZi Xuan Wu   NewBB->getParent()->RenumberBlocks(NewBB);
628065e0324SZi Xuan Wu 
629065e0324SZi Xuan Wu   // Insert an entry into BBInfo to align it properly with the (newly
630065e0324SZi Xuan Wu   // renumbered) block numbers.
631065e0324SZi Xuan Wu   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
632065e0324SZi Xuan Wu 
633065e0324SZi Xuan Wu   // Next, update WaterList.  Specifically, we need to add NewMBB as having
634065e0324SZi Xuan Wu   // available water after it.
635065e0324SZi Xuan Wu   water_iterator IP = llvm::lower_bound(WaterList, NewBB, compareMbbNumbers);
636065e0324SZi Xuan Wu   WaterList.insert(IP, NewBB);
637065e0324SZi Xuan Wu }
638065e0324SZi Xuan Wu 
getUserOffset(CPUser & U) const639065e0324SZi Xuan Wu unsigned CSKYConstantIslands::getUserOffset(CPUser &U) const {
640065e0324SZi Xuan Wu   unsigned UserOffset = getOffsetOf(U.MI);
641065e0324SZi Xuan Wu 
642065e0324SZi Xuan Wu   UserOffset &= ~3u;
643065e0324SZi Xuan Wu 
644065e0324SZi Xuan Wu   return UserOffset;
645065e0324SZi Xuan Wu }
646065e0324SZi Xuan Wu 
647065e0324SZi Xuan Wu /// Split the basic block containing MI into two blocks, which are joined by
648065e0324SZi Xuan Wu /// an unconditional branch.  Update data structures and renumber blocks to
649065e0324SZi Xuan Wu /// account for this change and returns the newly created block.
650065e0324SZi Xuan Wu MachineBasicBlock *
splitBlockBeforeInstr(MachineInstr & MI)651065e0324SZi Xuan Wu CSKYConstantIslands::splitBlockBeforeInstr(MachineInstr &MI) {
652065e0324SZi Xuan Wu   MachineBasicBlock *OrigBB = MI.getParent();
653065e0324SZi Xuan Wu 
654065e0324SZi Xuan Wu   // Create a new MBB for the code after the OrigBB.
655065e0324SZi Xuan Wu   MachineBasicBlock *NewBB =
656065e0324SZi Xuan Wu       MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
657065e0324SZi Xuan Wu   MachineFunction::iterator MBBI = ++OrigBB->getIterator();
658065e0324SZi Xuan Wu   MF->insert(MBBI, NewBB);
659065e0324SZi Xuan Wu 
660065e0324SZi Xuan Wu   // Splice the instructions starting with MI over to NewBB.
661065e0324SZi Xuan Wu   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
662065e0324SZi Xuan Wu 
663065e0324SZi Xuan Wu   // Add an unconditional branch from OrigBB to NewBB.
664065e0324SZi Xuan Wu   // Note the new unconditional branch is not being recorded.
665065e0324SZi Xuan Wu   // There doesn't seem to be meaningful DebugInfo available; this doesn't
666065e0324SZi Xuan Wu   // correspond to anything in the source.
667065e0324SZi Xuan Wu 
668065e0324SZi Xuan Wu   // TODO: Add support for 16bit instr.
669065e0324SZi Xuan Wu   BuildMI(OrigBB, DebugLoc(), TII->get(CSKY::BR32)).addMBB(NewBB);
670065e0324SZi Xuan Wu   ++NumSplit;
671065e0324SZi Xuan Wu 
672065e0324SZi Xuan Wu   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
673065e0324SZi Xuan Wu   NewBB->transferSuccessors(OrigBB);
674065e0324SZi Xuan Wu 
675065e0324SZi Xuan Wu   // OrigBB branches to NewBB.
676065e0324SZi Xuan Wu   OrigBB->addSuccessor(NewBB);
677065e0324SZi Xuan Wu 
678065e0324SZi Xuan Wu   // Update internal data structures to account for the newly inserted MBB.
679065e0324SZi Xuan Wu   // This is almost the same as updateForInsertedWaterBlock, except that
680065e0324SZi Xuan Wu   // the Water goes after OrigBB, not NewBB.
681065e0324SZi Xuan Wu   MF->RenumberBlocks(NewBB);
682065e0324SZi Xuan Wu 
683065e0324SZi Xuan Wu   // Insert an entry into BBInfo to align it properly with the (newly
684065e0324SZi Xuan Wu   // renumbered) block numbers.
685065e0324SZi Xuan Wu   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
686065e0324SZi Xuan Wu 
687065e0324SZi Xuan Wu   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
688065e0324SZi Xuan Wu   // available water after it (but not if it's already there, which happens
689065e0324SZi Xuan Wu   // when splitting before a conditional branch that is followed by an
690065e0324SZi Xuan Wu   // unconditional branch - in that case we want to insert NewBB).
691065e0324SZi Xuan Wu   water_iterator IP = llvm::lower_bound(WaterList, OrigBB, compareMbbNumbers);
692065e0324SZi Xuan Wu   MachineBasicBlock *WaterBB = *IP;
693065e0324SZi Xuan Wu   if (WaterBB == OrigBB)
694065e0324SZi Xuan Wu     WaterList.insert(std::next(IP), NewBB);
695065e0324SZi Xuan Wu   else
696065e0324SZi Xuan Wu     WaterList.insert(IP, OrigBB);
697065e0324SZi Xuan Wu   NewWaterList.insert(OrigBB);
698065e0324SZi Xuan Wu 
699065e0324SZi Xuan Wu   // Figure out how large the OrigBB is.  As the first half of the original
700065e0324SZi Xuan Wu   // block, it cannot contain a tablejump.  The size includes
701065e0324SZi Xuan Wu   // the new jump we added.  (It should be possible to do this without
702065e0324SZi Xuan Wu   // recounting everything, but it's very confusing, and this is rarely
703065e0324SZi Xuan Wu   // executed.)
704065e0324SZi Xuan Wu   computeBlockSize(OrigBB);
705065e0324SZi Xuan Wu 
706065e0324SZi Xuan Wu   // Figure out how large the NewMBB is.  As the second half of the original
707065e0324SZi Xuan Wu   // block, it may contain a tablejump.
708065e0324SZi Xuan Wu   computeBlockSize(NewBB);
709065e0324SZi Xuan Wu 
710065e0324SZi Xuan Wu   // All BBOffsets following these blocks must be modified.
711065e0324SZi Xuan Wu   adjustBBOffsetsAfter(OrigBB);
712065e0324SZi Xuan Wu 
713065e0324SZi Xuan Wu   return NewBB;
714065e0324SZi Xuan Wu }
715065e0324SZi Xuan Wu 
716065e0324SZi Xuan Wu /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
717065e0324SZi Xuan Wu /// reference) is within MaxDisp of TrialOffset (a proposed location of a
718065e0324SZi Xuan Wu /// constant pool entry).
isOffsetInRange(unsigned UserOffset,unsigned TrialOffset,unsigned MaxDisp,bool NegativeOK)719065e0324SZi Xuan Wu bool CSKYConstantIslands::isOffsetInRange(unsigned UserOffset,
720065e0324SZi Xuan Wu                                           unsigned TrialOffset,
721065e0324SZi Xuan Wu                                           unsigned MaxDisp, bool NegativeOK) {
722065e0324SZi Xuan Wu   if (UserOffset <= TrialOffset) {
723065e0324SZi Xuan Wu     // User before the Trial.
724065e0324SZi Xuan Wu     if (TrialOffset - UserOffset <= MaxDisp)
725065e0324SZi Xuan Wu       return true;
726065e0324SZi Xuan Wu   } else if (NegativeOK) {
727065e0324SZi Xuan Wu     if (UserOffset - TrialOffset <= MaxDisp)
728065e0324SZi Xuan Wu       return true;
729065e0324SZi Xuan Wu   }
730065e0324SZi Xuan Wu   return false;
731065e0324SZi Xuan Wu }
732065e0324SZi Xuan Wu 
733065e0324SZi Xuan Wu /// isWaterInRange - Returns true if a CPE placed after the specified
734065e0324SZi Xuan Wu /// Water (a basic block) will be in range for the specific MI.
735065e0324SZi Xuan Wu ///
736065e0324SZi Xuan Wu /// Compute how much the function will grow by inserting a CPE after Water.
isWaterInRange(unsigned UserOffset,MachineBasicBlock * Water,CPUser & U,unsigned & Growth)737065e0324SZi Xuan Wu bool CSKYConstantIslands::isWaterInRange(unsigned UserOffset,
738065e0324SZi Xuan Wu                                          MachineBasicBlock *Water, CPUser &U,
739065e0324SZi Xuan Wu                                          unsigned &Growth) {
740065e0324SZi Xuan Wu   unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
741065e0324SZi Xuan Wu   unsigned NextBlockOffset;
742065e0324SZi Xuan Wu   Align NextBlockAlignment;
743065e0324SZi Xuan Wu   MachineFunction::const_iterator NextBlock = ++Water->getIterator();
744065e0324SZi Xuan Wu   if (NextBlock == MF->end()) {
745065e0324SZi Xuan Wu     NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
746065e0324SZi Xuan Wu     NextBlockAlignment = Align(4);
747065e0324SZi Xuan Wu   } else {
748065e0324SZi Xuan Wu     NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
749065e0324SZi Xuan Wu     NextBlockAlignment = NextBlock->getAlignment();
750065e0324SZi Xuan Wu   }
751065e0324SZi Xuan Wu   unsigned Size = U.CPEMI->getOperand(2).getImm();
752065e0324SZi Xuan Wu   unsigned CPEEnd = CPEOffset + Size;
753065e0324SZi Xuan Wu 
754065e0324SZi Xuan Wu   // The CPE may be able to hide in the alignment padding before the next
755065e0324SZi Xuan Wu   // block. It may also cause more padding to be required if it is more aligned
756065e0324SZi Xuan Wu   // that the next block.
757065e0324SZi Xuan Wu   if (CPEEnd > NextBlockOffset) {
758065e0324SZi Xuan Wu     Growth = CPEEnd - NextBlockOffset;
759065e0324SZi Xuan Wu     // Compute the padding that would go at the end of the CPE to align the next
760065e0324SZi Xuan Wu     // block.
761065e0324SZi Xuan Wu     Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);
762065e0324SZi Xuan Wu 
763065e0324SZi Xuan Wu     // If the CPE is to be inserted before the instruction, that will raise
764065e0324SZi Xuan Wu     // the offset of the instruction. Also account for unknown alignment padding
765065e0324SZi Xuan Wu     // in blocks between CPE and the user.
766065e0324SZi Xuan Wu     if (CPEOffset < UserOffset)
767065e0324SZi Xuan Wu       UserOffset += Growth;
768065e0324SZi Xuan Wu   } else
769065e0324SZi Xuan Wu     // CPE fits in existing padding.
770065e0324SZi Xuan Wu     Growth = 0;
771065e0324SZi Xuan Wu 
772065e0324SZi Xuan Wu   return isOffsetInRange(UserOffset, CPEOffset, U);
773065e0324SZi Xuan Wu }
774065e0324SZi Xuan Wu 
775065e0324SZi Xuan Wu /// isCPEntryInRange - Returns true if the distance between specific MI and
776065e0324SZi Xuan Wu /// specific ConstPool entry instruction can fit in MI's displacement field.
isCPEntryInRange(MachineInstr * MI,unsigned UserOffset,MachineInstr * CPEMI,unsigned MaxDisp,bool NegOk,bool DoDump)777065e0324SZi Xuan Wu bool CSKYConstantIslands::isCPEntryInRange(MachineInstr *MI,
778065e0324SZi Xuan Wu                                            unsigned UserOffset,
779065e0324SZi Xuan Wu                                            MachineInstr *CPEMI,
780065e0324SZi Xuan Wu                                            unsigned MaxDisp, bool NegOk,
781065e0324SZi Xuan Wu                                            bool DoDump) {
782065e0324SZi Xuan Wu   unsigned CPEOffset = getOffsetOf(CPEMI);
783065e0324SZi Xuan Wu 
784065e0324SZi Xuan Wu   if (DoDump) {
785065e0324SZi Xuan Wu     LLVM_DEBUG({
786065e0324SZi Xuan Wu       unsigned Block = MI->getParent()->getNumber();
787065e0324SZi Xuan Wu       const BasicBlockInfo &BBI = BBInfo[Block];
788065e0324SZi Xuan Wu       dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
789065e0324SZi Xuan Wu              << " max delta=" << MaxDisp
790065e0324SZi Xuan Wu              << format(" insn address=%#x", UserOffset) << " in "
791065e0324SZi Xuan Wu              << printMBBReference(*MI->getParent()) << ": "
792065e0324SZi Xuan Wu              << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
793065e0324SZi Xuan Wu              << format("CPE address=%#x offset=%+d: ", CPEOffset,
794065e0324SZi Xuan Wu                        int(CPEOffset - UserOffset));
795065e0324SZi Xuan Wu     });
796065e0324SZi Xuan Wu   }
797065e0324SZi Xuan Wu 
798065e0324SZi Xuan Wu   return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
799065e0324SZi Xuan Wu }
800065e0324SZi Xuan Wu 
801065e0324SZi Xuan Wu #ifndef NDEBUG
802065e0324SZi Xuan Wu /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
803065e0324SZi Xuan Wu /// unconditionally branches to its only successor.
bbIsJumpedOver(MachineBasicBlock * MBB)804065e0324SZi Xuan Wu static bool bbIsJumpedOver(MachineBasicBlock *MBB) {
805065e0324SZi Xuan Wu   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
806065e0324SZi Xuan Wu     return false;
807065e0324SZi Xuan Wu   MachineBasicBlock *Succ = *MBB->succ_begin();
808065e0324SZi Xuan Wu   MachineBasicBlock *Pred = *MBB->pred_begin();
809065e0324SZi Xuan Wu   MachineInstr *PredMI = &Pred->back();
810065e0324SZi Xuan Wu   if (PredMI->getOpcode() == CSKY::BR32 /*TODO: change to 16bit instr. */)
811065e0324SZi Xuan Wu     return PredMI->getOperand(0).getMBB() == Succ;
812065e0324SZi Xuan Wu   return false;
813065e0324SZi Xuan Wu }
814065e0324SZi Xuan Wu #endif
815065e0324SZi Xuan Wu 
adjustBBOffsetsAfter(MachineBasicBlock * BB)816065e0324SZi Xuan Wu void CSKYConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
817065e0324SZi Xuan Wu   unsigned BBNum = BB->getNumber();
818065e0324SZi Xuan Wu   for (unsigned I = BBNum + 1, E = MF->getNumBlockIDs(); I < E; ++I) {
819065e0324SZi Xuan Wu     // Get the offset and known bits at the end of the layout predecessor.
820065e0324SZi Xuan Wu     // Include the alignment of the current block.
821065e0324SZi Xuan Wu     unsigned Offset = BBInfo[I - 1].Offset + BBInfo[I - 1].Size;
822065e0324SZi Xuan Wu     BBInfo[I].Offset = Offset;
823065e0324SZi Xuan Wu   }
824065e0324SZi Xuan Wu }
825065e0324SZi Xuan Wu 
826065e0324SZi Xuan Wu /// decrementCPEReferenceCount - find the constant pool entry with index CPI
827065e0324SZi Xuan Wu /// and instruction CPEMI, and decrement its refcount.  If the refcount
828065e0324SZi Xuan Wu /// becomes 0 remove the entry and instruction.  Returns true if we removed
829065e0324SZi Xuan Wu /// the entry, false if we didn't.
decrementCPEReferenceCount(unsigned CPI,MachineInstr * CPEMI)830065e0324SZi Xuan Wu bool CSKYConstantIslands::decrementCPEReferenceCount(unsigned CPI,
831065e0324SZi Xuan Wu                                                      MachineInstr *CPEMI) {
832065e0324SZi Xuan Wu   // Find the old entry. Eliminate it if it is no longer used.
833065e0324SZi Xuan Wu   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
834065e0324SZi Xuan Wu   assert(CPE && "Unexpected!");
835065e0324SZi Xuan Wu   if (--CPE->RefCount == 0) {
836065e0324SZi Xuan Wu     removeDeadCPEMI(CPEMI);
837065e0324SZi Xuan Wu     CPE->CPEMI = nullptr;
838065e0324SZi Xuan Wu     --NumCPEs;
839065e0324SZi Xuan Wu     return true;
840065e0324SZi Xuan Wu   }
841065e0324SZi Xuan Wu   return false;
842065e0324SZi Xuan Wu }
843065e0324SZi Xuan Wu 
844065e0324SZi Xuan Wu /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
845065e0324SZi Xuan Wu /// if not, see if an in-range clone of the CPE is in range, and if so,
846065e0324SZi Xuan Wu /// change the data structures so the user references the clone.  Returns:
847065e0324SZi Xuan Wu /// 0 = no existing entry found
848065e0324SZi Xuan Wu /// 1 = entry found, and there were no code insertions or deletions
849065e0324SZi Xuan Wu /// 2 = entry found, and there were code insertions or deletions
findInRangeCPEntry(CPUser & U,unsigned UserOffset)850065e0324SZi Xuan Wu int CSKYConstantIslands::findInRangeCPEntry(CPUser &U, unsigned UserOffset) {
851065e0324SZi Xuan Wu   MachineInstr *UserMI = U.MI;
852065e0324SZi Xuan Wu   MachineInstr *CPEMI = U.CPEMI;
853065e0324SZi Xuan Wu 
854065e0324SZi Xuan Wu   // Check to see if the CPE is already in-range.
855065e0324SZi Xuan Wu   if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
856065e0324SZi Xuan Wu                        true)) {
857065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "In range\n");
858065e0324SZi Xuan Wu     return 1;
859065e0324SZi Xuan Wu   }
860065e0324SZi Xuan Wu 
861065e0324SZi Xuan Wu   // No.  Look for previously created clones of the CPE that are in range.
862065e0324SZi Xuan Wu   unsigned CPI = CPEMI->getOperand(1).getIndex();
863065e0324SZi Xuan Wu   std::vector<CPEntry> &CPEs = CPEntries[CPI];
864065e0324SZi Xuan Wu   for (unsigned I = 0, E = CPEs.size(); I != E; ++I) {
865065e0324SZi Xuan Wu     // We already tried this one
866065e0324SZi Xuan Wu     if (CPEs[I].CPEMI == CPEMI)
867065e0324SZi Xuan Wu       continue;
868065e0324SZi Xuan Wu     // Removing CPEs can leave empty entries, skip
869065e0324SZi Xuan Wu     if (CPEs[I].CPEMI == nullptr)
870065e0324SZi Xuan Wu       continue;
871065e0324SZi Xuan Wu     if (isCPEntryInRange(UserMI, UserOffset, CPEs[I].CPEMI, U.getMaxDisp(),
872065e0324SZi Xuan Wu                          U.NegOk)) {
873065e0324SZi Xuan Wu       LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
874065e0324SZi Xuan Wu                         << CPEs[I].CPI << "\n");
875065e0324SZi Xuan Wu       // Point the CPUser node to the replacement
876065e0324SZi Xuan Wu       U.CPEMI = CPEs[I].CPEMI;
877065e0324SZi Xuan Wu       // Change the CPI in the instruction operand to refer to the clone.
878065e0324SZi Xuan Wu       for (unsigned J = 0, E = UserMI->getNumOperands(); J != E; ++J)
879065e0324SZi Xuan Wu         if (UserMI->getOperand(J).isCPI()) {
880065e0324SZi Xuan Wu           UserMI->getOperand(J).setIndex(CPEs[I].CPI);
881065e0324SZi Xuan Wu           break;
882065e0324SZi Xuan Wu         }
883065e0324SZi Xuan Wu       // Adjust the refcount of the clone...
884065e0324SZi Xuan Wu       CPEs[I].RefCount++;
885065e0324SZi Xuan Wu       // ...and the original.  If we didn't remove the old entry, none of the
886065e0324SZi Xuan Wu       // addresses changed, so we don't need another pass.
887065e0324SZi Xuan Wu       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
888065e0324SZi Xuan Wu     }
889065e0324SZi Xuan Wu   }
890065e0324SZi Xuan Wu   return 0;
891065e0324SZi Xuan Wu }
892065e0324SZi Xuan Wu 
893065e0324SZi Xuan Wu /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
894065e0324SZi Xuan Wu /// the specific unconditional branch instruction.
getUnconditionalBrDisp(int Opc)895065e0324SZi Xuan Wu static inline unsigned getUnconditionalBrDisp(int Opc) {
896065e0324SZi Xuan Wu   unsigned Bits, Scale;
897065e0324SZi Xuan Wu 
898065e0324SZi Xuan Wu   switch (Opc) {
899065e0324SZi Xuan Wu   case CSKY::BR16:
900065e0324SZi Xuan Wu     Bits = 10;
901065e0324SZi Xuan Wu     Scale = 2;
902065e0324SZi Xuan Wu     break;
903065e0324SZi Xuan Wu   case CSKY::BR32:
904065e0324SZi Xuan Wu     Bits = 16;
905065e0324SZi Xuan Wu     Scale = 2;
906065e0324SZi Xuan Wu     break;
907065e0324SZi Xuan Wu   default:
908ef437a7dSFangrui Song     llvm_unreachable("");
909065e0324SZi Xuan Wu   }
910065e0324SZi Xuan Wu 
911065e0324SZi Xuan Wu   unsigned MaxOffs = ((1 << (Bits - 1)) - 1) * Scale;
912065e0324SZi Xuan Wu   return MaxOffs;
913065e0324SZi Xuan Wu }
914065e0324SZi Xuan Wu 
915065e0324SZi Xuan Wu /// findAvailableWater - Look for an existing entry in the WaterList in which
916065e0324SZi Xuan Wu /// we can place the CPE referenced from U so it's within range of U's MI.
917065e0324SZi Xuan Wu /// Returns true if found, false if not.  If it returns true, WaterIter
918065e0324SZi Xuan Wu /// is set to the WaterList entry.
919065e0324SZi Xuan Wu /// To ensure that this pass
920065e0324SZi Xuan Wu /// terminates, the CPE location for a particular CPUser is only allowed to
921065e0324SZi Xuan Wu /// move to a lower address, so search backward from the end of the list and
922065e0324SZi Xuan Wu /// prefer the first water that is in range.
findAvailableWater(CPUser & U,unsigned UserOffset,water_iterator & WaterIter)923065e0324SZi Xuan Wu bool CSKYConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
924065e0324SZi Xuan Wu                                              water_iterator &WaterIter) {
925065e0324SZi Xuan Wu   if (WaterList.empty())
926065e0324SZi Xuan Wu     return false;
927065e0324SZi Xuan Wu 
928065e0324SZi Xuan Wu   unsigned BestGrowth = ~0u;
929065e0324SZi Xuan Wu   for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
930065e0324SZi Xuan Wu        --IP) {
931065e0324SZi Xuan Wu     MachineBasicBlock *WaterBB = *IP;
932065e0324SZi Xuan Wu     // Check if water is in range and is either at a lower address than the
933065e0324SZi Xuan Wu     // current "high water mark" or a new water block that was created since
934065e0324SZi Xuan Wu     // the previous iteration by inserting an unconditional branch.  In the
935065e0324SZi Xuan Wu     // latter case, we want to allow resetting the high water mark back to
936065e0324SZi Xuan Wu     // this new water since we haven't seen it before.  Inserting branches
937065e0324SZi Xuan Wu     // should be relatively uncommon and when it does happen, we want to be
938065e0324SZi Xuan Wu     // sure to take advantage of it for all the CPEs near that block, so that
939065e0324SZi Xuan Wu     // we don't insert more branches than necessary.
940065e0324SZi Xuan Wu     unsigned Growth;
941065e0324SZi Xuan Wu     if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
942065e0324SZi Xuan Wu         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
943065e0324SZi Xuan Wu          NewWaterList.count(WaterBB)) &&
944065e0324SZi Xuan Wu         Growth < BestGrowth) {
945065e0324SZi Xuan Wu       // This is the least amount of required padding seen so far.
946065e0324SZi Xuan Wu       BestGrowth = Growth;
947065e0324SZi Xuan Wu       WaterIter = IP;
948065e0324SZi Xuan Wu       LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
949065e0324SZi Xuan Wu                         << " Growth=" << Growth << '\n');
950065e0324SZi Xuan Wu 
951065e0324SZi Xuan Wu       // Keep looking unless it is perfect.
952065e0324SZi Xuan Wu       if (BestGrowth == 0)
953065e0324SZi Xuan Wu         return true;
954065e0324SZi Xuan Wu     }
955065e0324SZi Xuan Wu     if (IP == B)
956065e0324SZi Xuan Wu       break;
957065e0324SZi Xuan Wu   }
958065e0324SZi Xuan Wu   return BestGrowth != ~0u;
959065e0324SZi Xuan Wu }
960065e0324SZi Xuan Wu 
961065e0324SZi Xuan Wu /// createNewWater - No existing WaterList entry will work for
962065e0324SZi Xuan Wu /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
963065e0324SZi Xuan Wu /// block is used if in range, and the conditional branch munged so control
964065e0324SZi Xuan Wu /// flow is correct.  Otherwise the block is split to create a hole with an
965065e0324SZi Xuan Wu /// unconditional branch around it.  In either case NewMBB is set to a
966065e0324SZi Xuan Wu /// block following which the new island can be inserted (the WaterList
967065e0324SZi Xuan Wu /// is not adjusted).
createNewWater(unsigned CPUserIndex,unsigned UserOffset,MachineBasicBlock * & NewMBB)968065e0324SZi Xuan Wu void CSKYConstantIslands::createNewWater(unsigned CPUserIndex,
969065e0324SZi Xuan Wu                                          unsigned UserOffset,
970065e0324SZi Xuan Wu                                          MachineBasicBlock *&NewMBB) {
971065e0324SZi Xuan Wu   CPUser &U = CPUsers[CPUserIndex];
972065e0324SZi Xuan Wu   MachineInstr *UserMI = U.MI;
973065e0324SZi Xuan Wu   MachineInstr *CPEMI = U.CPEMI;
974065e0324SZi Xuan Wu   MachineBasicBlock *UserMBB = UserMI->getParent();
975065e0324SZi Xuan Wu   const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
976065e0324SZi Xuan Wu 
977065e0324SZi Xuan Wu   // If the block does not end in an unconditional branch already, and if the
978065e0324SZi Xuan Wu   // end of the block is within range, make new water there.
979065e0324SZi Xuan Wu   if (bbHasFallthrough(UserMBB)) {
980065e0324SZi Xuan Wu     // Size of branch to insert.
981065e0324SZi Xuan Wu     unsigned Delta = 4;
982065e0324SZi Xuan Wu     // Compute the offset where the CPE will begin.
983065e0324SZi Xuan Wu     unsigned CPEOffset = UserBBI.postOffset() + Delta;
984065e0324SZi Xuan Wu 
985065e0324SZi Xuan Wu     if (isOffsetInRange(UserOffset, CPEOffset, U)) {
986065e0324SZi Xuan Wu       LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
987065e0324SZi Xuan Wu                         << format(", expected CPE offset %#x\n", CPEOffset));
988065e0324SZi Xuan Wu       NewMBB = &*++UserMBB->getIterator();
989065e0324SZi Xuan Wu       // Add an unconditional branch from UserMBB to fallthrough block.  Record
990065e0324SZi Xuan Wu       // it for branch lengthening; this new branch will not get out of range,
991065e0324SZi Xuan Wu       // but if the preceding conditional branch is out of range, the targets
992065e0324SZi Xuan Wu       // will be exchanged, and the altered branch may be out of range, so the
993065e0324SZi Xuan Wu       // machinery has to know about it.
994065e0324SZi Xuan Wu 
995065e0324SZi Xuan Wu       // TODO: Add support for 16bit instr.
996065e0324SZi Xuan Wu       int UncondBr = CSKY::BR32;
997065e0324SZi Xuan Wu       auto *NewMI = BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
998065e0324SZi Xuan Wu                         .addMBB(NewMBB)
999065e0324SZi Xuan Wu                         .getInstr();
1000065e0324SZi Xuan Wu       unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1001065e0324SZi Xuan Wu       ImmBranches.push_back(
1002065e0324SZi Xuan Wu           ImmBranch(&UserMBB->back(), MaxDisp, false, UncondBr));
1003065e0324SZi Xuan Wu       BBInfo[UserMBB->getNumber()].Size += TII->getInstSizeInBytes(*NewMI);
1004065e0324SZi Xuan Wu       adjustBBOffsetsAfter(UserMBB);
1005065e0324SZi Xuan Wu       return;
1006065e0324SZi Xuan Wu     }
1007065e0324SZi Xuan Wu   }
1008065e0324SZi Xuan Wu 
1009065e0324SZi Xuan Wu   // What a big block.  Find a place within the block to split it.
1010065e0324SZi Xuan Wu 
1011065e0324SZi Xuan Wu   // Try to split the block so it's fully aligned.  Compute the latest split
1012065e0324SZi Xuan Wu   // point where we can add a 4-byte branch instruction, and then align to
1013065e0324SZi Xuan Wu   // Align which is the largest possible alignment in the function.
1014065e0324SZi Xuan Wu   const Align Align = MF->getAlignment();
1015065e0324SZi Xuan Wu   unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1016065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1017065e0324SZi Xuan Wu                               BaseInsertOffset));
1018065e0324SZi Xuan Wu 
1019065e0324SZi Xuan Wu   // The 4 in the following is for the unconditional branch we'll be inserting
1020065e0324SZi Xuan Wu   // Alignment of the island is handled
1021065e0324SZi Xuan Wu   // inside isOffsetInRange.
1022065e0324SZi Xuan Wu   BaseInsertOffset -= 4;
1023065e0324SZi Xuan Wu 
1024065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1025065e0324SZi Xuan Wu                     << " la=" << Log2(Align) << '\n');
1026065e0324SZi Xuan Wu 
1027065e0324SZi Xuan Wu   // This could point off the end of the block if we've already got constant
1028065e0324SZi Xuan Wu   // pool entries following this block; only the last one is in the water list.
1029065e0324SZi Xuan Wu   // Back past any possible branches (allow for a conditional and a maximally
1030065e0324SZi Xuan Wu   // long unconditional).
1031065e0324SZi Xuan Wu   if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1032065e0324SZi Xuan Wu     BaseInsertOffset = UserBBI.postOffset() - 8;
1033065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1034065e0324SZi Xuan Wu   }
1035065e0324SZi Xuan Wu   unsigned EndInsertOffset =
1036065e0324SZi Xuan Wu       BaseInsertOffset + 4 + CPEMI->getOperand(2).getImm();
1037065e0324SZi Xuan Wu   MachineBasicBlock::iterator MI = UserMI;
1038065e0324SZi Xuan Wu   ++MI;
1039065e0324SZi Xuan Wu   unsigned CPUIndex = CPUserIndex + 1;
1040065e0324SZi Xuan Wu   unsigned NumCPUsers = CPUsers.size();
1041065e0324SZi Xuan Wu   for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1042065e0324SZi Xuan Wu        Offset < BaseInsertOffset;
1043065e0324SZi Xuan Wu        Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1044065e0324SZi Xuan Wu     assert(MI != UserMBB->end() && "Fell off end of block");
1045065e0324SZi Xuan Wu     if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1046065e0324SZi Xuan Wu       CPUser &U = CPUsers[CPUIndex];
1047065e0324SZi Xuan Wu       if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1048065e0324SZi Xuan Wu         // Shift intertion point by one unit of alignment so it is within reach.
1049065e0324SZi Xuan Wu         BaseInsertOffset -= Align.value();
1050065e0324SZi Xuan Wu         EndInsertOffset -= Align.value();
1051065e0324SZi Xuan Wu       }
1052065e0324SZi Xuan Wu       // This is overly conservative, as we don't account for CPEMIs being
1053065e0324SZi Xuan Wu       // reused within the block, but it doesn't matter much.  Also assume CPEs
1054065e0324SZi Xuan Wu       // are added in order with alignment padding.  We may eventually be able
1055065e0324SZi Xuan Wu       // to pack the aligned CPEs better.
1056065e0324SZi Xuan Wu       EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1057065e0324SZi Xuan Wu       CPUIndex++;
1058065e0324SZi Xuan Wu     }
1059065e0324SZi Xuan Wu   }
1060065e0324SZi Xuan Wu 
1061065e0324SZi Xuan Wu   NewMBB = splitBlockBeforeInstr(*--MI);
1062065e0324SZi Xuan Wu }
1063065e0324SZi Xuan Wu 
1064065e0324SZi Xuan Wu /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1065065e0324SZi Xuan Wu /// is out-of-range.  If so, pick up the constant pool value and move it some
1066065e0324SZi Xuan Wu /// place in-range.  Return true if we changed any addresses (thus must run
1067065e0324SZi Xuan Wu /// another pass of branch lengthening), false otherwise.
handleConstantPoolUser(unsigned CPUserIndex)1068065e0324SZi Xuan Wu bool CSKYConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1069065e0324SZi Xuan Wu   CPUser &U = CPUsers[CPUserIndex];
1070065e0324SZi Xuan Wu   MachineInstr *UserMI = U.MI;
1071065e0324SZi Xuan Wu   MachineInstr *CPEMI = U.CPEMI;
1072065e0324SZi Xuan Wu   unsigned CPI = CPEMI->getOperand(1).getIndex();
1073065e0324SZi Xuan Wu   unsigned Size = CPEMI->getOperand(2).getImm();
1074065e0324SZi Xuan Wu   // Compute this only once, it's expensive.
1075065e0324SZi Xuan Wu   unsigned UserOffset = getUserOffset(U);
1076065e0324SZi Xuan Wu 
1077065e0324SZi Xuan Wu   // See if the current entry is within range, or there is a clone of it
1078065e0324SZi Xuan Wu   // in range.
1079065e0324SZi Xuan Wu   int result = findInRangeCPEntry(U, UserOffset);
1080065e0324SZi Xuan Wu   if (result == 1)
1081065e0324SZi Xuan Wu     return false;
1082065e0324SZi Xuan Wu   if (result == 2)
1083065e0324SZi Xuan Wu     return true;
1084065e0324SZi Xuan Wu 
1085065e0324SZi Xuan Wu   // Look for water where we can place this CPE.
1086065e0324SZi Xuan Wu   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1087065e0324SZi Xuan Wu   MachineBasicBlock *NewMBB;
1088065e0324SZi Xuan Wu   water_iterator IP;
1089065e0324SZi Xuan Wu   if (findAvailableWater(U, UserOffset, IP)) {
1090065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "Found water in range\n");
1091065e0324SZi Xuan Wu     MachineBasicBlock *WaterBB = *IP;
1092065e0324SZi Xuan Wu 
1093065e0324SZi Xuan Wu     // If the original WaterList entry was "new water" on this iteration,
1094065e0324SZi Xuan Wu     // propagate that to the new island.  This is just keeping NewWaterList
1095065e0324SZi Xuan Wu     // updated to match the WaterList, which will be updated below.
1096065e0324SZi Xuan Wu     if (NewWaterList.erase(WaterBB))
1097065e0324SZi Xuan Wu       NewWaterList.insert(NewIsland);
1098065e0324SZi Xuan Wu 
1099065e0324SZi Xuan Wu     // The new CPE goes before the following block (NewMBB).
1100065e0324SZi Xuan Wu     NewMBB = &*++WaterBB->getIterator();
1101065e0324SZi Xuan Wu   } else {
1102065e0324SZi Xuan Wu     LLVM_DEBUG(dbgs() << "No water found\n");
1103065e0324SZi Xuan Wu     createNewWater(CPUserIndex, UserOffset, NewMBB);
1104065e0324SZi Xuan Wu 
1105065e0324SZi Xuan Wu     // splitBlockBeforeInstr adds to WaterList, which is important when it is
1106065e0324SZi Xuan Wu     // called while handling branches so that the water will be seen on the
1107065e0324SZi Xuan Wu     // next iteration for constant pools, but in this context, we don't want
1108065e0324SZi Xuan Wu     // it.  Check for this so it will be removed from the WaterList.
1109065e0324SZi Xuan Wu     // Also remove any entry from NewWaterList.
1110065e0324SZi Xuan Wu     MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
1111065e0324SZi Xuan Wu     IP = llvm::find(WaterList, WaterBB);
1112065e0324SZi Xuan Wu     if (IP != WaterList.end())
1113065e0324SZi Xuan Wu       NewWaterList.erase(WaterBB);
1114065e0324SZi Xuan Wu 
1115065e0324SZi Xuan Wu     // We are adding new water.  Update NewWaterList.
1116065e0324SZi Xuan Wu     NewWaterList.insert(NewIsland);
1117065e0324SZi Xuan Wu   }
1118065e0324SZi Xuan Wu 
1119065e0324SZi Xuan Wu   // Remove the original WaterList entry; we want subsequent insertions in
1120065e0324SZi Xuan Wu   // this vicinity to go after the one we're about to insert.  This
1121065e0324SZi Xuan Wu   // considerably reduces the number of times we have to move the same CPE
1122065e0324SZi Xuan Wu   // more than once and is also important to ensure the algorithm terminates.
1123065e0324SZi Xuan Wu   if (IP != WaterList.end())
1124065e0324SZi Xuan Wu     WaterList.erase(IP);
1125065e0324SZi Xuan Wu 
1126065e0324SZi Xuan Wu   // Okay, we know we can put an island before NewMBB now, do it!
1127065e0324SZi Xuan Wu   MF->insert(NewMBB->getIterator(), NewIsland);
1128065e0324SZi Xuan Wu 
1129065e0324SZi Xuan Wu   // Update internal data structures to account for the newly inserted MBB.
1130065e0324SZi Xuan Wu   updateForInsertedWaterBlock(NewIsland);
1131065e0324SZi Xuan Wu 
1132065e0324SZi Xuan Wu   // Decrement the old entry, and remove it if refcount becomes 0.
1133065e0324SZi Xuan Wu   decrementCPEReferenceCount(CPI, CPEMI);
1134065e0324SZi Xuan Wu 
1135065e0324SZi Xuan Wu   // No existing clone of this CPE is within range.
1136065e0324SZi Xuan Wu   // We will be generating a new clone.  Get a UID for it.
1137065e0324SZi Xuan Wu   unsigned ID = createPICLabelUId();
1138065e0324SZi Xuan Wu 
1139065e0324SZi Xuan Wu   // Now that we have an island to add the CPE to, clone the original CPE and
1140065e0324SZi Xuan Wu   // add it to the island.
1141065e0324SZi Xuan Wu   U.HighWaterMark = NewIsland;
1142065e0324SZi Xuan Wu   U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(CSKY::CONSTPOOL_ENTRY))
1143065e0324SZi Xuan Wu                 .addImm(ID)
1144065e0324SZi Xuan Wu                 .addConstantPoolIndex(CPI)
1145065e0324SZi Xuan Wu                 .addImm(Size);
1146065e0324SZi Xuan Wu   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1147065e0324SZi Xuan Wu   ++NumCPEs;
1148065e0324SZi Xuan Wu 
1149065e0324SZi Xuan Wu   // Mark the basic block as aligned as required by the const-pool entry.
1150065e0324SZi Xuan Wu   NewIsland->setAlignment(getCPEAlign(*U.CPEMI));
1151065e0324SZi Xuan Wu 
1152065e0324SZi Xuan Wu   // Increase the size of the island block to account for the new entry.
1153065e0324SZi Xuan Wu   BBInfo[NewIsland->getNumber()].Size += Size;
1154065e0324SZi Xuan Wu   adjustBBOffsetsAfter(&*--NewIsland->getIterator());
1155065e0324SZi Xuan Wu 
1156065e0324SZi Xuan Wu   // Finally, change the CPI in the instruction operand to be ID.
1157065e0324SZi Xuan Wu   for (unsigned I = 0, E = UserMI->getNumOperands(); I != E; ++I)
1158065e0324SZi Xuan Wu     if (UserMI->getOperand(I).isCPI()) {
1159065e0324SZi Xuan Wu       UserMI->getOperand(I).setIndex(ID);
1160065e0324SZi Xuan Wu       break;
1161065e0324SZi Xuan Wu     }
1162065e0324SZi Xuan Wu 
1163065e0324SZi Xuan Wu   LLVM_DEBUG(
1164065e0324SZi Xuan Wu       dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1165065e0324SZi Xuan Wu              << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1166065e0324SZi Xuan Wu 
1167065e0324SZi Xuan Wu   return true;
1168065e0324SZi Xuan Wu }
1169065e0324SZi Xuan Wu 
1170065e0324SZi Xuan Wu /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1171065e0324SZi Xuan Wu /// sizes and offsets of impacted basic blocks.
removeDeadCPEMI(MachineInstr * CPEMI)1172065e0324SZi Xuan Wu void CSKYConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1173065e0324SZi Xuan Wu   MachineBasicBlock *CPEBB = CPEMI->getParent();
1174065e0324SZi Xuan Wu   unsigned Size = CPEMI->getOperand(2).getImm();
1175065e0324SZi Xuan Wu   CPEMI->eraseFromParent();
1176065e0324SZi Xuan Wu   BBInfo[CPEBB->getNumber()].Size -= Size;
1177065e0324SZi Xuan Wu   // All succeeding offsets have the current size value added in, fix this.
1178065e0324SZi Xuan Wu   if (CPEBB->empty()) {
1179065e0324SZi Xuan Wu     BBInfo[CPEBB->getNumber()].Size = 0;
1180065e0324SZi Xuan Wu 
1181065e0324SZi Xuan Wu     // This block no longer needs to be aligned.
1182065e0324SZi Xuan Wu     CPEBB->setAlignment(Align(4));
1183065e0324SZi Xuan Wu   } else {
1184065e0324SZi Xuan Wu     // Entries are sorted by descending alignment, so realign from the front.
1185065e0324SZi Xuan Wu     CPEBB->setAlignment(getCPEAlign(*CPEBB->begin()));
1186065e0324SZi Xuan Wu   }
1187065e0324SZi Xuan Wu 
1188065e0324SZi Xuan Wu   adjustBBOffsetsAfter(CPEBB);
1189065e0324SZi Xuan Wu   // An island has only one predecessor BB and one successor BB. Check if
1190065e0324SZi Xuan Wu   // this BB's predecessor jumps directly to this BB's successor. This
1191065e0324SZi Xuan Wu   // shouldn't happen currently.
1192065e0324SZi Xuan Wu   assert(!bbIsJumpedOver(CPEBB) && "How did this happen?");
1193065e0324SZi Xuan Wu   // FIXME: remove the empty blocks after all the work is done?
1194065e0324SZi Xuan Wu }
1195065e0324SZi Xuan Wu 
1196065e0324SZi Xuan Wu /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1197065e0324SZi Xuan Wu /// are zero.
removeUnusedCPEntries()1198065e0324SZi Xuan Wu bool CSKYConstantIslands::removeUnusedCPEntries() {
1199065e0324SZi Xuan Wu   unsigned MadeChange = false;
1200065e0324SZi Xuan Wu   for (unsigned I = 0, E = CPEntries.size(); I != E; ++I) {
1201065e0324SZi Xuan Wu     std::vector<CPEntry> &CPEs = CPEntries[I];
1202065e0324SZi Xuan Wu     for (unsigned J = 0, Ee = CPEs.size(); J != Ee; ++J) {
1203065e0324SZi Xuan Wu       if (CPEs[J].RefCount == 0 && CPEs[J].CPEMI) {
1204065e0324SZi Xuan Wu         removeDeadCPEMI(CPEs[J].CPEMI);
1205065e0324SZi Xuan Wu         CPEs[J].CPEMI = nullptr;
1206065e0324SZi Xuan Wu         MadeChange = true;
1207065e0324SZi Xuan Wu       }
1208065e0324SZi Xuan Wu     }
1209065e0324SZi Xuan Wu   }
1210065e0324SZi Xuan Wu   return MadeChange;
1211065e0324SZi Xuan Wu }
1212065e0324SZi Xuan Wu 
1213065e0324SZi Xuan Wu /// isBBInRange - Returns true if the distance between specific MI and
1214065e0324SZi Xuan Wu /// specific BB can fit in MI's displacement field.
isBBInRange(MachineInstr * MI,MachineBasicBlock * DestBB,unsigned MaxDisp)1215065e0324SZi Xuan Wu bool CSKYConstantIslands::isBBInRange(MachineInstr *MI,
1216065e0324SZi Xuan Wu                                       MachineBasicBlock *DestBB,
1217065e0324SZi Xuan Wu                                       unsigned MaxDisp) {
1218065e0324SZi Xuan Wu   unsigned BrOffset = getOffsetOf(MI);
1219065e0324SZi Xuan Wu   unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1220065e0324SZi Xuan Wu 
1221065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)
1222065e0324SZi Xuan Wu                     << " from " << printMBBReference(*MI->getParent())
1223065e0324SZi Xuan Wu                     << " max delta=" << MaxDisp << " from " << getOffsetOf(MI)
1224065e0324SZi Xuan Wu                     << " to " << DestOffset << " offset "
1225065e0324SZi Xuan Wu                     << int(DestOffset - BrOffset) << "\t" << *MI);
1226065e0324SZi Xuan Wu 
1227065e0324SZi Xuan Wu   if (BrOffset <= DestOffset) {
1228065e0324SZi Xuan Wu     // Branch before the Dest.
1229065e0324SZi Xuan Wu     if (DestOffset - BrOffset <= MaxDisp)
1230065e0324SZi Xuan Wu       return true;
1231065e0324SZi Xuan Wu   } else {
1232065e0324SZi Xuan Wu     if (BrOffset - DestOffset <= MaxDisp)
1233065e0324SZi Xuan Wu       return true;
1234065e0324SZi Xuan Wu   }
1235065e0324SZi Xuan Wu   return false;
1236065e0324SZi Xuan Wu }
1237065e0324SZi Xuan Wu 
1238065e0324SZi Xuan Wu /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1239065e0324SZi Xuan Wu /// away to fit in its displacement field.
fixupImmediateBr(ImmBranch & Br)1240065e0324SZi Xuan Wu bool CSKYConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1241065e0324SZi Xuan Wu   MachineInstr *MI = Br.MI;
1242065e0324SZi Xuan Wu   MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);
1243065e0324SZi Xuan Wu 
1244065e0324SZi Xuan Wu   // Check to see if the DestBB is already in-range.
1245065e0324SZi Xuan Wu   if (isBBInRange(MI, DestBB, Br.MaxDisp))
1246065e0324SZi Xuan Wu     return false;
1247065e0324SZi Xuan Wu 
1248065e0324SZi Xuan Wu   if (!Br.IsCond)
1249065e0324SZi Xuan Wu     return fixupUnconditionalBr(Br);
1250065e0324SZi Xuan Wu   return fixupConditionalBr(Br);
1251065e0324SZi Xuan Wu }
1252065e0324SZi Xuan Wu 
1253065e0324SZi Xuan Wu /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1254065e0324SZi Xuan Wu /// too far away to fit in its displacement field. If the LR register has been
1255065e0324SZi Xuan Wu /// spilled in the epilogue, then we can use BSR to implement a far jump.
1256065e0324SZi Xuan Wu /// Otherwise, add an intermediate branch instruction to a branch.
fixupUnconditionalBr(ImmBranch & Br)1257065e0324SZi Xuan Wu bool CSKYConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1258065e0324SZi Xuan Wu   MachineInstr *MI = Br.MI;
1259065e0324SZi Xuan Wu   MachineBasicBlock *MBB = MI->getParent();
1260065e0324SZi Xuan Wu 
1261065e0324SZi Xuan Wu   if (!MFI->isLRSpilled())
1262065e0324SZi Xuan Wu     report_fatal_error("underestimated function size");
1263065e0324SZi Xuan Wu 
1264065e0324SZi Xuan Wu   // Use BSR to implement far jump.
1265065e0324SZi Xuan Wu   Br.MaxDisp = ((1 << (26 - 1)) - 1) * 2;
1266065e0324SZi Xuan Wu   MI->setDesc(TII->get(CSKY::BSR32_BR));
1267065e0324SZi Xuan Wu   BBInfo[MBB->getNumber()].Size += 4;
1268065e0324SZi Xuan Wu   adjustBBOffsetsAfter(MBB);
1269065e0324SZi Xuan Wu   ++NumUBrFixed;
1270065e0324SZi Xuan Wu 
1271065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1272065e0324SZi Xuan Wu 
1273065e0324SZi Xuan Wu   return true;
1274065e0324SZi Xuan Wu }
1275065e0324SZi Xuan Wu 
1276065e0324SZi Xuan Wu /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1277065e0324SZi Xuan Wu /// far away to fit in its displacement field. It is converted to an inverse
1278065e0324SZi Xuan Wu /// conditional branch + an unconditional branch to the destination.
fixupConditionalBr(ImmBranch & Br)1279065e0324SZi Xuan Wu bool CSKYConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1280065e0324SZi Xuan Wu   MachineInstr *MI = Br.MI;
1281065e0324SZi Xuan Wu   MachineBasicBlock *DestBB = TII->getBranchDestBlock(*MI);
1282065e0324SZi Xuan Wu 
1283065e0324SZi Xuan Wu   SmallVector<MachineOperand, 4> Cond;
1284065e0324SZi Xuan Wu   Cond.push_back(MachineOperand::CreateImm(MI->getOpcode()));
1285065e0324SZi Xuan Wu   Cond.push_back(MI->getOperand(0));
1286065e0324SZi Xuan Wu   TII->reverseBranchCondition(Cond);
1287065e0324SZi Xuan Wu 
1288065e0324SZi Xuan Wu   // Add an unconditional branch to the destination and invert the branch
1289065e0324SZi Xuan Wu   // condition to jump over it:
1290065e0324SZi Xuan Wu   // bteqz L1
1291065e0324SZi Xuan Wu   // =>
1292065e0324SZi Xuan Wu   // bnez L2
1293065e0324SZi Xuan Wu   // b   L1
1294065e0324SZi Xuan Wu   // L2:
1295065e0324SZi Xuan Wu 
1296065e0324SZi Xuan Wu   // If the branch is at the end of its MBB and that has a fall-through block,
1297065e0324SZi Xuan Wu   // direct the updated conditional branch to the fall-through block. Otherwise,
1298065e0324SZi Xuan Wu   // split the MBB before the next instruction.
1299065e0324SZi Xuan Wu   MachineBasicBlock *MBB = MI->getParent();
1300065e0324SZi Xuan Wu   MachineInstr *BMI = &MBB->back();
1301065e0324SZi Xuan Wu   bool NeedSplit = (BMI != MI) || !bbHasFallthrough(MBB);
1302065e0324SZi Xuan Wu 
1303065e0324SZi Xuan Wu   ++NumCBrFixed;
1304065e0324SZi Xuan Wu   if (BMI != MI) {
1305065e0324SZi Xuan Wu     if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1306065e0324SZi Xuan Wu         BMI->isUnconditionalBranch()) {
1307065e0324SZi Xuan Wu       // Last MI in the BB is an unconditional branch. Can we simply invert the
1308065e0324SZi Xuan Wu       // condition and swap destinations:
1309065e0324SZi Xuan Wu       // beqz L1
1310065e0324SZi Xuan Wu       // b   L2
1311065e0324SZi Xuan Wu       // =>
1312065e0324SZi Xuan Wu       // bnez L2
1313065e0324SZi Xuan Wu       // b   L1
1314065e0324SZi Xuan Wu       MachineBasicBlock *NewDest = TII->getBranchDestBlock(*BMI);
1315065e0324SZi Xuan Wu       if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1316065e0324SZi Xuan Wu         LLVM_DEBUG(
1317065e0324SZi Xuan Wu             dbgs() << "  Invert Bcc condition and swap its destination with "
1318065e0324SZi Xuan Wu                    << *BMI);
1319065e0324SZi Xuan Wu         BMI->getOperand(BMI->getNumExplicitOperands() - 1).setMBB(DestBB);
1320065e0324SZi Xuan Wu         MI->getOperand(MI->getNumExplicitOperands() - 1).setMBB(NewDest);
1321065e0324SZi Xuan Wu 
1322065e0324SZi Xuan Wu         MI->setDesc(TII->get(Cond[0].getImm()));
1323065e0324SZi Xuan Wu         return true;
1324065e0324SZi Xuan Wu       }
1325065e0324SZi Xuan Wu     }
1326065e0324SZi Xuan Wu   }
1327065e0324SZi Xuan Wu 
1328065e0324SZi Xuan Wu   if (NeedSplit) {
1329065e0324SZi Xuan Wu     splitBlockBeforeInstr(*MI);
1330065e0324SZi Xuan Wu     // No need for the branch to the next block. We're adding an unconditional
1331065e0324SZi Xuan Wu     // branch to the destination.
1332065e0324SZi Xuan Wu     int Delta = TII->getInstSizeInBytes(MBB->back());
1333065e0324SZi Xuan Wu     BBInfo[MBB->getNumber()].Size -= Delta;
1334065e0324SZi Xuan Wu     MBB->back().eraseFromParent();
1335065e0324SZi Xuan Wu     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1336065e0324SZi Xuan Wu 
1337065e0324SZi Xuan Wu     // The conditional successor will be swapped between the BBs after this, so
1338065e0324SZi Xuan Wu     // update CFG.
1339065e0324SZi Xuan Wu     MBB->addSuccessor(DestBB);
1340065e0324SZi Xuan Wu     std::next(MBB->getIterator())->removeSuccessor(DestBB);
1341065e0324SZi Xuan Wu   }
1342065e0324SZi Xuan Wu   MachineBasicBlock *NextBB = &*++MBB->getIterator();
1343065e0324SZi Xuan Wu 
1344065e0324SZi Xuan Wu   LLVM_DEBUG(dbgs() << "  Insert B to " << printMBBReference(*DestBB)
1345065e0324SZi Xuan Wu                     << " also invert condition and change dest. to "
1346065e0324SZi Xuan Wu                     << printMBBReference(*NextBB) << "\n");
1347065e0324SZi Xuan Wu 
1348065e0324SZi Xuan Wu   // Insert a new conditional branch and a new unconditional branch.
1349065e0324SZi Xuan Wu   // Also update the ImmBranch as well as adding a new entry for the new branch.
1350065e0324SZi Xuan Wu 
1351065e0324SZi Xuan Wu   BuildMI(MBB, DebugLoc(), TII->get(Cond[0].getImm()))
1352065e0324SZi Xuan Wu       .addReg(MI->getOperand(0).getReg())
1353065e0324SZi Xuan Wu       .addMBB(NextBB);
1354065e0324SZi Xuan Wu 
1355065e0324SZi Xuan Wu   Br.MI = &MBB->back();
1356065e0324SZi Xuan Wu   BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1357065e0324SZi Xuan Wu   BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1358065e0324SZi Xuan Wu   BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1359065e0324SZi Xuan Wu   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1360065e0324SZi Xuan Wu   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1361065e0324SZi Xuan Wu 
1362065e0324SZi Xuan Wu   // Remove the old conditional branch.  It may or may not still be in MBB.
1363065e0324SZi Xuan Wu   BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
1364065e0324SZi Xuan Wu   MI->eraseFromParent();
1365065e0324SZi Xuan Wu   adjustBBOffsetsAfter(MBB);
1366065e0324SZi Xuan Wu   return true;
1367065e0324SZi Xuan Wu }
1368065e0324SZi Xuan Wu 
1369065e0324SZi Xuan Wu /// Returns a pass that converts branches to long branches.
createCSKYConstantIslandPass()1370065e0324SZi Xuan Wu FunctionPass *llvm::createCSKYConstantIslandPass() {
1371065e0324SZi Xuan Wu   return new CSKYConstantIslands();
1372065e0324SZi Xuan Wu }
1373065e0324SZi Xuan Wu 
1374065e0324SZi Xuan Wu INITIALIZE_PASS(CSKYConstantIslands, DEBUG_TYPE,
1375065e0324SZi Xuan Wu                 "CSKY constant island placement and branch shortening pass",
1376065e0324SZi Xuan Wu                 false, false)
1377