blob: 5ee816be37303554eafbf7a49534df848e032e0b [file] [log] [blame]
Eugene Zelenko79220eae2017-08-03 22:12:30 +00001//===- MipsConstantIslandPass.cpp - Emit Pc Relative loads ----------------===//
Reed Kotlerbb3094a2013-02-27 03:33:58 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Reed Kotlerbb3094a2013-02-27 03:33:58 +000010// This pass is used to make Pc relative loads of constants.
Reed Kotler4d0313d2013-11-05 12:04:37 +000011// For now, only Mips16 will use this.
Reed Kotlerbb3094a2013-02-27 03:33:58 +000012//
13// Loading constants inline is expensive on Mips16 and it's in general better
14// to place the constant nearby in code space and then it can be loaded with a
15// simple 16 bit load instruction.
16//
17// The constants can be not just numbers but addresses of functions and labels.
18// This can be particularly helpful in static relocation mode for embedded
Alp Tokerf907b892013-12-05 05:44:44 +000019// non-linux targets.
Reed Kotlerbb3094a2013-02-27 03:33:58 +000020//
Eugene Zelenkodde94e42017-01-30 23:21:32 +000021//===----------------------------------------------------------------------===//
Reed Kotlerbb3094a2013-02-27 03:33:58 +000022
Reed Kotlerbb3094a2013-02-27 03:33:58 +000023#include "Mips.h"
Reed Kotler5c8ae092013-11-13 04:37:52 +000024#include "Mips16InstrInfo.h"
Reed Kotler0f007fc2013-11-05 08:14:14 +000025#include "MipsMachineFunction.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000026#include "MipsSubtarget.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000027#include "llvm/ADT/STLExtras.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000028#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/SmallVector.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000030#include "llvm/ADT/Statistic.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000031#include "llvm/ADT/StringRef.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000032#include "llvm/CodeGen/MachineBasicBlock.h"
Eric Christopher79cc1e32014-09-02 22:28:02 +000033#include "llvm/CodeGen/MachineConstantPool.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000034#include "llvm/CodeGen/MachineFunction.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000035#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000036#include "llvm/CodeGen/MachineInstr.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000037#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000038#include "llvm/CodeGen/MachineOperand.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000039#include "llvm/CodeGen/MachineRegisterInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000040#include "llvm/Config/llvm-config.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000041#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DebugLoc.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000044#include "llvm/IR/Function.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000045#include "llvm/IR/Type.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000046#include "llvm/Support/CommandLine.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000047#include "llvm/Support/Compiler.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000048#include "llvm/Support/Debug.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000049#include "llvm/Support/ErrorHandling.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000050#include "llvm/Support/Format.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000051#include "llvm/Support/MathExtras.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000052#include "llvm/Support/raw_ostream.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000053#include <algorithm>
Eugene Zelenkodde94e42017-01-30 23:21:32 +000054#include <cassert>
55#include <cstdint>
56#include <iterator>
Eugene Zelenkodde94e42017-01-30 23:21:32 +000057#include <vector>
Reed Kotlerbb3094a2013-02-27 03:33:58 +000058
59using namespace llvm;
60
Chandler Carruth84e68b22014-04-22 02:41:26 +000061#define DEBUG_TYPE "mips-constant-islands"
62
Reed Kotler91ae9822013-10-27 21:57:36 +000063STATISTIC(NumCPEs, "Number of constpool entries");
Reed Kotler0f007fc2013-11-05 08:14:14 +000064STATISTIC(NumSplit, "Number of uncond branches inserted");
65STATISTIC(NumCBrFixed, "Number of cond branches fixed");
66STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
Reed Kotler91ae9822013-10-27 21:57:36 +000067
68// FIXME: This option should be removed once it has received sufficient testing.
69static cl::opt<bool>
70AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
71 cl::desc("Align constant islands in code"));
72
Reed Kotler0f007fc2013-11-05 08:14:14 +000073// Rather than do make check tests with huge amounts of code, we force
74// the test to use this amount.
Reed Kotler0f007fc2013-11-05 08:14:14 +000075static cl::opt<int> ConstantIslandsSmallOffset(
76 "mips-constant-islands-small-offset",
77 cl::init(0),
78 cl::desc("Make small offsets be this amount for testing purposes"),
79 cl::Hidden);
80
Reed Kotler45c59272013-11-10 00:09:26 +000081// For testing purposes we tell it to not use relaxed load forms so that it
82// will split blocks.
Reed Kotler45c59272013-11-10 00:09:26 +000083static cl::opt<bool> NoLoadRelaxation(
84 "mips-constant-islands-no-load-relaxation",
85 cl::init(false),
86 cl::desc("Don't relax loads to long loads - for testing purposes"),
87 cl::Hidden);
88
Reed Kotler0d409e22013-11-28 00:56:37 +000089static unsigned int branchTargetOperand(MachineInstr *MI) {
90 switch (MI->getOpcode()) {
91 case Mips::Bimm16:
92 case Mips::BimmX16:
93 case Mips::Bteqz16:
94 case Mips::BteqzX16:
95 case Mips::Btnez16:
96 case Mips::BtnezX16:
Reed Kotlerad450f22013-11-29 22:32:56 +000097 case Mips::JalB16:
Reed Kotler0d409e22013-11-28 00:56:37 +000098 return 0;
99 case Mips::BeqzRxImm16:
100 case Mips::BeqzRxImmX16:
101 case Mips::BnezRxImm16:
102 case Mips::BnezRxImmX16:
103 return 1;
104 }
105 llvm_unreachable("Unknown branch type");
106}
107
108static unsigned int longformBranchOpcode(unsigned int Opcode) {
109 switch (Opcode) {
110 case Mips::Bimm16:
111 case Mips::BimmX16:
112 return Mips::BimmX16;
113 case Mips::Bteqz16:
114 case Mips::BteqzX16:
115 return Mips::BteqzX16;
116 case Mips::Btnez16:
117 case Mips::BtnezX16:
118 return Mips::BtnezX16;
Reed Kotlerad450f22013-11-29 22:32:56 +0000119 case Mips::JalB16:
120 return Mips::JalB16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000121 case Mips::BeqzRxImm16:
122 case Mips::BeqzRxImmX16:
123 return Mips::BeqzRxImmX16;
124 case Mips::BnezRxImm16:
125 case Mips::BnezRxImmX16:
126 return Mips::BnezRxImmX16;
127 }
128 llvm_unreachable("Unknown branch type");
129}
130
Reed Kotler0d409e22013-11-28 00:56:37 +0000131// FIXME: need to go through this whole constant islands port and check the math
132// for branch ranges and clean this up and make some functions to calculate things
133// that are done many times identically.
134// Need to refactor some of the code to call this routine.
Reed Kotler0d409e22013-11-28 00:56:37 +0000135static unsigned int branchMaxOffsets(unsigned int Opcode) {
136 unsigned Bits, Scale;
137 switch (Opcode) {
138 case Mips::Bimm16:
139 Bits = 11;
140 Scale = 2;
141 break;
142 case Mips::BimmX16:
143 Bits = 16;
144 Scale = 2;
145 break;
146 case Mips::BeqzRxImm16:
147 Bits = 8;
148 Scale = 2;
149 break;
150 case Mips::BeqzRxImmX16:
151 Bits = 16;
152 Scale = 2;
153 break;
154 case Mips::BnezRxImm16:
155 Bits = 8;
156 Scale = 2;
157 break;
158 case Mips::BnezRxImmX16:
159 Bits = 16;
160 Scale = 2;
161 break;
162 case Mips::Bteqz16:
163 Bits = 8;
164 Scale = 2;
165 break;
166 case Mips::BteqzX16:
167 Bits = 16;
168 Scale = 2;
169 break;
170 case Mips::Btnez16:
171 Bits = 8;
172 Scale = 2;
173 break;
174 case Mips::BtnezX16:
175 Bits = 16;
176 Scale = 2;
177 break;
178 default:
179 llvm_unreachable("Unknown branch type");
180 }
181 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
182 return MaxOffs;
183}
Reed Kotler0f007fc2013-11-05 08:14:14 +0000184
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000185namespace {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000186
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000187 using Iter = MachineBasicBlock::iterator;
188 using ReverseIter = MachineBasicBlock::reverse_iterator;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000189
Reed Kotler0f007fc2013-11-05 08:14:14 +0000190 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
191 /// requires constant pool entries to be scattered among the instructions
192 /// inside a function. To do this, it completely ignores the normal LLVM
193 /// constant pool; instead, it places constants wherever it feels like with
194 /// special instructions.
195 ///
196 /// The terminology used in this pass includes:
197 /// Islands - Clumps of constants placed in the function.
198 /// Water - Potential places where an island could be formed.
199 /// CPE - A constant pool entry that has been placed somewhere, which
200 /// tracks a list of users.
201
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000202 class MipsConstantIslands : public MachineFunctionPass {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000203 /// BasicBlockInfo - Information about the offset and size of a single
204 /// basic block.
205 struct BasicBlockInfo {
206 /// Offset - Distance from the beginning of the function to the beginning
207 /// of this basic block.
208 ///
209 /// Offsets are computed assuming worst case padding before an aligned
210 /// block. This means that subtracting basic block offsets always gives a
211 /// conservative estimate of the real distance which may be smaller.
212 ///
213 /// Because worst case padding is used, the computed offset of an aligned
214 /// block may not actually be aligned.
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000215 unsigned Offset = 0;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000216
217 /// Size - Size of the basic block in bytes. If the block contains
218 /// inline assembly, this is a worst case estimate.
219 ///
220 /// The size does not include any alignment padding whether from the
221 /// beginning of the block, or from an aligned jump table at the end.
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000222 unsigned Size = 0;
223
224 BasicBlockInfo() = default;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000225
Reed Kotler7ded5b62013-11-05 23:36:58 +0000226 // FIXME: ignore LogAlign for this patch
227 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000228 unsigned postOffset(unsigned LogAlign = 0) const {
229 unsigned PO = Offset + Size;
230 return PO;
231 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000232 };
233
234 std::vector<BasicBlockInfo> BBInfo;
235
236 /// WaterList - A sorted list of basic blocks where islands could be placed
237 /// (i.e. blocks that don't fall through to the following block, due
238 /// to a return, unreachable, or unconditional branch).
239 std::vector<MachineBasicBlock*> WaterList;
240
241 /// NewWaterList - The subset of WaterList that was created since the
242 /// previous iteration by inserting unconditional branches.
243 SmallSet<MachineBasicBlock*, 4> NewWaterList;
244
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000245 using water_iterator = std::vector<MachineBasicBlock *>::iterator;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000246
247 /// CPUser - One user of a constant pool, keeping the machine instruction
248 /// pointer, the constant pool being referenced, and the max displacement
249 /// allowed from the instruction to the CP. The HighWaterMark records the
250 /// highest basic block where a new CPEntry can be placed. To ensure this
251 /// pass terminates, the CP entries are initially placed at the end of the
252 /// function and then move monotonically to lower addresses. The
253 /// exception to this rule is when the current CP entry for a particular
254 /// CPUser is out of range, but there is another CP entry for the same
255 /// constant value in range. We want to use the existing in-range CP
256 /// entry, but if it later moves out of range, the search for new water
257 /// should resume where it left off. The HighWaterMark is used to record
258 /// that point.
259 struct CPUser {
260 MachineInstr *MI;
261 MachineInstr *CPEMI;
262 MachineBasicBlock *HighWaterMark;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000263
Reed Kotler0f007fc2013-11-05 08:14:14 +0000264 private:
265 unsigned MaxDisp;
266 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
267 // with different displacements
268 unsigned LongFormOpcode;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000269
Reed Kotler0f007fc2013-11-05 08:14:14 +0000270 public:
271 bool NegOk;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000272
Reed Kotler0f007fc2013-11-05 08:14:14 +0000273 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000274 bool neg,
Reed Kotler0f007fc2013-11-05 08:14:14 +0000275 unsigned longformmaxdisp, unsigned longformopcode)
276 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
277 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
Reed Kotler7ded5b62013-11-05 23:36:58 +0000278 NegOk(neg){
Reed Kotler0f007fc2013-11-05 08:14:14 +0000279 HighWaterMark = CPEMI->getParent();
280 }
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000281
Reed Kotler0f007fc2013-11-05 08:14:14 +0000282 /// getMaxDisp - Returns the maximum displacement supported by MI.
Reed Kotler0f007fc2013-11-05 08:14:14 +0000283 unsigned getMaxDisp() const {
284 unsigned xMaxDisp = ConstantIslandsSmallOffset?
285 ConstantIslandsSmallOffset: MaxDisp;
Reed Kotler7ded5b62013-11-05 23:36:58 +0000286 return xMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000287 }
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000288
Reed Kotler45c59272013-11-10 00:09:26 +0000289 void setMaxDisp(unsigned val) {
290 MaxDisp = val;
291 }
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000292
Reed Kotler0f007fc2013-11-05 08:14:14 +0000293 unsigned getLongFormMaxDisp() const {
Reed Kotler7ded5b62013-11-05 23:36:58 +0000294 return LongFormMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000295 }
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000296
Reed Kotler0f007fc2013-11-05 08:14:14 +0000297 unsigned getLongFormOpcode() const {
298 return LongFormOpcode;
299 }
300 };
301
302 /// CPUsers - Keep track of all of the machine instructions that use various
303 /// constant pools and their max displacement.
304 std::vector<CPUser> CPUsers;
Reed Kotler91ae9822013-10-27 21:57:36 +0000305
306 /// CPEntry - One per constant pool entry, keeping the machine instruction
307 /// pointer, the constpool index, and the number of CPUser's which
308 /// reference this entry.
309 struct CPEntry {
310 MachineInstr *CPEMI;
311 unsigned CPI;
312 unsigned RefCount;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000313
Reed Kotler91ae9822013-10-27 21:57:36 +0000314 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
315 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
316 };
317
318 /// CPEntries - Keep track of all of the constant pool entry machine
319 /// instructions. For each original constpool index (i.e. those that
320 /// existed upon entry to this pass), it keeps a vector of entries.
321 /// Original elements are cloned as we go along; the clones are
322 /// put in the vector of the original element, but have distinct CPIs.
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000323 std::vector<std::vector<CPEntry>> CPEntries;
Reed Kotler91ae9822013-10-27 21:57:36 +0000324
Reed Kotler0f007fc2013-11-05 08:14:14 +0000325 /// ImmBranch - One per immediate branch, keeping the machine instruction
326 /// pointer, conditional or unconditional, the max displacement,
327 /// and (if isCond is true) the corresponding unconditional branch
328 /// opcode.
329 struct ImmBranch {
330 MachineInstr *MI;
331 unsigned MaxDisp : 31;
332 bool isCond : 1;
333 int UncondBr;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000334
Reed Kotler0f007fc2013-11-05 08:14:14 +0000335 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
336 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
337 };
338
339 /// ImmBranches - Keep track of all the immediate branch instructions.
340 ///
341 std::vector<ImmBranch> ImmBranches;
342
343 /// HasFarJump - True if any far jump instruction has been emitted during
344 /// the branch fix up pass.
345 bool HasFarJump;
346
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000347 const MipsSubtarget *STI = nullptr;
Reed Kotler5c8ae092013-11-13 04:37:52 +0000348 const Mips16InstrInfo *TII;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000349 MipsFunctionInfo *MFI;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000350 MachineFunction *MF = nullptr;
351 MachineConstantPool *MCP = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000352
353 unsigned PICLabelUId;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000354 bool PrescannedForConstants = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000355
356 void initPICLabelUId(unsigned UId) {
357 PICLabelUId = UId;
358 }
359
Reed Kotler0f007fc2013-11-05 08:14:14 +0000360 unsigned createPICLabelUId() {
361 return PICLabelUId++;
362 }
363
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000364 public:
365 static char ID;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000366
367 MipsConstantIslands() : MachineFunctionPass(ID) {}
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000368
Mehdi Amini117296c2016-10-01 02:56:57 +0000369 StringRef getPassName() const override { return "Mips Constant Islands"; }
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000370
Craig Topper56c590a2014-04-29 07:58:02 +0000371 bool runOnMachineFunction(MachineFunction &F) override;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000372
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000373 MachineFunctionProperties getRequiredProperties() const override {
374 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000375 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000376 }
377
Reed Kotler91ae9822013-10-27 21:57:36 +0000378 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000379 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000380 unsigned getCPELogAlign(const MachineInstr &CPEMI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000381 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
382 unsigned getOffsetOf(MachineInstr *MI) const;
383 unsigned getUserOffset(CPUser&) const;
384 void dumpBBs();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000385
386 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000387 unsigned Disp, bool NegativeOK);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000388 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
389 const CPUser &U);
390
Reed Kotler0f007fc2013-11-05 08:14:14 +0000391 void computeBlockSize(MachineBasicBlock *MBB);
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000392 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000393 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
394 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
395 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
396 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
397 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
398 bool findAvailableWater(CPUser&U, unsigned UserOffset,
399 water_iterator &WaterIter);
400 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
401 MachineBasicBlock *&NewMBB);
402 bool handleConstantPoolUser(unsigned CPUserIndex);
403 void removeDeadCPEMI(MachineInstr *CPEMI);
404 bool removeUnusedCPEntries();
405 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
406 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
407 bool DoDump = false);
408 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
409 CPUser &U, unsigned &Growth);
410 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
411 bool fixupImmediateBr(ImmBranch &Br);
412 bool fixupConditionalBr(ImmBranch &Br);
413 bool fixupUnconditionalBr(ImmBranch &Br);
Reed Kotler91ae9822013-10-27 21:57:36 +0000414
415 void prescanForConstants();
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000416 };
417
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000418} // end anonymous namespace
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000419
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000420char MipsConstantIslands::ID = 0;
421
Reed Kotler0f007fc2013-11-05 08:14:14 +0000422bool MipsConstantIslands::isOffsetInRange
423 (unsigned UserOffset, unsigned TrialOffset,
424 const CPUser &U) {
425 return isOffsetInRange(UserOffset, TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000426 U.getMaxDisp(), U.NegOk);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000427}
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000428
Aaron Ballman615eb472017-10-15 14:32:27 +0000429#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Reed Kotler0f007fc2013-11-05 08:14:14 +0000430/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000431LLVM_DUMP_METHOD void MipsConstantIslands::dumpBBs() {
432 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
433 const BasicBlockInfo &BBI = BBInfo[J];
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000434 dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000435 << format(" size=%#x\n", BBInfo[J].Size);
436 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000437}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000438#endif
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000439
Reed Kotler91ae9822013-10-27 21:57:36 +0000440bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
Reed Kotler1595f362013-04-09 19:46:01 +0000441 // The intention is for this to be a mips16 only pass for now
442 // FIXME:
Reed Kotler91ae9822013-10-27 21:57:36 +0000443 MF = &mf;
444 MCP = mf.getConstantPool();
Eric Christopher96e72c62015-01-29 23:27:36 +0000445 STI = &static_cast<const MipsSubtarget &>(mf.getSubtarget());
Reed Kotler91ae9822013-10-27 21:57:36 +0000446 DEBUG(dbgs() << "constant island machine function " << "\n");
Eric Christopher4e7d1e72014-07-18 23:41:32 +0000447 if (!STI->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
Reed Kotler91ae9822013-10-27 21:57:36 +0000448 return false;
449 }
Eric Christopher96e72c62015-01-29 23:27:36 +0000450 TII = (const Mips16InstrInfo *)STI->getInstrInfo();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000451 MFI = MF->getInfo<MipsFunctionInfo>();
Reed Kotler91ae9822013-10-27 21:57:36 +0000452 DEBUG(dbgs() << "constant island processing " << "\n");
453 //
454 // will need to make predermination if there is any constants we need to
455 // put in constant islands. TBD.
456 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000457 if (!PrescannedForConstants) prescanForConstants();
Reed Kotler91ae9822013-10-27 21:57:36 +0000458
Reed Kotler0f007fc2013-11-05 08:14:14 +0000459 HasFarJump = false;
Reed Kotler91ae9822013-10-27 21:57:36 +0000460 // This pass invalidates liveness information when it splits basic blocks.
461 MF->getRegInfo().invalidateLiveness();
462
463 // Renumber all of the machine basic blocks in the function, guaranteeing that
464 // the numbers agree with the position of the block in the function.
465 MF->RenumberBlocks();
466
Reed Kotler0f007fc2013-11-05 08:14:14 +0000467 bool MadeChange = false;
468
Reed Kotler91ae9822013-10-27 21:57:36 +0000469 // Perform the initial placement of the constant pool entries. To start with,
470 // we put them all at the end of the function.
471 std::vector<MachineInstr*> CPEMIs;
472 if (!MCP->isEmpty())
473 doInitialPlacement(CPEMIs);
474
Reed Kotler0f007fc2013-11-05 08:14:14 +0000475 /// The next UID to take is the first unused one.
476 initPICLabelUId(CPEMIs.size());
477
478 // Do the initial scan of the function, building up information about the
479 // sizes of each block, the location of all the water, and finding all of the
480 // constant pool users.
481 initializeFunctionInfo(CPEMIs);
482 CPEMIs.clear();
483 DEBUG(dumpBBs());
484
485 /// Remove dead constant pool entries.
486 MadeChange |= removeUnusedCPEntries();
487
488 // Iteratively place constant pool entries and fix up branches until there
489 // is no change.
490 unsigned NoCPIters = 0, NoBRIters = 0;
491 (void)NoBRIters;
492 while (true) {
493 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
494 bool CPChange = false;
495 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
496 CPChange |= handleConstantPoolUser(i);
497 if (CPChange && ++NoCPIters > 30)
498 report_fatal_error("Constant Island pass failed to converge!");
499 DEBUG(dumpBBs());
500
501 // Clear NewWaterList now. If we split a block for branches, it should
502 // appear as "new water" for the next iteration of constant pool placement.
503 NewWaterList.clear();
504
505 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
506 bool BRChange = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000507 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
508 BRChange |= fixupImmediateBr(ImmBranches[i]);
509 if (BRChange && ++NoBRIters > 30)
510 report_fatal_error("Branch Fix Up pass failed to converge!");
511 DEBUG(dumpBBs());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000512 if (!CPChange && !BRChange)
513 break;
514 MadeChange = true;
515 }
516
517 DEBUG(dbgs() << '\n'; dumpBBs());
518
519 BBInfo.clear();
520 WaterList.clear();
521 CPUsers.clear();
522 CPEntries.clear();
523 ImmBranches.clear();
524 return MadeChange;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000525}
526
Reed Kotler91ae9822013-10-27 21:57:36 +0000527/// doInitialPlacement - Perform the initial placement of the constant pool
528/// entries. To start with, we put them all at the end of the function.
529void
530MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
531 // Create the basic block to hold the CPE's.
532 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
533 MF->push_back(BB);
534
Reed Kotler91ae9822013-10-27 21:57:36 +0000535 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
536 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
537
538 // Mark the basic block as required by the const-pool.
539 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
540 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
541
542 // The function needs to be as aligned as the basic blocks. The linker may
543 // move functions around based on their alignment.
544 MF->ensureAlignment(BB->getAlignment());
545
546 // Order the entries in BB by descending alignment. That ensures correct
547 // alignment of all entries as long as BB is sufficiently aligned. Keep
548 // track of the insertion point for each alignment. We are going to bucket
549 // sort the entries as they are created.
550 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
551
552 // Add all of the constants from the constant pool to the end block, use an
553 // identity mapping of CPI's to CPE's.
554 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
555
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000556 const DataLayout &TD = MF->getDataLayout();
Reed Kotler91ae9822013-10-27 21:57:36 +0000557 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
558 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
559 assert(Size >= 4 && "Too small constant pool entry");
560 unsigned Align = CPs[i].getAlignment();
561 assert(isPowerOf2_32(Align) && "Invalid alignment");
562 // Verify that all constant pool entries are a multiple of their alignment.
563 // If not, we would have to pad them out so that instructions stay aligned.
564 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
565
566 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
567 unsigned LogAlign = Log2_32(Align);
568 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
569
570 MachineInstr *CPEMI =
571 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
572 .addImm(i).addConstantPoolIndex(i).addImm(Size);
573
574 CPEMIs.push_back(CPEMI);
575
576 // Ensure that future entries with higher alignment get inserted before
577 // CPEMI. This is bucket sort with iterators.
578 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
579 if (InsPoint[a] == InsAt)
580 InsPoint[a] = CPEMI;
581 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000582 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Reed Kotler91ae9822013-10-27 21:57:36 +0000583 ++NumCPEs;
584 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
585 << Size << ", align = " << Align <<'\n');
586 }
587 DEBUG(BB->dump());
588}
589
Reed Kotler0f007fc2013-11-05 08:14:14 +0000590/// BBHasFallthrough - Return true if the specified basic block can fallthrough
591/// into the block immediately after it.
592static bool BBHasFallthrough(MachineBasicBlock *MBB) {
593 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000594 MachineFunction::iterator MBBI = MBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000595 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000596 if (std::next(MBBI) == MBB->getParent()->end())
Reed Kotler0f007fc2013-11-05 08:14:14 +0000597 return false;
598
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000599 MachineBasicBlock *NextBB = &*std::next(MBBI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000600 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
601 E = MBB->succ_end(); I != E; ++I)
602 if (*I == NextBB)
603 return true;
604
605 return false;
606}
607
608/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
609/// look up the corresponding CPEntry.
610MipsConstantIslands::CPEntry
611*MipsConstantIslands::findConstPoolEntry(unsigned CPI,
612 const MachineInstr *CPEMI) {
613 std::vector<CPEntry> &CPEs = CPEntries[CPI];
614 // Number of entries per constpool index should be small, just do a
615 // linear search.
616 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
617 if (CPEs[i].CPEMI == CPEMI)
618 return &CPEs[i];
619 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000620 return nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000621}
622
623/// getCPELogAlign - Returns the required alignment of the constant pool entry
624/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000625unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr &CPEMI) {
626 assert(CPEMI.getOpcode() == Mips::CONSTPOOL_ENTRY);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000627
628 // Everything is 4-byte aligned unless AlignConstantIslands is set.
629 if (!AlignConstantIslands)
630 return 2;
631
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000632 unsigned CPI = CPEMI.getOperand(1).getIndex();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000633 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
634 unsigned Align = MCP->getConstants()[CPI].getAlignment();
635 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
636 return Log2_32(Align);
637}
638
639/// initializeFunctionInfo - Do the initial scan of the function, building up
640/// information about the sizes of each block, the location of all the water,
641/// and finding all of the constant pool users.
642void MipsConstantIslands::
643initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
644 BBInfo.clear();
645 BBInfo.resize(MF->getNumBlockIDs());
646
647 // First thing, compute the size of all basic blocks, and see if the function
648 // has any inline assembly in it. If so, we have to be conservative about
649 // alignment assumptions, as we don't know for sure the size of any
650 // instructions in the inline assembly.
651 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000652 computeBlockSize(&*I);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000653
Reed Kotler0f007fc2013-11-05 08:14:14 +0000654 // Compute block offsets.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000655 adjustBBOffsetsAfter(&MF->front());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000656
657 // Now go back through the instructions and build up our data structures.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000658 for (MachineBasicBlock &MBB : *MF) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000659 // If this block doesn't fall through into the next MBB, then this is
660 // 'water' that a constant pool island could be placed.
661 if (!BBHasFallthrough(&MBB))
662 WaterList.push_back(&MBB);
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000663 for (MachineInstr &MI : MBB) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000664 if (MI.isDebugInstr())
Reed Kotler0f007fc2013-11-05 08:14:14 +0000665 continue;
666
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000667 int Opc = MI.getOpcode();
668 if (MI.isBranch()) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000669 bool isCond = false;
670 unsigned Bits = 0;
671 unsigned Scale = 1;
672 int UOpc = Opc;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000673 switch (Opc) {
674 default:
Reed Kotler4b7afe52013-11-13 23:52:18 +0000675 continue; // Ignore other branches for now
676 case Mips::Bimm16:
677 Bits = 11;
678 Scale = 2;
679 isCond = false;
680 break;
681 case Mips::BimmX16:
682 Bits = 16;
683 Scale = 2;
684 isCond = false;
Reed Kotler0d409e22013-11-28 00:56:37 +0000685 break;
686 case Mips::BeqzRxImm16:
Reed Kotler59975c22013-12-03 23:42:51 +0000687 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000688 Bits = 8;
689 Scale = 2;
690 isCond = true;
691 break;
692 case Mips::BeqzRxImmX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000693 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000694 Bits = 16;
695 Scale = 2;
696 isCond = true;
697 break;
698 case Mips::BnezRxImm16:
Reed Kotler59975c22013-12-03 23:42:51 +0000699 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000700 Bits = 8;
701 Scale = 2;
702 isCond = true;
703 break;
704 case Mips::BnezRxImmX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000705 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000706 Bits = 16;
707 Scale = 2;
708 isCond = true;
709 break;
710 case Mips::Bteqz16:
Reed Kotler59975c22013-12-03 23:42:51 +0000711 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000712 Bits = 8;
713 Scale = 2;
714 isCond = true;
715 break;
716 case Mips::BteqzX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000717 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000718 Bits = 16;
719 Scale = 2;
720 isCond = true;
721 break;
722 case Mips::Btnez16:
Reed Kotler59975c22013-12-03 23:42:51 +0000723 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000724 Bits = 8;
725 Scale = 2;
726 isCond = true;
727 break;
728 case Mips::BtnezX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000729 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000730 Bits = 16;
731 Scale = 2;
732 isCond = true;
733 break;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000734 }
735 // Record this immediate branch.
736 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000737 ImmBranches.push_back(ImmBranch(&MI, MaxOffs, isCond, UOpc));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000738 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000739
740 if (Opc == Mips::CONSTPOOL_ENTRY)
741 continue;
742
Reed Kotler0f007fc2013-11-05 08:14:14 +0000743 // Scan the instructions for constant pool operands.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000744 for (unsigned op = 0, e = MI.getNumOperands(); op != e; ++op)
745 if (MI.getOperand(op).isCPI()) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000746 // We found one. The addressing mode tells us the max displacement
747 // from the PC that this instruction permits.
748
749 // Basic size info comes from the TSFlags field.
750 unsigned Bits = 0;
751 unsigned Scale = 1;
752 bool NegOk = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000753 unsigned LongFormBits = 0;
754 unsigned LongFormScale = 0;
755 unsigned LongFormOpcode = 0;
756 switch (Opc) {
757 default:
758 llvm_unreachable("Unknown addressing mode for CP reference!");
759 case Mips::LwRxPcTcp16:
760 Bits = 8;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000761 Scale = 4;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000762 LongFormOpcode = Mips::LwRxPcTcpX16;
Reed Kotler43788a22014-01-16 00:47:46 +0000763 LongFormBits = 14;
Reed Kotler45c59272013-11-10 00:09:26 +0000764 LongFormScale = 1;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000765 break;
766 case Mips::LwRxPcTcpX16:
Reed Kotler43788a22014-01-16 00:47:46 +0000767 Bits = 14;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000768 Scale = 1;
769 NegOk = true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000770 break;
771 }
772 // Remember that this is a user of a CP entry.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000773 unsigned CPI = MI.getOperand(op).getIndex();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000774 MachineInstr *CPEMI = CPEMIs[CPI];
775 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
776 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000777 CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk, LongFormMaxOffs,
778 LongFormOpcode));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000779
780 // Increment corresponding CPEntry reference count.
781 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
782 assert(CPE && "Cannot find a corresponding CPEntry!");
783 CPE->RefCount++;
784
785 // Instructions can only use one CP entry, don't bother scanning the
786 // rest of the operands.
787 break;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000788 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000789 }
790 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000791}
792
793/// computeBlockSize - Compute the size and some alignment information for MBB.
794/// This function updates BBInfo directly.
795void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
796 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
797 BBI.Size = 0;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000798
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000799 for (const MachineInstr &MI : *MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000800 BBI.Size += TII->getInstSizeInBytes(MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000801}
802
803/// getOffsetOf - Return the current offset of the specified machine instruction
804/// from the start of the function. This offset changes as stuff is moved
805/// around inside the function.
806unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
807 MachineBasicBlock *MBB = MI->getParent();
808
809 // The offset is composed of two things: the sum of the sizes of all MBB's
810 // before this instruction's block, and the offset from the start of the block
811 // it is in.
812 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
813
814 // Sum instructions before MI in MBB.
815 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
816 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000817 Offset += TII->getInstSizeInBytes(*I);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000818 }
819 return Offset;
820}
821
822/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
823/// ID.
824static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
825 const MachineBasicBlock *RHS) {
826 return LHS->getNumber() < RHS->getNumber();
827}
828
829/// updateForInsertedWaterBlock - When a block is newly inserted into the
830/// machine function, it upsets all of the block numbers. Renumber the blocks
831/// and update the arrays that parallel this numbering.
832void MipsConstantIslands::updateForInsertedWaterBlock
833 (MachineBasicBlock *NewBB) {
834 // Renumber the MBB's to keep them consecutive.
835 NewBB->getParent()->RenumberBlocks(NewBB);
836
837 // Insert an entry into BBInfo to align it properly with the (newly
838 // renumbered) block numbers.
839 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
840
841 // Next, update WaterList. Specifically, we need to add NewMBB as having
842 // available water after it.
843 water_iterator IP =
844 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
845 CompareMBBNumbers);
846 WaterList.insert(IP, NewBB);
847}
848
Reed Kotler0f007fc2013-11-05 08:14:14 +0000849unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
Reed Kotler0eb87392013-11-05 21:39:57 +0000850 return getOffsetOf(U.MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000851}
852
853/// Split the basic block containing MI into two blocks, which are joined by
854/// an unconditional branch. Update data structures and renumber blocks to
855/// account for this change and returns the newly created block.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000856MachineBasicBlock *
857MipsConstantIslands::splitBlockBeforeInstr(MachineInstr &MI) {
858 MachineBasicBlock *OrigBB = MI.getParent();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000859
860 // Create a new MBB for the code after the OrigBB.
861 MachineBasicBlock *NewBB =
862 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000863 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000864 MF->insert(MBBI, NewBB);
865
866 // Splice the instructions starting with MI over to NewBB.
867 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
868
869 // Add an unconditional branch from OrigBB to NewBB.
870 // Note the new unconditional branch is not being recorded.
871 // There doesn't seem to be meaningful DebugInfo available; this doesn't
872 // correspond to anything in the source.
Reed Kotlerf0e69682013-11-12 02:27:12 +0000873 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000874 ++NumSplit;
875
876 // Update the CFG. All succs of OrigBB are now succs of NewBB.
877 NewBB->transferSuccessors(OrigBB);
878
879 // OrigBB branches to NewBB.
880 OrigBB->addSuccessor(NewBB);
881
882 // Update internal data structures to account for the newly inserted MBB.
883 // This is almost the same as updateForInsertedWaterBlock, except that
884 // the Water goes after OrigBB, not NewBB.
885 MF->RenumberBlocks(NewBB);
886
887 // Insert an entry into BBInfo to align it properly with the (newly
888 // renumbered) block numbers.
889 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
890
891 // Next, update WaterList. Specifically, we need to add OrigMBB as having
892 // available water after it (but not if it's already there, which happens
893 // when splitting before a conditional branch that is followed by an
894 // unconditional branch - in that case we want to insert NewBB).
895 water_iterator IP =
896 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
897 CompareMBBNumbers);
898 MachineBasicBlock* WaterBB = *IP;
899 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000900 WaterList.insert(std::next(IP), NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000901 else
902 WaterList.insert(IP, OrigBB);
903 NewWaterList.insert(OrigBB);
904
905 // Figure out how large the OrigBB is. As the first half of the original
906 // block, it cannot contain a tablejump. The size includes
907 // the new jump we added. (It should be possible to do this without
908 // recounting everything, but it's very confusing, and this is rarely
909 // executed.)
910 computeBlockSize(OrigBB);
911
912 // Figure out how large the NewMBB is. As the second half of the original
913 // block, it may contain a tablejump.
914 computeBlockSize(NewBB);
915
916 // All BBOffsets following these blocks must be modified.
917 adjustBBOffsetsAfter(OrigBB);
918
919 return NewBB;
920}
921
Reed Kotler0f007fc2013-11-05 08:14:14 +0000922/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
923/// reference) is within MaxDisp of TrialOffset (a proposed location of a
924/// constant pool entry).
Reed Kotler0f007fc2013-11-05 08:14:14 +0000925bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
926 unsigned TrialOffset, unsigned MaxDisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000927 bool NegativeOK) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000928 if (UserOffset <= TrialOffset) {
929 // User before the Trial.
930 if (TrialOffset - UserOffset <= MaxDisp)
931 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000932 } else if (NegativeOK) {
933 if (UserOffset - TrialOffset <= MaxDisp)
934 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000935 }
936 return false;
937}
938
939/// isWaterInRange - Returns true if a CPE placed after the specified
940/// Water (a basic block) will be in range for the specific MI.
941///
942/// Compute how much the function will grow by inserting a CPE after Water.
943bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
944 MachineBasicBlock* Water, CPUser &U,
945 unsigned &Growth) {
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000946 unsigned CPELogAlign = getCPELogAlign(*U.CPEMI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000947 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
948 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000949 MachineFunction::const_iterator NextBlock = ++Water->getIterator();
950 if (NextBlock == MF->end()) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000951 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
952 NextBlockAlignment = 0;
953 } else {
954 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
955 NextBlockAlignment = NextBlock->getAlignment();
956 }
957 unsigned Size = U.CPEMI->getOperand(2).getImm();
958 unsigned CPEEnd = CPEOffset + Size;
959
960 // The CPE may be able to hide in the alignment padding before the next
961 // block. It may also cause more padding to be required if it is more aligned
962 // that the next block.
963 if (CPEEnd > NextBlockOffset) {
964 Growth = CPEEnd - NextBlockOffset;
965 // Compute the padding that would go at the end of the CPE to align the next
966 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +0000967 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000968
969 // If the CPE is to be inserted before the instruction, that will raise
970 // the offset of the instruction. Also account for unknown alignment padding
971 // in blocks between CPE and the user.
972 if (CPEOffset < UserOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +0000973 UserOffset += Growth;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000974 } else
975 // CPE fits in existing padding.
976 Growth = 0;
977
978 return isOffsetInRange(UserOffset, CPEOffset, U);
979}
980
981/// isCPEntryInRange - Returns true if the distance between specific MI and
982/// specific ConstPool entry instruction can fit in MI's displacement field.
983bool MipsConstantIslands::isCPEntryInRange
984 (MachineInstr *MI, unsigned UserOffset,
985 MachineInstr *CPEMI, unsigned MaxDisp,
986 bool NegOk, bool DoDump) {
987 unsigned CPEOffset = getOffsetOf(CPEMI);
988
989 if (DoDump) {
990 DEBUG({
991 unsigned Block = MI->getParent()->getNumber();
992 const BasicBlockInfo &BBI = BBInfo[Block];
993 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
994 << " max delta=" << MaxDisp
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000995 << format(" insn address=%#x", UserOffset) << " in "
996 << printMBBReference(*MI->getParent()) << ": "
Reed Kotler0f007fc2013-11-05 08:14:14 +0000997 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
998 << format("CPE address=%#x offset=%+d: ", CPEOffset,
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000999 int(CPEOffset - UserOffset));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001000 });
1001 }
1002
1003 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1004}
1005
1006#ifndef NDEBUG
1007/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1008/// unconditionally branches to its only successor.
1009static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1010 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1011 return false;
1012 MachineBasicBlock *Succ = *MBB->succ_begin();
1013 MachineBasicBlock *Pred = *MBB->pred_begin();
1014 MachineInstr *PredMI = &Pred->back();
Reed Kotlerf0e69682013-11-12 02:27:12 +00001015 if (PredMI->getOpcode() == Mips::Bimm16)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001016 return PredMI->getOperand(0).getMBB() == Succ;
1017 return false;
1018}
1019#endif
1020
1021void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1022 unsigned BBNum = BB->getNumber();
1023 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1024 // Get the offset and known bits at the end of the layout predecessor.
1025 // Include the alignment of the current block.
Reed Kotler7ded5b62013-11-05 23:36:58 +00001026 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001027 BBInfo[i].Offset = Offset;
1028 }
1029}
1030
1031/// decrementCPEReferenceCount - find the constant pool entry with index CPI
1032/// and instruction CPEMI, and decrement its refcount. If the refcount
1033/// becomes 0 remove the entry and instruction. Returns true if we removed
1034/// the entry, false if we didn't.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001035bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1036 MachineInstr *CPEMI) {
1037 // Find the old entry. Eliminate it if it is no longer used.
1038 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1039 assert(CPE && "Unexpected!");
1040 if (--CPE->RefCount == 0) {
1041 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001042 CPE->CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001043 --NumCPEs;
1044 return true;
1045 }
1046 return false;
1047}
1048
1049/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1050/// if not, see if an in-range clone of the CPE is in range, and if so,
1051/// change the data structures so the user references the clone. Returns:
1052/// 0 = no existing entry found
1053/// 1 = entry found, and there were no code insertions or deletions
1054/// 2 = entry found, and there were code insertions or deletions
1055int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1056{
1057 MachineInstr *UserMI = U.MI;
1058 MachineInstr *CPEMI = U.CPEMI;
1059
1060 // Check to see if the CPE is already in-range.
1061 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1062 true)) {
1063 DEBUG(dbgs() << "In range\n");
1064 return 1;
1065 }
1066
1067 // No. Look for previously created clones of the CPE that are in range.
1068 unsigned CPI = CPEMI->getOperand(1).getIndex();
1069 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1070 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1071 // We already tried this one
1072 if (CPEs[i].CPEMI == CPEMI)
1073 continue;
1074 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001075 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001076 continue;
1077 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1078 U.NegOk)) {
1079 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1080 << CPEs[i].CPI << "\n");
1081 // Point the CPUser node to the replacement
1082 U.CPEMI = CPEs[i].CPEMI;
1083 // Change the CPI in the instruction operand to refer to the clone.
1084 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1085 if (UserMI->getOperand(j).isCPI()) {
1086 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1087 break;
1088 }
1089 // Adjust the refcount of the clone...
1090 CPEs[i].RefCount++;
1091 // ...and the original. If we didn't remove the old entry, none of the
1092 // addresses changed, so we don't need another pass.
1093 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1094 }
1095 }
1096 return 0;
1097}
1098
1099/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1100/// This version checks if the longer form of the instruction can be used to
1101/// to satisfy things.
1102/// if not, see if an in-range clone of the CPE is in range, and if so,
1103/// change the data structures so the user references the clone. Returns:
1104/// 0 = no existing entry found
1105/// 1 = entry found, and there were no code insertions or deletions
1106/// 2 = entry found, and there were code insertions or deletions
1107int MipsConstantIslands::findLongFormInRangeCPEntry
1108 (CPUser& U, unsigned UserOffset)
1109{
1110 MachineInstr *UserMI = U.MI;
1111 MachineInstr *CPEMI = U.CPEMI;
1112
1113 // Check to see if the CPE is already in-range.
1114 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1115 U.getLongFormMaxDisp(), U.NegOk,
1116 true)) {
1117 DEBUG(dbgs() << "In range\n");
1118 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
Reed Kotler45c59272013-11-10 00:09:26 +00001119 U.setMaxDisp(U.getLongFormMaxDisp());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001120 return 2; // instruction is longer length now
1121 }
1122
1123 // No. Look for previously created clones of the CPE that are in range.
1124 unsigned CPI = CPEMI->getOperand(1).getIndex();
1125 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1126 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1127 // We already tried this one
1128 if (CPEs[i].CPEMI == CPEMI)
1129 continue;
1130 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001131 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001132 continue;
1133 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1134 U.getLongFormMaxDisp(), U.NegOk)) {
1135 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1136 << CPEs[i].CPI << "\n");
1137 // Point the CPUser node to the replacement
1138 U.CPEMI = CPEs[i].CPEMI;
1139 // Change the CPI in the instruction operand to refer to the clone.
1140 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1141 if (UserMI->getOperand(j).isCPI()) {
1142 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1143 break;
1144 }
1145 // Adjust the refcount of the clone...
1146 CPEs[i].RefCount++;
1147 // ...and the original. If we didn't remove the old entry, none of the
1148 // addresses changed, so we don't need another pass.
1149 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1150 }
1151 }
1152 return 0;
1153}
1154
1155/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1156/// the specific unconditional branch instruction.
1157static inline unsigned getUnconditionalBrDisp(int Opc) {
1158 switch (Opc) {
Reed Kotlerf0e69682013-11-12 02:27:12 +00001159 case Mips::Bimm16:
1160 return ((1<<10)-1)*2;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001161 case Mips::BimmX16:
1162 return ((1<<16)-1)*2;
1163 default:
1164 break;
1165 }
1166 return ((1<<16)-1)*2;
1167}
1168
1169/// findAvailableWater - Look for an existing entry in the WaterList in which
1170/// we can place the CPE referenced from U so it's within range of U's MI.
1171/// Returns true if found, false if not. If it returns true, WaterIter
Reed Kotler4d0313d2013-11-05 12:04:37 +00001172/// is set to the WaterList entry.
1173/// To ensure that this pass
Reed Kotler0f007fc2013-11-05 08:14:14 +00001174/// terminates, the CPE location for a particular CPUser is only allowed to
1175/// move to a lower address, so search backward from the end of the list and
1176/// prefer the first water that is in range.
1177bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1178 water_iterator &WaterIter) {
1179 if (WaterList.empty())
1180 return false;
1181
1182 unsigned BestGrowth = ~0u;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001183 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001184 --IP) {
1185 MachineBasicBlock* WaterBB = *IP;
1186 // Check if water is in range and is either at a lower address than the
1187 // current "high water mark" or a new water block that was created since
1188 // the previous iteration by inserting an unconditional branch. In the
1189 // latter case, we want to allow resetting the high water mark back to
1190 // this new water since we haven't seen it before. Inserting branches
1191 // should be relatively uncommon and when it does happen, we want to be
1192 // sure to take advantage of it for all the CPEs near that block, so that
1193 // we don't insert more branches than necessary.
1194 unsigned Growth;
1195 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1196 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1197 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1198 // This is the least amount of required padding seen so far.
1199 BestGrowth = Growth;
1200 WaterIter = IP;
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001201 DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001202 << " Growth=" << Growth << '\n');
1203
1204 // Keep looking unless it is perfect.
1205 if (BestGrowth == 0)
1206 return true;
1207 }
1208 if (IP == B)
1209 break;
1210 }
1211 return BestGrowth != ~0u;
1212}
1213
1214/// createNewWater - No existing WaterList entry will work for
1215/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1216/// block is used if in range, and the conditional branch munged so control
1217/// flow is correct. Otherwise the block is split to create a hole with an
1218/// unconditional branch around it. In either case NewMBB is set to a
1219/// block following which the new island can be inserted (the WaterList
1220/// is not adjusted).
1221void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1222 unsigned UserOffset,
1223 MachineBasicBlock *&NewMBB) {
1224 CPUser &U = CPUsers[CPUserIndex];
1225 MachineInstr *UserMI = U.MI;
1226 MachineInstr *CPEMI = U.CPEMI;
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +00001227 unsigned CPELogAlign = getCPELogAlign(*CPEMI);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001228 MachineBasicBlock *UserMBB = UserMI->getParent();
1229 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1230
1231 // If the block does not end in an unconditional branch already, and if the
Reed Kotler4d0313d2013-11-05 12:04:37 +00001232 // end of the block is within range, make new water there.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001233 if (BBHasFallthrough(UserMBB)) {
1234 // Size of branch to insert.
1235 unsigned Delta = 2;
1236 // Compute the offset where the CPE will begin.
1237 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1238
1239 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001240 DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
1241 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001242 NewMBB = &*++UserMBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001243 // Add an unconditional branch from UserMBB to fallthrough block. Record
1244 // it for branch lengthening; this new branch will not get out of range,
1245 // but if the preceding conditional branch is out of range, the targets
1246 // will be exchanged, and the altered branch may be out of range, so the
1247 // machinery has to know about it.
Reed Kotlerf0e69682013-11-12 02:27:12 +00001248 int UncondBr = Mips::Bimm16;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001249 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1250 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1251 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1252 MaxDisp, false, UncondBr));
1253 BBInfo[UserMBB->getNumber()].Size += Delta;
1254 adjustBBOffsetsAfter(UserMBB);
1255 return;
1256 }
1257 }
1258
Reed Kotler4d0313d2013-11-05 12:04:37 +00001259 // What a big block. Find a place within the block to split it.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001260
1261 // Try to split the block so it's fully aligned. Compute the latest split
1262 // point where we can add a 4-byte branch instruction, and then align to
1263 // LogAlign which is the largest possible alignment in the function.
1264 unsigned LogAlign = MF->getAlignment();
1265 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
Reed Kotler7ded5b62013-11-05 23:36:58 +00001266 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001267 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1268 BaseInsertOffset));
1269
1270 // The 4 in the following is for the unconditional branch we'll be inserting
Reed Kotler4d0313d2013-11-05 12:04:37 +00001271 // Alignment of the island is handled
Reed Kotler0f007fc2013-11-05 08:14:14 +00001272 // inside isOffsetInRange.
1273 BaseInsertOffset -= 4;
1274
1275 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +00001276 << " la=" << LogAlign << '\n');
Reed Kotler0f007fc2013-11-05 08:14:14 +00001277
1278 // This could point off the end of the block if we've already got constant
1279 // pool entries following this block; only the last one is in the water list.
1280 // Back past any possible branches (allow for a conditional and a maximally
1281 // long unconditional).
1282 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Reed Kotler7ded5b62013-11-05 23:36:58 +00001283 BaseInsertOffset = UserBBI.postOffset() - 8;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001284 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1285 }
Reed Kotler7ded5b62013-11-05 23:36:58 +00001286 unsigned EndInsertOffset = BaseInsertOffset + 4 +
Reed Kotler0f007fc2013-11-05 08:14:14 +00001287 CPEMI->getOperand(2).getImm();
1288 MachineBasicBlock::iterator MI = UserMI;
1289 ++MI;
1290 unsigned CPUIndex = CPUserIndex+1;
1291 unsigned NumCPUsers = CPUsers.size();
1292 //MachineInstr *LastIT = 0;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001293 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001294 Offset < BaseInsertOffset;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001295 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001296 assert(MI != UserMBB->end() && "Fell off end of block");
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +00001297 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001298 CPUser &U = CPUsers[CPUIndex];
1299 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1300 // Shift intertion point by one unit of alignment so it is within reach.
1301 BaseInsertOffset -= 1u << LogAlign;
1302 EndInsertOffset -= 1u << LogAlign;
1303 }
1304 // This is overly conservative, as we don't account for CPEMIs being
1305 // reused within the block, but it doesn't matter much. Also assume CPEs
1306 // are added in order with alignment padding. We may eventually be able
1307 // to pack the aligned CPEs better.
1308 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1309 CPUIndex++;
1310 }
1311 }
1312
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +00001313 NewMBB = splitBlockBeforeInstr(*--MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001314}
1315
1316/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1317/// is out-of-range. If so, pick up the constant pool value and move it some
1318/// place in-range. Return true if we changed any addresses (thus must run
1319/// another pass of branch lengthening), false otherwise.
1320bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1321 CPUser &U = CPUsers[CPUserIndex];
1322 MachineInstr *UserMI = U.MI;
1323 MachineInstr *CPEMI = U.CPEMI;
1324 unsigned CPI = CPEMI->getOperand(1).getIndex();
1325 unsigned Size = CPEMI->getOperand(2).getImm();
1326 // Compute this only once, it's expensive.
1327 unsigned UserOffset = getUserOffset(U);
1328
1329 // See if the current entry is within range, or there is a clone of it
1330 // in range.
1331 int result = findInRangeCPEntry(U, UserOffset);
1332 if (result==1) return false;
1333 else if (result==2) return true;
1334
Reed Kotler0f007fc2013-11-05 08:14:14 +00001335 // Look for water where we can place this CPE.
1336 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1337 MachineBasicBlock *NewMBB;
1338 water_iterator IP;
1339 if (findAvailableWater(U, UserOffset, IP)) {
1340 DEBUG(dbgs() << "Found water in range\n");
1341 MachineBasicBlock *WaterBB = *IP;
1342
1343 // If the original WaterList entry was "new water" on this iteration,
1344 // propagate that to the new island. This is just keeping NewWaterList
1345 // updated to match the WaterList, which will be updated below.
1346 if (NewWaterList.erase(WaterBB))
1347 NewWaterList.insert(NewIsland);
1348
1349 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001350 NewMBB = &*++WaterBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001351 } else {
1352 // No water found.
1353 // we first see if a longer form of the instrucion could have reached
1354 // the constant. in that case we won't bother to split
Reed Kotler45c59272013-11-10 00:09:26 +00001355 if (!NoLoadRelaxation) {
1356 result = findLongFormInRangeCPEntry(U, UserOffset);
1357 if (result != 0) return true;
1358 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001359 DEBUG(dbgs() << "No water found\n");
1360 createNewWater(CPUserIndex, UserOffset, NewMBB);
1361
1362 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1363 // called while handling branches so that the water will be seen on the
1364 // next iteration for constant pools, but in this context, we don't want
1365 // it. Check for this so it will be removed from the WaterList.
1366 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001367 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
Eugene Zelenkodde94e42017-01-30 23:21:32 +00001368 IP = llvm::find(WaterList, WaterBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001369 if (IP != WaterList.end())
1370 NewWaterList.erase(WaterBB);
1371
1372 // We are adding new water. Update NewWaterList.
1373 NewWaterList.insert(NewIsland);
1374 }
1375
1376 // Remove the original WaterList entry; we want subsequent insertions in
1377 // this vicinity to go after the one we're about to insert. This
1378 // considerably reduces the number of times we have to move the same CPE
1379 // more than once and is also important to ensure the algorithm terminates.
1380 if (IP != WaterList.end())
1381 WaterList.erase(IP);
1382
1383 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001384 MF->insert(NewMBB->getIterator(), NewIsland);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001385
1386 // Update internal data structures to account for the newly inserted MBB.
1387 updateForInsertedWaterBlock(NewIsland);
1388
1389 // Decrement the old entry, and remove it if refcount becomes 0.
1390 decrementCPEReferenceCount(CPI, CPEMI);
1391
Reed Kotlerd3b28eb2013-11-24 02:53:09 +00001392 // No existing clone of this CPE is within range.
1393 // We will be generating a new clone. Get a UID for it.
1394 unsigned ID = createPICLabelUId();
1395
Reed Kotler0f007fc2013-11-05 08:14:14 +00001396 // Now that we have an island to add the CPE to, clone the original CPE and
1397 // add it to the island.
1398 U.HighWaterMark = NewIsland;
1399 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1400 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1401 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1402 ++NumCPEs;
1403
1404 // Mark the basic block as aligned as required by the const-pool entry.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +00001405 NewIsland->setAlignment(getCPELogAlign(*U.CPEMI));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001406
1407 // Increase the size of the island block to account for the new entry.
1408 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001409 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001410
1411 // Finally, change the CPI in the instruction operand to be ID.
1412 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1413 if (UserMI->getOperand(i).isCPI()) {
1414 UserMI->getOperand(i).setIndex(ID);
1415 break;
1416 }
1417
1418 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1419 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1420
1421 return true;
1422}
1423
1424/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1425/// sizes and offsets of impacted basic blocks.
1426void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1427 MachineBasicBlock *CPEBB = CPEMI->getParent();
1428 unsigned Size = CPEMI->getOperand(2).getImm();
1429 CPEMI->eraseFromParent();
1430 BBInfo[CPEBB->getNumber()].Size -= Size;
1431 // All succeeding offsets have the current size value added in, fix this.
1432 if (CPEBB->empty()) {
1433 BBInfo[CPEBB->getNumber()].Size = 0;
1434
1435 // This block no longer needs to be aligned.
1436 CPEBB->setAlignment(0);
1437 } else
1438 // Entries are sorted by descending alignment, so realign from the front.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +00001439 CPEBB->setAlignment(getCPELogAlign(*CPEBB->begin()));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001440
1441 adjustBBOffsetsAfter(CPEBB);
1442 // An island has only one predecessor BB and one successor BB. Check if
1443 // this BB's predecessor jumps directly to this BB's successor. This
1444 // shouldn't happen currently.
1445 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1446 // FIXME: remove the empty blocks after all the work is done?
1447}
1448
1449/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1450/// are zero.
1451bool MipsConstantIslands::removeUnusedCPEntries() {
1452 unsigned MadeChange = false;
1453 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1454 std::vector<CPEntry> &CPEs = CPEntries[i];
1455 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1456 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1457 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001458 CPEs[j].CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001459 MadeChange = true;
1460 }
1461 }
1462 }
1463 return MadeChange;
1464}
1465
1466/// isBBInRange - Returns true if the distance between specific MI and
1467/// specific BB can fit in MI's displacement field.
1468bool MipsConstantIslands::isBBInRange
1469 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
Eugene Zelenkodde94e42017-01-30 23:21:32 +00001470 unsigned PCAdj = 4;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001471 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1472 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1473
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001474 DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)
1475 << " from " << printMBBReference(*MI->getParent())
1476 << " max delta=" << MaxDisp << " from " << getOffsetOf(MI)
1477 << " to " << DestOffset << " offset "
1478 << int(DestOffset - BrOffset) << "\t" << *MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001479
1480 if (BrOffset <= DestOffset) {
1481 // Branch before the Dest.
1482 if (DestOffset-BrOffset <= MaxDisp)
1483 return true;
1484 } else {
1485 if (BrOffset-DestOffset <= MaxDisp)
1486 return true;
1487 }
1488 return false;
1489}
1490
1491/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1492/// away to fit in its displacement field.
1493bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1494 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001495 unsigned TargetOperand = branchTargetOperand(MI);
1496 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001497
1498 // Check to see if the DestBB is already in-range.
1499 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1500 return false;
1501
1502 if (!Br.isCond)
1503 return fixupUnconditionalBr(Br);
1504 return fixupConditionalBr(Br);
1505}
1506
1507/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1508/// too far away to fit in its displacement field. If the LR register has been
1509/// spilled in the epilogue, then we can use BL to implement a far jump.
1510/// Otherwise, add an intermediate branch instruction to a branch.
1511bool
1512MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1513 MachineInstr *MI = Br.MI;
1514 MachineBasicBlock *MBB = MI->getParent();
Reed Kotler2fc05be2013-11-21 05:13:23 +00001515 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001516 // Use BL to implement far jump.
Reed Kotler2fc05be2013-11-21 05:13:23 +00001517 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1518 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1519 Br.MaxDisp = BimmX16MaxDisp;
1520 MI->setDesc(TII->get(Mips::BimmX16));
1521 }
1522 else {
1523 // need to give the math a more careful look here
1524 // this is really a segment address and not
1525 // a PC relative address. FIXME. But I think that
1526 // just reducing the bits by 1 as I've done is correct.
1527 // The basic block we are branching too much be longword aligned.
1528 // we know that RA is saved because we always save it right now.
1529 // this requirement will be relaxed later but we also have an alternate
1530 // way to implement this that I will implement that does not need jal.
1531 // We should have a way to back out this alignment restriction if we "can" later.
1532 // but it is not harmful.
1533 //
1534 DestBB->setAlignment(2);
1535 Br.MaxDisp = ((1<<24)-1) * 2;
Reed Kotlerad450f22013-11-29 22:32:56 +00001536 MI->setDesc(TII->get(Mips::JalB16));
Reed Kotler2fc05be2013-11-21 05:13:23 +00001537 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001538 BBInfo[MBB->getNumber()].Size += 2;
1539 adjustBBOffsetsAfter(MBB);
1540 HasFarJump = true;
1541 ++NumUBrFixed;
1542
1543 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1544
1545 return true;
1546}
1547
1548/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1549/// far away to fit in its displacement field. It is converted to an inverse
1550/// conditional branch + an unconditional branch to the destination.
1551bool
1552MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1553 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001554 unsigned TargetOperand = branchTargetOperand(MI);
1555 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1556 unsigned Opcode = MI->getOpcode();
1557 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1558 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1559
1560 // Check to see if the DestBB is already in-range.
1561 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1562 Br.MaxDisp = LongFormMaxOff;
1563 MI->setDesc(TII->get(LongFormOpcode));
1564 return true;
1565 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001566
1567 // Add an unconditional branch to the destination and invert the branch
1568 // condition to jump over it:
Reed Kotlerad450f22013-11-29 22:32:56 +00001569 // bteqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001570 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001571 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001572 // b L1
1573 // L2:
Reed Kotler0f007fc2013-11-05 08:14:14 +00001574
1575 // If the branch is at the end of its MBB and that has a fall-through block,
1576 // direct the updated conditional branch to the fall-through block. Otherwise,
1577 // split the MBB before the next instruction.
1578 MachineBasicBlock *MBB = MI->getParent();
1579 MachineInstr *BMI = &MBB->back();
1580 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Reed Kotler47f3c64a2013-12-19 00:43:08 +00001581 unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
Reed Kotlerad450f22013-11-29 22:32:56 +00001582
Reed Kotler0f007fc2013-11-05 08:14:14 +00001583 ++NumCBrFixed;
1584 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001585 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Daniel Sandersf9d8b8c2016-05-06 13:23:51 +00001586 BMI->isUnconditionalBranch()) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001587 // Last MI in the BB is an unconditional branch. Can we simply invert the
1588 // condition and swap destinations:
Reed Kotlerad450f22013-11-29 22:32:56 +00001589 // beqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001590 // b L2
1591 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001592 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001593 // b L1
Reed Kotlerad450f22013-11-29 22:32:56 +00001594 unsigned BMITargetOperand = branchTargetOperand(BMI);
1595 MachineBasicBlock *NewDest =
1596 BMI->getOperand(BMITargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001597 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1598 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1599 << *BMI);
Reed Kotler59975c22013-12-03 23:42:51 +00001600 MI->setDesc(TII->get(OppositeBranchOpcode));
Reed Kotlerad450f22013-11-29 22:32:56 +00001601 BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1602 MI->getOperand(TargetOperand).setMBB(NewDest);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001603 return true;
1604 }
1605 }
1606 }
1607
1608 if (NeedSplit) {
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +00001609 splitBlockBeforeInstr(*MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001610 // No need for the branch to the next block. We're adding an unconditional
1611 // branch to the destination.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001612 int delta = TII->getInstSizeInBytes(MBB->back());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001613 BBInfo[MBB->getNumber()].Size -= delta;
1614 MBB->back().eraseFromParent();
1615 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1616 }
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001617 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001618
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001619 DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB)
1620 << " also invert condition and change dest. to "
1621 << printMBBReference(*NextBB) << "\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001622
1623 // Insert a new conditional branch and a new unconditional branch.
1624 // Also update the ImmBranch as well as adding a new entry for the new branch.
Reed Kotler59975c22013-12-03 23:42:51 +00001625 if (MI->getNumExplicitOperands() == 2) {
1626 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1627 .addReg(MI->getOperand(0).getReg())
1628 .addMBB(NextBB);
Reed Kotler47f3c64a2013-12-19 00:43:08 +00001629 } else {
1630 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1631 .addMBB(NextBB);
Reed Kotler59975c22013-12-03 23:42:51 +00001632 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001633 Br.MI = &MBB->back();
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001634 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001635 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001636 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001637 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1638 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1639
1640 // Remove the old conditional branch. It may or may not still be in MBB.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001641 BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001642 MI->eraseFromParent();
1643 adjustBBOffsetsAfter(MBB);
1644 return true;
1645}
1646
Reed Kotler91ae9822013-10-27 21:57:36 +00001647void MipsConstantIslands::prescanForConstants() {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001648 unsigned J = 0;
1649 (void)J;
Reed Kotler91ae9822013-10-27 21:57:36 +00001650 for (MachineFunction::iterator B =
1651 MF->begin(), E = MF->end(); B != E; ++B) {
1652 for (MachineBasicBlock::instr_iterator I =
1653 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1654 switch(I->getDesc().getOpcode()) {
1655 case Mips::LwConstant32: {
Reed Kotlera787aa22013-11-24 06:18:50 +00001656 PrescannedForConstants = true;
Reed Kotler91ae9822013-10-27 21:57:36 +00001657 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1658 J = I->getNumOperands();
Eugene Zelenkodde94e42017-01-30 23:21:32 +00001659 DEBUG(dbgs() << "num operands " << J << "\n");
Reed Kotler91ae9822013-10-27 21:57:36 +00001660 MachineOperand& Literal = I->getOperand(1);
1661 if (Literal.isImm()) {
1662 int64_t V = Literal.getImm();
Eugene Zelenkodde94e42017-01-30 23:21:32 +00001663 DEBUG(dbgs() << "literal " << V << "\n");
Reed Kotler91ae9822013-10-27 21:57:36 +00001664 Type *Int32Ty =
Matthias Braunf1caa282017-12-15 22:22:58 +00001665 Type::getInt32Ty(MF->getFunction().getContext());
Reed Kotler91ae9822013-10-27 21:57:36 +00001666 const Constant *C = ConstantInt::get(Int32Ty, V);
1667 unsigned index = MCP->getConstantPoolIndex(C, 4);
1668 I->getOperand(2).ChangeToImmediate(index);
1669 DEBUG(dbgs() << "constant island constant " << *I << "\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001670 I->setDesc(TII->get(Mips::LwRxPcTcp16));
Reed Kotler91ae9822013-10-27 21:57:36 +00001671 I->RemoveOperand(1);
1672 I->RemoveOperand(1);
1673 I->addOperand(MachineOperand::CreateCPI(index, 0));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001674 I->addOperand(MachineOperand::CreateImm(4));
Reed Kotler91ae9822013-10-27 21:57:36 +00001675 }
1676 break;
1677 }
1678 default:
1679 break;
1680 }
1681 }
1682 }
1683}
Eugene Zelenkodde94e42017-01-30 23:21:32 +00001684
1685/// Returns a pass that converts branches to long branches.
1686FunctionPass *llvm::createMipsConstantIslandPass() {
1687 return new MipsConstantIslands();
1688}