blob: 4cd64c672393ae5a675aed2cb6bef4b9bcddb033 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Reed Kotlerbb3094a2013-02-27 03:33:58 +00006//
7//===----------------------------------------------------------------------===//
8//
Reed Kotlerbb3094a2013-02-27 03:33:58 +00009// This pass is used to make Pc relative loads of constants.
Fangrui Songf78650a2018-07-30 19:41:25 +000010// For now, only Mips16 will use this.
Reed Kotlerbb3094a2013-02-27 03:33:58 +000011//
12// Loading constants inline is expensive on Mips16 and it's in general better
13// to place the constant nearby in code space and then it can be loaded with a
14// simple 16 bit load instruction.
15//
16// The constants can be not just numbers but addresses of functions and labels.
17// This can be particularly helpful in static relocation mode for embedded
Alp Tokerf907b892013-12-05 05:44:44 +000018// non-linux targets.
Reed Kotlerbb3094a2013-02-27 03:33:58 +000019//
Eugene Zelenkodde94e42017-01-30 23:21:32 +000020//===----------------------------------------------------------------------===//
Reed Kotlerbb3094a2013-02-27 03:33:58 +000021
Reed Kotlerbb3094a2013-02-27 03:33:58 +000022#include "Mips.h"
Reed Kotler5c8ae092013-11-13 04:37:52 +000023#include "Mips16InstrInfo.h"
Reed Kotler0f007fc2013-11-05 08:14:14 +000024#include "MipsMachineFunction.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000025#include "MipsSubtarget.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000026#include "llvm/ADT/STLExtras.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000027#include "llvm/ADT/SmallSet.h"
28#include "llvm/ADT/SmallVector.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000029#include "llvm/ADT/Statistic.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000030#include "llvm/ADT/StringRef.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000031#include "llvm/CodeGen/MachineBasicBlock.h"
Eric Christopher79cc1e32014-09-02 22:28:02 +000032#include "llvm/CodeGen/MachineConstantPool.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000033#include "llvm/CodeGen/MachineFunction.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000035#include "llvm/CodeGen/MachineInstr.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000036#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000037#include "llvm/CodeGen/MachineOperand.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000038#include "llvm/CodeGen/MachineRegisterInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000039#include "llvm/Config/llvm-config.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000040#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
42#include "llvm/IR/DebugLoc.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000043#include "llvm/IR/Function.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000044#include "llvm/IR/Type.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000045#include "llvm/Support/CommandLine.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000046#include "llvm/Support/Compiler.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000047#include "llvm/Support/Debug.h"
Eugene Zelenkodde94e42017-01-30 23:21:32 +000048#include "llvm/Support/ErrorHandling.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000049#include "llvm/Support/Format.h"
Reed Kotlerbb3094a2013-02-27 03:33:58 +000050#include "llvm/Support/MathExtras.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000051#include "llvm/Support/raw_ostream.h"
Reed Kotler91ae9822013-10-27 21:57:36 +000052#include <algorithm>
Eugene Zelenkodde94e42017-01-30 23:21:32 +000053#include <cassert>
54#include <cstdint>
55#include <iterator>
Eugene Zelenkodde94e42017-01-30 23:21:32 +000056#include <vector>
Reed Kotlerbb3094a2013-02-27 03:33:58 +000057
58using namespace llvm;
59
Chandler Carruth84e68b22014-04-22 02:41:26 +000060#define DEBUG_TYPE "mips-constant-islands"
61
Reed Kotler91ae9822013-10-27 21:57:36 +000062STATISTIC(NumCPEs, "Number of constpool entries");
Reed Kotler0f007fc2013-11-05 08:14:14 +000063STATISTIC(NumSplit, "Number of uncond branches inserted");
64STATISTIC(NumCBrFixed, "Number of cond branches fixed");
65STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
Reed Kotler91ae9822013-10-27 21:57:36 +000066
67// FIXME: This option should be removed once it has received sufficient testing.
68static cl::opt<bool>
69AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
70 cl::desc("Align constant islands in code"));
71
Reed Kotler0f007fc2013-11-05 08:14:14 +000072// Rather than do make check tests with huge amounts of code, we force
73// the test to use this amount.
Reed Kotler0f007fc2013-11-05 08:14:14 +000074static cl::opt<int> ConstantIslandsSmallOffset(
75 "mips-constant-islands-small-offset",
76 cl::init(0),
77 cl::desc("Make small offsets be this amount for testing purposes"),
78 cl::Hidden);
79
Reed Kotler45c59272013-11-10 00:09:26 +000080// For testing purposes we tell it to not use relaxed load forms so that it
81// will split blocks.
Reed Kotler45c59272013-11-10 00:09:26 +000082static cl::opt<bool> NoLoadRelaxation(
83 "mips-constant-islands-no-load-relaxation",
84 cl::init(false),
85 cl::desc("Don't relax loads to long loads - for testing purposes"),
86 cl::Hidden);
87
Reed Kotler0d409e22013-11-28 00:56:37 +000088static unsigned int branchTargetOperand(MachineInstr *MI) {
89 switch (MI->getOpcode()) {
90 case Mips::Bimm16:
91 case Mips::BimmX16:
92 case Mips::Bteqz16:
93 case Mips::BteqzX16:
94 case Mips::Btnez16:
95 case Mips::BtnezX16:
Reed Kotlerad450f22013-11-29 22:32:56 +000096 case Mips::JalB16:
Reed Kotler0d409e22013-11-28 00:56:37 +000097 return 0;
98 case Mips::BeqzRxImm16:
99 case Mips::BeqzRxImmX16:
100 case Mips::BnezRxImm16:
101 case Mips::BnezRxImmX16:
102 return 1;
103 }
104 llvm_unreachable("Unknown branch type");
105}
106
107static unsigned int longformBranchOpcode(unsigned int Opcode) {
108 switch (Opcode) {
109 case Mips::Bimm16:
110 case Mips::BimmX16:
111 return Mips::BimmX16;
112 case Mips::Bteqz16:
113 case Mips::BteqzX16:
114 return Mips::BteqzX16;
115 case Mips::Btnez16:
116 case Mips::BtnezX16:
117 return Mips::BtnezX16;
Reed Kotlerad450f22013-11-29 22:32:56 +0000118 case Mips::JalB16:
119 return Mips::JalB16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000120 case Mips::BeqzRxImm16:
121 case Mips::BeqzRxImmX16:
122 return Mips::BeqzRxImmX16;
123 case Mips::BnezRxImm16:
124 case Mips::BnezRxImmX16:
125 return Mips::BnezRxImmX16;
126 }
127 llvm_unreachable("Unknown branch type");
128}
129
Reed Kotler0d409e22013-11-28 00:56:37 +0000130// FIXME: need to go through this whole constant islands port and check the math
131// for branch ranges and clean this up and make some functions to calculate things
132// that are done many times identically.
133// Need to refactor some of the code to call this routine.
Reed Kotler0d409e22013-11-28 00:56:37 +0000134static unsigned int branchMaxOffsets(unsigned int Opcode) {
135 unsigned Bits, Scale;
136 switch (Opcode) {
137 case Mips::Bimm16:
138 Bits = 11;
139 Scale = 2;
140 break;
141 case Mips::BimmX16:
142 Bits = 16;
143 Scale = 2;
144 break;
145 case Mips::BeqzRxImm16:
146 Bits = 8;
147 Scale = 2;
148 break;
149 case Mips::BeqzRxImmX16:
150 Bits = 16;
151 Scale = 2;
152 break;
153 case Mips::BnezRxImm16:
154 Bits = 8;
155 Scale = 2;
156 break;
157 case Mips::BnezRxImmX16:
158 Bits = 16;
159 Scale = 2;
160 break;
161 case Mips::Bteqz16:
162 Bits = 8;
163 Scale = 2;
164 break;
165 case Mips::BteqzX16:
166 Bits = 16;
167 Scale = 2;
168 break;
169 case Mips::Btnez16:
170 Bits = 8;
171 Scale = 2;
172 break;
173 case Mips::BtnezX16:
174 Bits = 16;
175 Scale = 2;
176 break;
177 default:
178 llvm_unreachable("Unknown branch type");
179 }
180 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
181 return MaxOffs;
182}
Reed Kotler0f007fc2013-11-05 08:14:14 +0000183
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000184namespace {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000185
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000186 using Iter = MachineBasicBlock::iterator;
187 using ReverseIter = MachineBasicBlock::reverse_iterator;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000188
Reed Kotler0f007fc2013-11-05 08:14:14 +0000189 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
190 /// requires constant pool entries to be scattered among the instructions
191 /// inside a function. To do this, it completely ignores the normal LLVM
192 /// constant pool; instead, it places constants wherever it feels like with
193 /// special instructions.
194 ///
195 /// The terminology used in this pass includes:
196 /// Islands - Clumps of constants placed in the function.
197 /// Water - Potential places where an island could be formed.
198 /// CPE - A constant pool entry that has been placed somewhere, which
199 /// tracks a list of users.
200
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000201 class MipsConstantIslands : public MachineFunctionPass {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000202 /// BasicBlockInfo - Information about the offset and size of a single
203 /// basic block.
204 struct BasicBlockInfo {
205 /// Offset - Distance from the beginning of the function to the beginning
206 /// of this basic block.
207 ///
208 /// Offsets are computed assuming worst case padding before an aligned
209 /// block. This means that subtracting basic block offsets always gives a
210 /// conservative estimate of the real distance which may be smaller.
211 ///
212 /// Because worst case padding is used, the computed offset of an aligned
213 /// block may not actually be aligned.
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000214 unsigned Offset = 0;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000215
216 /// Size - Size of the basic block in bytes. If the block contains
217 /// inline assembly, this is a worst case estimate.
218 ///
219 /// The size does not include any alignment padding whether from the
220 /// beginning of the block, or from an aligned jump table at the end.
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000221 unsigned Size = 0;
222
223 BasicBlockInfo() = default;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000224
Reed Kotler7ded5b62013-11-05 23:36:58 +0000225 // FIXME: ignore LogAlign for this patch
226 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000227 unsigned postOffset(unsigned LogAlign = 0) const {
228 unsigned PO = Offset + Size;
229 return PO;
230 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000231 };
232
233 std::vector<BasicBlockInfo> BBInfo;
234
235 /// WaterList - A sorted list of basic blocks where islands could be placed
236 /// (i.e. blocks that don't fall through to the following block, due
237 /// to a return, unreachable, or unconditional branch).
238 std::vector<MachineBasicBlock*> WaterList;
239
240 /// NewWaterList - The subset of WaterList that was created since the
241 /// previous iteration by inserting unconditional branches.
242 SmallSet<MachineBasicBlock*, 4> NewWaterList;
243
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000244 using water_iterator = std::vector<MachineBasicBlock *>::iterator;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000245
246 /// CPUser - One user of a constant pool, keeping the machine instruction
247 /// pointer, the constant pool being referenced, and the max displacement
248 /// allowed from the instruction to the CP. The HighWaterMark records the
249 /// highest basic block where a new CPEntry can be placed. To ensure this
250 /// pass terminates, the CP entries are initially placed at the end of the
251 /// function and then move monotonically to lower addresses. The
252 /// exception to this rule is when the current CP entry for a particular
253 /// CPUser is out of range, but there is another CP entry for the same
254 /// constant value in range. We want to use the existing in-range CP
255 /// entry, but if it later moves out of range, the search for new water
256 /// should resume where it left off. The HighWaterMark is used to record
257 /// that point.
258 struct CPUser {
259 MachineInstr *MI;
260 MachineInstr *CPEMI;
261 MachineBasicBlock *HighWaterMark;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000262
Reed Kotler0f007fc2013-11-05 08:14:14 +0000263 private:
264 unsigned MaxDisp;
265 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
266 // with different displacements
267 unsigned LongFormOpcode;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000268
Reed Kotler0f007fc2013-11-05 08:14:14 +0000269 public:
270 bool NegOk;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000271
Reed Kotler0f007fc2013-11-05 08:14:14 +0000272 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000273 bool neg,
Reed Kotler0f007fc2013-11-05 08:14:14 +0000274 unsigned longformmaxdisp, unsigned longformopcode)
275 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
276 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
Reed Kotler7ded5b62013-11-05 23:36:58 +0000277 NegOk(neg){
Reed Kotler0f007fc2013-11-05 08:14:14 +0000278 HighWaterMark = CPEMI->getParent();
279 }
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000280
Reed Kotler0f007fc2013-11-05 08:14:14 +0000281 /// getMaxDisp - Returns the maximum displacement supported by MI.
Reed Kotler0f007fc2013-11-05 08:14:14 +0000282 unsigned getMaxDisp() const {
283 unsigned xMaxDisp = ConstantIslandsSmallOffset?
284 ConstantIslandsSmallOffset: MaxDisp;
Reed Kotler7ded5b62013-11-05 23:36:58 +0000285 return xMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000286 }
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000287
Reed Kotler45c59272013-11-10 00:09:26 +0000288 void setMaxDisp(unsigned val) {
289 MaxDisp = val;
290 }
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000291
Reed Kotler0f007fc2013-11-05 08:14:14 +0000292 unsigned getLongFormMaxDisp() const {
Reed Kotler7ded5b62013-11-05 23:36:58 +0000293 return LongFormMaxDisp;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000294 }
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000295
Reed Kotler0f007fc2013-11-05 08:14:14 +0000296 unsigned getLongFormOpcode() const {
297 return LongFormOpcode;
298 }
299 };
300
301 /// CPUsers - Keep track of all of the machine instructions that use various
302 /// constant pools and their max displacement.
303 std::vector<CPUser> CPUsers;
Reed Kotler91ae9822013-10-27 21:57:36 +0000304
305 /// CPEntry - One per constant pool entry, keeping the machine instruction
306 /// pointer, the constpool index, and the number of CPUser's which
307 /// reference this entry.
308 struct CPEntry {
309 MachineInstr *CPEMI;
310 unsigned CPI;
311 unsigned RefCount;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000312
Reed Kotler91ae9822013-10-27 21:57:36 +0000313 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
314 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
315 };
316
317 /// CPEntries - Keep track of all of the constant pool entry machine
318 /// instructions. For each original constpool index (i.e. those that
319 /// existed upon entry to this pass), it keeps a vector of entries.
320 /// Original elements are cloned as we go along; the clones are
321 /// put in the vector of the original element, but have distinct CPIs.
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000322 std::vector<std::vector<CPEntry>> CPEntries;
Reed Kotler91ae9822013-10-27 21:57:36 +0000323
Reed Kotler0f007fc2013-11-05 08:14:14 +0000324 /// ImmBranch - One per immediate branch, keeping the machine instruction
325 /// pointer, conditional or unconditional, the max displacement,
326 /// and (if isCond is true) the corresponding unconditional branch
327 /// opcode.
328 struct ImmBranch {
329 MachineInstr *MI;
330 unsigned MaxDisp : 31;
331 bool isCond : 1;
332 int UncondBr;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000333
Reed Kotler0f007fc2013-11-05 08:14:14 +0000334 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
335 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
336 };
337
338 /// ImmBranches - Keep track of all the immediate branch instructions.
339 ///
340 std::vector<ImmBranch> ImmBranches;
341
342 /// HasFarJump - True if any far jump instruction has been emitted during
343 /// the branch fix up pass.
344 bool HasFarJump;
345
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000346 const MipsSubtarget *STI = nullptr;
Reed Kotler5c8ae092013-11-13 04:37:52 +0000347 const Mips16InstrInfo *TII;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000348 MipsFunctionInfo *MFI;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000349 MachineFunction *MF = nullptr;
350 MachineConstantPool *MCP = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000351
352 unsigned PICLabelUId;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000353 bool PrescannedForConstants = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000354
355 void initPICLabelUId(unsigned UId) {
356 PICLabelUId = UId;
357 }
358
Reed Kotler0f007fc2013-11-05 08:14:14 +0000359 unsigned createPICLabelUId() {
360 return PICLabelUId++;
361 }
362
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000363 public:
364 static char ID;
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000365
366 MipsConstantIslands() : MachineFunctionPass(ID) {}
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000367
Mehdi Amini117296c2016-10-01 02:56:57 +0000368 StringRef getPassName() const override { return "Mips Constant Islands"; }
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000369
Craig Topper56c590a2014-04-29 07:58:02 +0000370 bool runOnMachineFunction(MachineFunction &F) override;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000371
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000372 MachineFunctionProperties getRequiredProperties() const override {
373 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000374 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000375 }
376
Reed Kotler91ae9822013-10-27 21:57:36 +0000377 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000378 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000379 unsigned getCPELogAlign(const MachineInstr &CPEMI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000380 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
381 unsigned getOffsetOf(MachineInstr *MI) const;
382 unsigned getUserOffset(CPUser&) const;
383 void dumpBBs();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000384
385 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000386 unsigned Disp, bool NegativeOK);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000387 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
388 const CPUser &U);
389
Reed Kotler0f007fc2013-11-05 08:14:14 +0000390 void computeBlockSize(MachineBasicBlock *MBB);
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000391 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000392 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
393 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
394 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
395 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
396 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
397 bool findAvailableWater(CPUser&U, unsigned UserOffset,
398 water_iterator &WaterIter);
399 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
400 MachineBasicBlock *&NewMBB);
401 bool handleConstantPoolUser(unsigned CPUserIndex);
402 void removeDeadCPEMI(MachineInstr *CPEMI);
403 bool removeUnusedCPEntries();
404 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
405 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
406 bool DoDump = false);
407 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
408 CPUser &U, unsigned &Growth);
409 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
410 bool fixupImmediateBr(ImmBranch &Br);
411 bool fixupConditionalBr(ImmBranch &Br);
412 bool fixupUnconditionalBr(ImmBranch &Br);
Reed Kotler91ae9822013-10-27 21:57:36 +0000413
414 void prescanForConstants();
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000415 };
416
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000417} // end anonymous namespace
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000418
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000419char MipsConstantIslands::ID = 0;
420
Reed Kotler0f007fc2013-11-05 08:14:14 +0000421bool MipsConstantIslands::isOffsetInRange
422 (unsigned UserOffset, unsigned TrialOffset,
423 const CPUser &U) {
424 return isOffsetInRange(UserOffset, TrialOffset,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000425 U.getMaxDisp(), U.NegOk);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000426}
Eugene Zelenkodde94e42017-01-30 23:21:32 +0000427
Aaron Ballman615eb472017-10-15 14:32:27 +0000428#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Reed Kotler0f007fc2013-11-05 08:14:14 +0000429/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000430LLVM_DUMP_METHOD void MipsConstantIslands::dumpBBs() {
431 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
432 const BasicBlockInfo &BBI = BBInfo[J];
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000433 dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000434 << format(" size=%#x\n", BBInfo[J].Size);
435 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000436}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000437#endif
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000438
Reed Kotler91ae9822013-10-27 21:57:36 +0000439bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
Reed Kotler1595f362013-04-09 19:46:01 +0000440 // The intention is for this to be a mips16 only pass for now
441 // FIXME:
Reed Kotler91ae9822013-10-27 21:57:36 +0000442 MF = &mf;
443 MCP = mf.getConstantPool();
Eric Christopher96e72c62015-01-29 23:27:36 +0000444 STI = &static_cast<const MipsSubtarget &>(mf.getSubtarget());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000445 LLVM_DEBUG(dbgs() << "constant island machine function "
446 << "\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>();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000452 LLVM_DEBUG(dbgs() << "constant island processing "
453 << "\n");
Reed Kotler91ae9822013-10-27 21:57:36 +0000454 //
455 // will need to make predermination if there is any constants we need to
456 // put in constant islands. TBD.
457 //
Reed Kotler0f007fc2013-11-05 08:14:14 +0000458 if (!PrescannedForConstants) prescanForConstants();
Reed Kotler91ae9822013-10-27 21:57:36 +0000459
Reed Kotler0f007fc2013-11-05 08:14:14 +0000460 HasFarJump = false;
Reed Kotler91ae9822013-10-27 21:57:36 +0000461 // This pass invalidates liveness information when it splits basic blocks.
462 MF->getRegInfo().invalidateLiveness();
463
464 // Renumber all of the machine basic blocks in the function, guaranteeing that
465 // the numbers agree with the position of the block in the function.
466 MF->RenumberBlocks();
467
Reed Kotler0f007fc2013-11-05 08:14:14 +0000468 bool MadeChange = false;
469
Reed Kotler91ae9822013-10-27 21:57:36 +0000470 // Perform the initial placement of the constant pool entries. To start with,
471 // we put them all at the end of the function.
472 std::vector<MachineInstr*> CPEMIs;
473 if (!MCP->isEmpty())
474 doInitialPlacement(CPEMIs);
475
Reed Kotler0f007fc2013-11-05 08:14:14 +0000476 /// The next UID to take is the first unused one.
477 initPICLabelUId(CPEMIs.size());
478
479 // Do the initial scan of the function, building up information about the
480 // sizes of each block, the location of all the water, and finding all of the
481 // constant pool users.
482 initializeFunctionInfo(CPEMIs);
483 CPEMIs.clear();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000484 LLVM_DEBUG(dumpBBs());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000485
486 /// Remove dead constant pool entries.
487 MadeChange |= removeUnusedCPEntries();
488
489 // Iteratively place constant pool entries and fix up branches until there
490 // is no change.
491 unsigned NoCPIters = 0, NoBRIters = 0;
492 (void)NoBRIters;
493 while (true) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000494 LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Reed Kotler0f007fc2013-11-05 08:14:14 +0000495 bool CPChange = false;
496 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
497 CPChange |= handleConstantPoolUser(i);
498 if (CPChange && ++NoCPIters > 30)
499 report_fatal_error("Constant Island pass failed to converge!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000500 LLVM_DEBUG(dumpBBs());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000501
502 // Clear NewWaterList now. If we split a block for branches, it should
503 // appear as "new water" for the next iteration of constant pool placement.
504 NewWaterList.clear();
505
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000506 LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Reed Kotler0f007fc2013-11-05 08:14:14 +0000507 bool BRChange = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000508 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
509 BRChange |= fixupImmediateBr(ImmBranches[i]);
510 if (BRChange && ++NoBRIters > 30)
511 report_fatal_error("Branch Fix Up pass failed to converge!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000512 LLVM_DEBUG(dumpBBs());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000513 if (!CPChange && !BRChange)
514 break;
515 MadeChange = true;
516 }
517
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000518 LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000519
520 BBInfo.clear();
521 WaterList.clear();
522 CPUsers.clear();
523 CPEntries.clear();
524 ImmBranches.clear();
525 return MadeChange;
Reed Kotlerbb3094a2013-02-27 03:33:58 +0000526}
527
Reed Kotler91ae9822013-10-27 21:57:36 +0000528/// doInitialPlacement - Perform the initial placement of the constant pool
529/// entries. To start with, we put them all at the end of the function.
530void
531MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
532 // Create the basic block to hold the CPE's.
533 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
534 MF->push_back(BB);
535
Reed Kotler91ae9822013-10-27 21:57:36 +0000536 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Guillaume Chateletaff45e42019-09-05 10:00:22 +0000537 unsigned MaxLogAlign = Log2_32(MCP->getConstantPoolAlignment());
Reed Kotler91ae9822013-10-27 21:57:36 +0000538
539 // Mark the basic block as required by the const-pool.
540 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
Guillaume Chateletaff45e42019-09-05 10:00:22 +0000541 BB->setLogAlignment(AlignConstantIslands ? MaxLogAlign : 2);
Reed Kotler91ae9822013-10-27 21:57:36 +0000542
543 // The function needs to be as aligned as the basic blocks. The linker may
544 // move functions around based on their alignment.
Guillaume Chatelet48904e92019-09-11 11:16:48 +0000545 MF->ensureAlignment(BB->getAlignment());
Reed Kotler91ae9822013-10-27 21:57:36 +0000546
547 // Order the entries in BB by descending alignment. That ensures correct
548 // alignment of all entries as long as BB is sufficiently aligned. Keep
549 // track of the insertion point for each alignment. We are going to bucket
550 // sort the entries as they are created.
Guillaume Chateletaff45e42019-09-05 10:00:22 +0000551 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxLogAlign + 1,
552 BB->end());
Reed Kotler91ae9822013-10-27 21:57:36 +0000553
554 // Add all of the constants from the constant pool to the end block, use an
555 // identity mapping of CPI's to CPE's.
556 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
557
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000558 const DataLayout &TD = MF->getDataLayout();
Reed Kotler91ae9822013-10-27 21:57:36 +0000559 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
560 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
561 assert(Size >= 4 && "Too small constant pool entry");
562 unsigned Align = CPs[i].getAlignment();
563 assert(isPowerOf2_32(Align) && "Invalid alignment");
564 // Verify that all constant pool entries are a multiple of their alignment.
565 // If not, we would have to pad them out so that instructions stay aligned.
566 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
567
568 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
569 unsigned LogAlign = Log2_32(Align);
570 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
571
572 MachineInstr *CPEMI =
573 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
574 .addImm(i).addConstantPoolIndex(i).addImm(Size);
575
576 CPEMIs.push_back(CPEMI);
577
578 // Ensure that future entries with higher alignment get inserted before
579 // CPEMI. This is bucket sort with iterators.
Guillaume Chateletaff45e42019-09-05 10:00:22 +0000580 for (unsigned a = LogAlign + 1; a <= MaxLogAlign; ++a)
Reed Kotler91ae9822013-10-27 21:57:36 +0000581 if (InsPoint[a] == InsAt)
582 InsPoint[a] = CPEMI;
583 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000584 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Reed Kotler91ae9822013-10-27 21:57:36 +0000585 ++NumCPEs;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000586 LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
587 << Size << ", align = " << Align << '\n');
Reed Kotler91ae9822013-10-27 21:57:36 +0000588 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000589 LLVM_DEBUG(BB->dump());
Reed Kotler91ae9822013-10-27 21:57:36 +0000590}
591
Reed Kotler0f007fc2013-11-05 08:14:14 +0000592/// BBHasFallthrough - Return true if the specified basic block can fallthrough
593/// into the block immediately after it.
594static bool BBHasFallthrough(MachineBasicBlock *MBB) {
595 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000596 MachineFunction::iterator MBBI = MBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000597 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000598 if (std::next(MBBI) == MBB->getParent()->end())
Reed Kotler0f007fc2013-11-05 08:14:14 +0000599 return false;
600
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000601 MachineBasicBlock *NextBB = &*std::next(MBBI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000602 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
603 E = MBB->succ_end(); I != E; ++I)
604 if (*I == NextBB)
605 return true;
606
607 return false;
608}
609
610/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
611/// look up the corresponding CPEntry.
612MipsConstantIslands::CPEntry
613*MipsConstantIslands::findConstPoolEntry(unsigned CPI,
614 const MachineInstr *CPEMI) {
615 std::vector<CPEntry> &CPEs = CPEntries[CPI];
616 // Number of entries per constpool index should be small, just do a
617 // linear search.
618 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
619 if (CPEs[i].CPEMI == CPEMI)
620 return &CPEs[i];
621 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000622 return nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000623}
624
625/// getCPELogAlign - Returns the required alignment of the constant pool entry
626/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000627unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr &CPEMI) {
628 assert(CPEMI.getOpcode() == Mips::CONSTPOOL_ENTRY);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000629
630 // Everything is 4-byte aligned unless AlignConstantIslands is set.
631 if (!AlignConstantIslands)
632 return 2;
633
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000634 unsigned CPI = CPEMI.getOperand(1).getIndex();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000635 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
636 unsigned Align = MCP->getConstants()[CPI].getAlignment();
637 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
638 return Log2_32(Align);
639}
640
641/// initializeFunctionInfo - Do the initial scan of the function, building up
642/// information about the sizes of each block, the location of all the water,
643/// and finding all of the constant pool users.
644void MipsConstantIslands::
645initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
646 BBInfo.clear();
647 BBInfo.resize(MF->getNumBlockIDs());
648
649 // First thing, compute the size of all basic blocks, and see if the function
650 // has any inline assembly in it. If so, we have to be conservative about
651 // alignment assumptions, as we don't know for sure the size of any
652 // instructions in the inline assembly.
653 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000654 computeBlockSize(&*I);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000655
Reed Kotler0f007fc2013-11-05 08:14:14 +0000656 // Compute block offsets.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000657 adjustBBOffsetsAfter(&MF->front());
Reed Kotler0f007fc2013-11-05 08:14:14 +0000658
659 // Now go back through the instructions and build up our data structures.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000660 for (MachineBasicBlock &MBB : *MF) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000661 // If this block doesn't fall through into the next MBB, then this is
662 // 'water' that a constant pool island could be placed.
663 if (!BBHasFallthrough(&MBB))
664 WaterList.push_back(&MBB);
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000665 for (MachineInstr &MI : MBB) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000666 if (MI.isDebugInstr())
Reed Kotler0f007fc2013-11-05 08:14:14 +0000667 continue;
668
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000669 int Opc = MI.getOpcode();
670 if (MI.isBranch()) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000671 bool isCond = false;
672 unsigned Bits = 0;
673 unsigned Scale = 1;
674 int UOpc = Opc;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000675 switch (Opc) {
676 default:
Reed Kotler4b7afe52013-11-13 23:52:18 +0000677 continue; // Ignore other branches for now
678 case Mips::Bimm16:
679 Bits = 11;
680 Scale = 2;
681 isCond = false;
682 break;
683 case Mips::BimmX16:
684 Bits = 16;
685 Scale = 2;
686 isCond = false;
Reed Kotler0d409e22013-11-28 00:56:37 +0000687 break;
688 case Mips::BeqzRxImm16:
Reed Kotler59975c22013-12-03 23:42:51 +0000689 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000690 Bits = 8;
691 Scale = 2;
692 isCond = true;
693 break;
694 case Mips::BeqzRxImmX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000695 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000696 Bits = 16;
697 Scale = 2;
698 isCond = true;
699 break;
700 case Mips::BnezRxImm16:
Reed Kotler59975c22013-12-03 23:42:51 +0000701 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000702 Bits = 8;
703 Scale = 2;
704 isCond = true;
705 break;
706 case Mips::BnezRxImmX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000707 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000708 Bits = 16;
709 Scale = 2;
710 isCond = true;
711 break;
712 case Mips::Bteqz16:
Reed Kotler59975c22013-12-03 23:42:51 +0000713 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000714 Bits = 8;
715 Scale = 2;
716 isCond = true;
717 break;
718 case Mips::BteqzX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000719 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000720 Bits = 16;
721 Scale = 2;
722 isCond = true;
723 break;
724 case Mips::Btnez16:
Reed Kotler59975c22013-12-03 23:42:51 +0000725 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000726 Bits = 8;
727 Scale = 2;
728 isCond = true;
729 break;
730 case Mips::BtnezX16:
Reed Kotler59975c22013-12-03 23:42:51 +0000731 UOpc=Mips::Bimm16;
Reed Kotler0d409e22013-11-28 00:56:37 +0000732 Bits = 16;
733 Scale = 2;
734 isCond = true;
735 break;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000736 }
737 // Record this immediate branch.
738 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000739 ImmBranches.push_back(ImmBranch(&MI, MaxOffs, isCond, UOpc));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000740 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000741
742 if (Opc == Mips::CONSTPOOL_ENTRY)
743 continue;
744
Reed Kotler0f007fc2013-11-05 08:14:14 +0000745 // Scan the instructions for constant pool operands.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000746 for (unsigned op = 0, e = MI.getNumOperands(); op != e; ++op)
747 if (MI.getOperand(op).isCPI()) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000748 // We found one. The addressing mode tells us the max displacement
749 // from the PC that this instruction permits.
750
751 // Basic size info comes from the TSFlags field.
752 unsigned Bits = 0;
753 unsigned Scale = 1;
754 bool NegOk = false;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000755 unsigned LongFormBits = 0;
756 unsigned LongFormScale = 0;
757 unsigned LongFormOpcode = 0;
758 switch (Opc) {
759 default:
760 llvm_unreachable("Unknown addressing mode for CP reference!");
761 case Mips::LwRxPcTcp16:
762 Bits = 8;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000763 Scale = 4;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000764 LongFormOpcode = Mips::LwRxPcTcpX16;
Reed Kotler43788a22014-01-16 00:47:46 +0000765 LongFormBits = 14;
Reed Kotler45c59272013-11-10 00:09:26 +0000766 LongFormScale = 1;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000767 break;
768 case Mips::LwRxPcTcpX16:
Reed Kotler43788a22014-01-16 00:47:46 +0000769 Bits = 14;
Reed Kotler3d7b33f2013-11-06 04:29:52 +0000770 Scale = 1;
771 NegOk = true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000772 break;
773 }
774 // Remember that this is a user of a CP entry.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000775 unsigned CPI = MI.getOperand(op).getIndex();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000776 MachineInstr *CPEMI = CPEMIs[CPI];
777 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
778 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000779 CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk, LongFormMaxOffs,
780 LongFormOpcode));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000781
782 // Increment corresponding CPEntry reference count.
783 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
784 assert(CPE && "Cannot find a corresponding CPEntry!");
785 CPE->RefCount++;
786
787 // Instructions can only use one CP entry, don't bother scanning the
788 // rest of the operands.
789 break;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000790 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000791 }
792 }
Reed Kotler0f007fc2013-11-05 08:14:14 +0000793}
794
795/// computeBlockSize - Compute the size and some alignment information for MBB.
796/// This function updates BBInfo directly.
797void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
798 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
799 BBI.Size = 0;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000800
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000801 for (const MachineInstr &MI : *MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000802 BBI.Size += TII->getInstSizeInBytes(MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000803}
804
805/// getOffsetOf - Return the current offset of the specified machine instruction
806/// from the start of the function. This offset changes as stuff is moved
807/// around inside the function.
808unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
809 MachineBasicBlock *MBB = MI->getParent();
810
811 // The offset is composed of two things: the sum of the sizes of all MBB's
812 // before this instruction's block, and the offset from the start of the block
813 // it is in.
814 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
815
816 // Sum instructions before MI in MBB.
817 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
818 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000819 Offset += TII->getInstSizeInBytes(*I);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000820 }
821 return Offset;
822}
823
824/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
825/// ID.
826static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
827 const MachineBasicBlock *RHS) {
828 return LHS->getNumber() < RHS->getNumber();
829}
830
831/// updateForInsertedWaterBlock - When a block is newly inserted into the
832/// machine function, it upsets all of the block numbers. Renumber the blocks
833/// and update the arrays that parallel this numbering.
834void MipsConstantIslands::updateForInsertedWaterBlock
835 (MachineBasicBlock *NewBB) {
836 // Renumber the MBB's to keep them consecutive.
837 NewBB->getParent()->RenumberBlocks(NewBB);
838
839 // Insert an entry into BBInfo to align it properly with the (newly
840 // renumbered) block numbers.
841 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
842
843 // Next, update WaterList. Specifically, we need to add NewMBB as having
844 // available water after it.
Fangrui Songdc8de602019-06-21 05:40:31 +0000845 water_iterator IP = llvm::lower_bound(WaterList, NewBB, CompareMBBNumbers);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000846 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).
Fangrui Songdc8de602019-06-21 05:40:31 +0000895 water_iterator IP = llvm::lower_bound(WaterList, OrigBB, CompareMBBNumbers);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000896 MachineBasicBlock* WaterBB = *IP;
897 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000898 WaterList.insert(std::next(IP), NewBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000899 else
900 WaterList.insert(IP, OrigBB);
901 NewWaterList.insert(OrigBB);
902
903 // Figure out how large the OrigBB is. As the first half of the original
904 // block, it cannot contain a tablejump. The size includes
905 // the new jump we added. (It should be possible to do this without
906 // recounting everything, but it's very confusing, and this is rarely
907 // executed.)
908 computeBlockSize(OrigBB);
909
910 // Figure out how large the NewMBB is. As the second half of the original
911 // block, it may contain a tablejump.
912 computeBlockSize(NewBB);
913
914 // All BBOffsets following these blocks must be modified.
915 adjustBBOffsetsAfter(OrigBB);
916
917 return NewBB;
918}
919
Reed Kotler0f007fc2013-11-05 08:14:14 +0000920/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
921/// reference) is within MaxDisp of TrialOffset (a proposed location of a
922/// constant pool entry).
Reed Kotler0f007fc2013-11-05 08:14:14 +0000923bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
924 unsigned TrialOffset, unsigned MaxDisp,
Reed Kotlerb09ebe92013-11-05 22:34:29 +0000925 bool NegativeOK) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000926 if (UserOffset <= TrialOffset) {
927 // User before the Trial.
928 if (TrialOffset - UserOffset <= MaxDisp)
929 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000930 } else if (NegativeOK) {
931 if (UserOffset - TrialOffset <= MaxDisp)
932 return true;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000933 }
934 return false;
935}
936
937/// isWaterInRange - Returns true if a CPE placed after the specified
938/// Water (a basic block) will be in range for the specific MI.
939///
940/// Compute how much the function will grow by inserting a CPE after Water.
941bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
942 MachineBasicBlock* Water, CPUser &U,
943 unsigned &Growth) {
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000944 unsigned CPELogAlign = getCPELogAlign(*U.CPEMI);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000945 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
Guillaume Chateletaff45e42019-09-05 10:00:22 +0000946 unsigned NextBlockOffset, NextBlockLogAlignment;
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +0000947 MachineFunction::const_iterator NextBlock = ++Water->getIterator();
948 if (NextBlock == MF->end()) {
Reed Kotler0f007fc2013-11-05 08:14:14 +0000949 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
Guillaume Chateletaff45e42019-09-05 10:00:22 +0000950 NextBlockLogAlignment = 0;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000951 } else {
952 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
Guillaume Chateletaff45e42019-09-05 10:00:22 +0000953 NextBlockLogAlignment = NextBlock->getLogAlignment();
Reed Kotler0f007fc2013-11-05 08:14:14 +0000954 }
955 unsigned Size = U.CPEMI->getOperand(2).getImm();
956 unsigned CPEEnd = CPEOffset + Size;
957
958 // The CPE may be able to hide in the alignment padding before the next
959 // block. It may also cause more padding to be required if it is more aligned
960 // that the next block.
961 if (CPEEnd > NextBlockOffset) {
962 Growth = CPEEnd - NextBlockOffset;
963 // Compute the padding that would go at the end of the CPE to align the next
964 // block.
Guillaume Chateletaff45e42019-09-05 10:00:22 +0000965 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockLogAlignment);
Reed Kotler0f007fc2013-11-05 08:14:14 +0000966
967 // If the CPE is to be inserted before the instruction, that will raise
968 // the offset of the instruction. Also account for unknown alignment padding
969 // in blocks between CPE and the user.
970 if (CPEOffset < UserOffset)
Reed Kotler7ded5b62013-11-05 23:36:58 +0000971 UserOffset += Growth;
Reed Kotler0f007fc2013-11-05 08:14:14 +0000972 } else
973 // CPE fits in existing padding.
974 Growth = 0;
975
976 return isOffsetInRange(UserOffset, CPEOffset, U);
977}
978
979/// isCPEntryInRange - Returns true if the distance between specific MI and
980/// specific ConstPool entry instruction can fit in MI's displacement field.
981bool MipsConstantIslands::isCPEntryInRange
982 (MachineInstr *MI, unsigned UserOffset,
983 MachineInstr *CPEMI, unsigned MaxDisp,
984 bool NegOk, bool DoDump) {
985 unsigned CPEOffset = getOffsetOf(CPEMI);
986
987 if (DoDump) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000988 LLVM_DEBUG({
Reed Kotler0f007fc2013-11-05 08:14:14 +0000989 unsigned Block = MI->getParent()->getNumber();
990 const BasicBlockInfo &BBI = BBInfo[Block];
991 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
992 << " max delta=" << MaxDisp
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000993 << format(" insn address=%#x", UserOffset) << " in "
994 << printMBBReference(*MI->getParent()) << ": "
Reed Kotler0f007fc2013-11-05 08:14:14 +0000995 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
996 << format("CPE address=%#x offset=%+d: ", CPEOffset,
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000997 int(CPEOffset - UserOffset));
Reed Kotler0f007fc2013-11-05 08:14:14 +0000998 });
999 }
1000
1001 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1002}
1003
1004#ifndef NDEBUG
1005/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1006/// unconditionally branches to its only successor.
1007static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1008 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1009 return false;
1010 MachineBasicBlock *Succ = *MBB->succ_begin();
1011 MachineBasicBlock *Pred = *MBB->pred_begin();
1012 MachineInstr *PredMI = &Pred->back();
Reed Kotlerf0e69682013-11-12 02:27:12 +00001013 if (PredMI->getOpcode() == Mips::Bimm16)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001014 return PredMI->getOperand(0).getMBB() == Succ;
1015 return false;
1016}
1017#endif
1018
1019void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1020 unsigned BBNum = BB->getNumber();
1021 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1022 // Get the offset and known bits at the end of the layout predecessor.
1023 // Include the alignment of the current block.
Reed Kotler7ded5b62013-11-05 23:36:58 +00001024 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001025 BBInfo[i].Offset = Offset;
1026 }
1027}
1028
1029/// decrementCPEReferenceCount - find the constant pool entry with index CPI
1030/// and instruction CPEMI, and decrement its refcount. If the refcount
1031/// becomes 0 remove the entry and instruction. Returns true if we removed
1032/// the entry, false if we didn't.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001033bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1034 MachineInstr *CPEMI) {
1035 // Find the old entry. Eliminate it if it is no longer used.
1036 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1037 assert(CPE && "Unexpected!");
1038 if (--CPE->RefCount == 0) {
1039 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001040 CPE->CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001041 --NumCPEs;
1042 return true;
1043 }
1044 return false;
1045}
1046
1047/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1048/// if not, see if an in-range clone of the CPE is in range, and if so,
1049/// change the data structures so the user references the clone. Returns:
1050/// 0 = no existing entry found
1051/// 1 = entry found, and there were no code insertions or deletions
1052/// 2 = entry found, and there were code insertions or deletions
1053int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1054{
1055 MachineInstr *UserMI = U.MI;
1056 MachineInstr *CPEMI = U.CPEMI;
1057
1058 // Check to see if the CPE is already in-range.
1059 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1060 true)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001061 LLVM_DEBUG(dbgs() << "In range\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001062 return 1;
1063 }
1064
1065 // No. Look for previously created clones of the CPE that are in range.
1066 unsigned CPI = CPEMI->getOperand(1).getIndex();
1067 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1068 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1069 // We already tried this one
1070 if (CPEs[i].CPEMI == CPEMI)
1071 continue;
1072 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001073 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001074 continue;
1075 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1076 U.NegOk)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001077 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1078 << CPEs[i].CPI << "\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001079 // Point the CPUser node to the replacement
1080 U.CPEMI = CPEs[i].CPEMI;
1081 // Change the CPI in the instruction operand to refer to the clone.
1082 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1083 if (UserMI->getOperand(j).isCPI()) {
1084 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1085 break;
1086 }
1087 // Adjust the refcount of the clone...
1088 CPEs[i].RefCount++;
1089 // ...and the original. If we didn't remove the old entry, none of the
1090 // addresses changed, so we don't need another pass.
1091 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1092 }
1093 }
1094 return 0;
1095}
1096
1097/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1098/// This version checks if the longer form of the instruction can be used to
1099/// to satisfy things.
1100/// if not, see if an in-range clone of the CPE is in range, and if so,
1101/// change the data structures so the user references the clone. Returns:
1102/// 0 = no existing entry found
1103/// 1 = entry found, and there were no code insertions or deletions
1104/// 2 = entry found, and there were code insertions or deletions
1105int MipsConstantIslands::findLongFormInRangeCPEntry
1106 (CPUser& U, unsigned UserOffset)
1107{
1108 MachineInstr *UserMI = U.MI;
1109 MachineInstr *CPEMI = U.CPEMI;
1110
1111 // Check to see if the CPE is already in-range.
1112 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1113 U.getLongFormMaxDisp(), U.NegOk,
1114 true)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001115 LLVM_DEBUG(dbgs() << "In range\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001116 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
Reed Kotler45c59272013-11-10 00:09:26 +00001117 U.setMaxDisp(U.getLongFormMaxDisp());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001118 return 2; // instruction is longer length now
1119 }
1120
1121 // No. Look for previously created clones of the CPE that are in range.
1122 unsigned CPI = CPEMI->getOperand(1).getIndex();
1123 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1124 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1125 // We already tried this one
1126 if (CPEs[i].CPEMI == CPEMI)
1127 continue;
1128 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001129 if (CPEs[i].CPEMI == nullptr)
Reed Kotler0f007fc2013-11-05 08:14:14 +00001130 continue;
1131 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1132 U.getLongFormMaxDisp(), U.NegOk)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001133 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1134 << CPEs[i].CPI << "\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001135 // Point the CPUser node to the replacement
1136 U.CPEMI = CPEs[i].CPEMI;
1137 // Change the CPI in the instruction operand to refer to the clone.
1138 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1139 if (UserMI->getOperand(j).isCPI()) {
1140 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1141 break;
1142 }
1143 // Adjust the refcount of the clone...
1144 CPEs[i].RefCount++;
1145 // ...and the original. If we didn't remove the old entry, none of the
1146 // addresses changed, so we don't need another pass.
1147 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1148 }
1149 }
1150 return 0;
1151}
1152
1153/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1154/// the specific unconditional branch instruction.
1155static inline unsigned getUnconditionalBrDisp(int Opc) {
1156 switch (Opc) {
Reed Kotlerf0e69682013-11-12 02:27:12 +00001157 case Mips::Bimm16:
1158 return ((1<<10)-1)*2;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001159 case Mips::BimmX16:
1160 return ((1<<16)-1)*2;
1161 default:
1162 break;
1163 }
1164 return ((1<<16)-1)*2;
1165}
1166
1167/// findAvailableWater - Look for an existing entry in the WaterList in which
1168/// we can place the CPE referenced from U so it's within range of U's MI.
1169/// Returns true if found, false if not. If it returns true, WaterIter
Fangrui Songf78650a2018-07-30 19:41:25 +00001170/// is set to the WaterList entry.
Reed Kotler4d0313d2013-11-05 12:04:37 +00001171/// To ensure that this pass
Reed Kotler0f007fc2013-11-05 08:14:14 +00001172/// terminates, the CPE location for a particular CPUser is only allowed to
1173/// move to a lower address, so search backward from the end of the list and
1174/// prefer the first water that is in range.
1175bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1176 water_iterator &WaterIter) {
1177 if (WaterList.empty())
1178 return false;
1179
1180 unsigned BestGrowth = ~0u;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001181 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001182 --IP) {
1183 MachineBasicBlock* WaterBB = *IP;
1184 // Check if water is in range and is either at a lower address than the
1185 // current "high water mark" or a new water block that was created since
1186 // the previous iteration by inserting an unconditional branch. In the
1187 // latter case, we want to allow resetting the high water mark back to
1188 // this new water since we haven't seen it before. Inserting branches
1189 // should be relatively uncommon and when it does happen, we want to be
1190 // sure to take advantage of it for all the CPEs near that block, so that
1191 // we don't insert more branches than necessary.
1192 unsigned Growth;
1193 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1194 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1195 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1196 // This is the least amount of required padding seen so far.
1197 BestGrowth = Growth;
1198 WaterIter = IP;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001199 LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
1200 << " Growth=" << Growth << '\n');
Reed Kotler0f007fc2013-11-05 08:14:14 +00001201
1202 // Keep looking unless it is perfect.
1203 if (BestGrowth == 0)
1204 return true;
1205 }
1206 if (IP == B)
1207 break;
1208 }
1209 return BestGrowth != ~0u;
1210}
1211
1212/// createNewWater - No existing WaterList entry will work for
1213/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1214/// block is used if in range, and the conditional branch munged so control
1215/// flow is correct. Otherwise the block is split to create a hole with an
1216/// unconditional branch around it. In either case NewMBB is set to a
1217/// block following which the new island can be inserted (the WaterList
1218/// is not adjusted).
1219void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1220 unsigned UserOffset,
1221 MachineBasicBlock *&NewMBB) {
1222 CPUser &U = CPUsers[CPUserIndex];
1223 MachineInstr *UserMI = U.MI;
1224 MachineInstr *CPEMI = U.CPEMI;
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +00001225 unsigned CPELogAlign = getCPELogAlign(*CPEMI);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001226 MachineBasicBlock *UserMBB = UserMI->getParent();
1227 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1228
1229 // If the block does not end in an unconditional branch already, and if the
Fangrui Songf78650a2018-07-30 19:41:25 +00001230 // end of the block is within range, make new water there.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001231 if (BBHasFallthrough(UserMBB)) {
1232 // Size of branch to insert.
1233 unsigned Delta = 2;
1234 // Compute the offset where the CPE will begin.
1235 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1236
1237 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001238 LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
1239 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001240 NewMBB = &*++UserMBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001241 // Add an unconditional branch from UserMBB to fallthrough block. Record
1242 // it for branch lengthening; this new branch will not get out of range,
1243 // but if the preceding conditional branch is out of range, the targets
1244 // will be exchanged, and the altered branch may be out of range, so the
1245 // machinery has to know about it.
Reed Kotlerf0e69682013-11-12 02:27:12 +00001246 int UncondBr = Mips::Bimm16;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001247 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1248 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1249 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1250 MaxDisp, false, UncondBr));
1251 BBInfo[UserMBB->getNumber()].Size += Delta;
1252 adjustBBOffsetsAfter(UserMBB);
1253 return;
1254 }
1255 }
1256
Fangrui Songf78650a2018-07-30 19:41:25 +00001257 // What a big block. Find a place within the block to split it.
Reed Kotler0f007fc2013-11-05 08:14:14 +00001258
1259 // Try to split the block so it's fully aligned. Compute the latest split
1260 // point where we can add a 4-byte branch instruction, and then align to
1261 // LogAlign which is the largest possible alignment in the function.
Guillaume Chatelet48904e92019-09-11 11:16:48 +00001262 unsigned LogAlign = Log2(MF->getAlignment());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001263 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
Reed Kotler7ded5b62013-11-05 23:36:58 +00001264 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001265 LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1266 BaseInsertOffset));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001267
1268 // The 4 in the following is for the unconditional branch we'll be inserting
Reed Kotler4d0313d2013-11-05 12:04:37 +00001269 // Alignment of the island is handled
Reed Kotler0f007fc2013-11-05 08:14:14 +00001270 // inside isOffsetInRange.
1271 BaseInsertOffset -= 4;
1272
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001273 LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1274 << " la=" << LogAlign << '\n');
Reed Kotler0f007fc2013-11-05 08:14:14 +00001275
1276 // This could point off the end of the block if we've already got constant
1277 // pool entries following this block; only the last one is in the water list.
1278 // Back past any possible branches (allow for a conditional and a maximally
1279 // long unconditional).
1280 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Reed Kotler7ded5b62013-11-05 23:36:58 +00001281 BaseInsertOffset = UserBBI.postOffset() - 8;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001282 LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001283 }
Reed Kotler7ded5b62013-11-05 23:36:58 +00001284 unsigned EndInsertOffset = BaseInsertOffset + 4 +
Reed Kotler0f007fc2013-11-05 08:14:14 +00001285 CPEMI->getOperand(2).getImm();
1286 MachineBasicBlock::iterator MI = UserMI;
1287 ++MI;
1288 unsigned CPUIndex = CPUserIndex+1;
1289 unsigned NumCPUsers = CPUsers.size();
1290 //MachineInstr *LastIT = 0;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001291 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001292 Offset < BaseInsertOffset;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001293 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001294 assert(MI != UserMBB->end() && "Fell off end of block");
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +00001295 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001296 CPUser &U = CPUsers[CPUIndex];
1297 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1298 // Shift intertion point by one unit of alignment so it is within reach.
1299 BaseInsertOffset -= 1u << LogAlign;
1300 EndInsertOffset -= 1u << LogAlign;
1301 }
1302 // This is overly conservative, as we don't account for CPEMIs being
1303 // reused within the block, but it doesn't matter much. Also assume CPEs
1304 // are added in order with alignment padding. We may eventually be able
1305 // to pack the aligned CPEs better.
1306 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1307 CPUIndex++;
1308 }
1309 }
1310
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +00001311 NewMBB = splitBlockBeforeInstr(*--MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001312}
1313
1314/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1315/// is out-of-range. If so, pick up the constant pool value and move it some
1316/// place in-range. Return true if we changed any addresses (thus must run
1317/// another pass of branch lengthening), false otherwise.
1318bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1319 CPUser &U = CPUsers[CPUserIndex];
1320 MachineInstr *UserMI = U.MI;
1321 MachineInstr *CPEMI = U.CPEMI;
1322 unsigned CPI = CPEMI->getOperand(1).getIndex();
1323 unsigned Size = CPEMI->getOperand(2).getImm();
1324 // Compute this only once, it's expensive.
1325 unsigned UserOffset = getUserOffset(U);
1326
1327 // See if the current entry is within range, or there is a clone of it
1328 // in range.
1329 int result = findInRangeCPEntry(U, UserOffset);
1330 if (result==1) return false;
1331 else if (result==2) return true;
1332
Reed Kotler0f007fc2013-11-05 08:14:14 +00001333 // Look for water where we can place this CPE.
1334 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1335 MachineBasicBlock *NewMBB;
1336 water_iterator IP;
1337 if (findAvailableWater(U, UserOffset, IP)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001338 LLVM_DEBUG(dbgs() << "Found water in range\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001339 MachineBasicBlock *WaterBB = *IP;
1340
1341 // If the original WaterList entry was "new water" on this iteration,
1342 // propagate that to the new island. This is just keeping NewWaterList
1343 // updated to match the WaterList, which will be updated below.
1344 if (NewWaterList.erase(WaterBB))
1345 NewWaterList.insert(NewIsland);
1346
1347 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001348 NewMBB = &*++WaterBB->getIterator();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001349 } else {
1350 // No water found.
1351 // we first see if a longer form of the instrucion could have reached
1352 // the constant. in that case we won't bother to split
Reed Kotler45c59272013-11-10 00:09:26 +00001353 if (!NoLoadRelaxation) {
1354 result = findLongFormInRangeCPEntry(U, UserOffset);
1355 if (result != 0) return true;
1356 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001357 LLVM_DEBUG(dbgs() << "No water found\n");
Reed Kotler0f007fc2013-11-05 08:14:14 +00001358 createNewWater(CPUserIndex, UserOffset, NewMBB);
1359
1360 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1361 // called while handling branches so that the water will be seen on the
1362 // next iteration for constant pools, but in this context, we don't want
1363 // it. Check for this so it will be removed from the WaterList.
1364 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001365 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
Eugene Zelenkodde94e42017-01-30 23:21:32 +00001366 IP = llvm::find(WaterList, WaterBB);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001367 if (IP != WaterList.end())
1368 NewWaterList.erase(WaterBB);
1369
1370 // We are adding new water. Update NewWaterList.
1371 NewWaterList.insert(NewIsland);
1372 }
1373
1374 // Remove the original WaterList entry; we want subsequent insertions in
1375 // this vicinity to go after the one we're about to insert. This
1376 // considerably reduces the number of times we have to move the same CPE
1377 // more than once and is also important to ensure the algorithm terminates.
1378 if (IP != WaterList.end())
1379 WaterList.erase(IP);
1380
1381 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001382 MF->insert(NewMBB->getIterator(), NewIsland);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001383
1384 // Update internal data structures to account for the newly inserted MBB.
1385 updateForInsertedWaterBlock(NewIsland);
1386
1387 // Decrement the old entry, and remove it if refcount becomes 0.
1388 decrementCPEReferenceCount(CPI, CPEMI);
1389
Reed Kotlerd3b28eb2013-11-24 02:53:09 +00001390 // No existing clone of this CPE is within range.
1391 // We will be generating a new clone. Get a UID for it.
1392 unsigned ID = createPICLabelUId();
1393
Reed Kotler0f007fc2013-11-05 08:14:14 +00001394 // Now that we have an island to add the CPE to, clone the original CPE and
1395 // add it to the island.
1396 U.HighWaterMark = NewIsland;
1397 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1398 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1399 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1400 ++NumCPEs;
1401
1402 // Mark the basic block as aligned as required by the const-pool entry.
Guillaume Chateletaff45e42019-09-05 10:00:22 +00001403 NewIsland->setLogAlignment(getCPELogAlign(*U.CPEMI));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001404
1405 // Increase the size of the island block to account for the new entry.
1406 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith78691482015-10-20 00:15:20 +00001407 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Reed Kotler0f007fc2013-11-05 08:14:14 +00001408
1409 // Finally, change the CPI in the instruction operand to be ID.
1410 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1411 if (UserMI->getOperand(i).isCPI()) {
1412 UserMI->getOperand(i).setIndex(ID);
1413 break;
1414 }
1415
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001416 LLVM_DEBUG(
1417 dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1418 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001419
1420 return true;
1421}
1422
1423/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1424/// sizes and offsets of impacted basic blocks.
1425void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1426 MachineBasicBlock *CPEBB = CPEMI->getParent();
1427 unsigned Size = CPEMI->getOperand(2).getImm();
1428 CPEMI->eraseFromParent();
1429 BBInfo[CPEBB->getNumber()].Size -= Size;
1430 // All succeeding offsets have the current size value added in, fix this.
1431 if (CPEBB->empty()) {
1432 BBInfo[CPEBB->getNumber()].Size = 0;
1433
1434 // This block no longer needs to be aligned.
Guillaume Chateletaff45e42019-09-05 10:00:22 +00001435 CPEBB->setLogAlignment(0);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001436 } else
1437 // Entries are sorted by descending alignment, so realign from the front.
Guillaume Chateletaff45e42019-09-05 10:00:22 +00001438 CPEBB->setLogAlignment(getCPELogAlign(*CPEBB->begin()));
Reed Kotler0f007fc2013-11-05 08:14:14 +00001439
1440 adjustBBOffsetsAfter(CPEBB);
1441 // An island has only one predecessor BB and one successor BB. Check if
1442 // this BB's predecessor jumps directly to this BB's successor. This
1443 // shouldn't happen currently.
1444 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1445 // FIXME: remove the empty blocks after all the work is done?
1446}
1447
1448/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1449/// are zero.
1450bool MipsConstantIslands::removeUnusedCPEntries() {
1451 unsigned MadeChange = false;
1452 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1453 std::vector<CPEntry> &CPEs = CPEntries[i];
1454 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1455 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1456 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001457 CPEs[j].CPEMI = nullptr;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001458 MadeChange = true;
1459 }
1460 }
1461 }
1462 return MadeChange;
1463}
1464
1465/// isBBInRange - Returns true if the distance between specific MI and
1466/// specific BB can fit in MI's displacement field.
1467bool MipsConstantIslands::isBBInRange
1468 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
Eugene Zelenkodde94e42017-01-30 23:21:32 +00001469 unsigned PCAdj = 4;
Reed Kotler0f007fc2013-11-05 08:14:14 +00001470 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1471 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1472
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001473 LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)
1474 << " from " << printMBBReference(*MI->getParent())
1475 << " max delta=" << MaxDisp << " from " << getOffsetOf(MI)
1476 << " to " << DestOffset << " offset "
1477 << int(DestOffset - BrOffset) << "\t" << *MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001478
1479 if (BrOffset <= DestOffset) {
1480 // Branch before the Dest.
1481 if (DestOffset-BrOffset <= MaxDisp)
1482 return true;
1483 } else {
1484 if (BrOffset-DestOffset <= MaxDisp)
1485 return true;
1486 }
1487 return false;
1488}
1489
1490/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1491/// away to fit in its displacement field.
1492bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1493 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001494 unsigned TargetOperand = branchTargetOperand(MI);
1495 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001496
1497 // Check to see if the DestBB is already in-range.
1498 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1499 return false;
1500
1501 if (!Br.isCond)
1502 return fixupUnconditionalBr(Br);
1503 return fixupConditionalBr(Br);
1504}
1505
1506/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1507/// too far away to fit in its displacement field. If the LR register has been
1508/// spilled in the epilogue, then we can use BL to implement a far jump.
1509/// Otherwise, add an intermediate branch instruction to a branch.
1510bool
1511MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1512 MachineInstr *MI = Br.MI;
1513 MachineBasicBlock *MBB = MI->getParent();
Reed Kotler2fc05be2013-11-21 05:13:23 +00001514 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001515 // Use BL to implement far jump.
Reed Kotler2fc05be2013-11-21 05:13:23 +00001516 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1517 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1518 Br.MaxDisp = BimmX16MaxDisp;
1519 MI->setDesc(TII->get(Mips::BimmX16));
1520 }
1521 else {
1522 // need to give the math a more careful look here
1523 // this is really a segment address and not
1524 // a PC relative address. FIXME. But I think that
1525 // just reducing the bits by 1 as I've done is correct.
1526 // The basic block we are branching too much be longword aligned.
1527 // we know that RA is saved because we always save it right now.
1528 // this requirement will be relaxed later but we also have an alternate
1529 // way to implement this that I will implement that does not need jal.
1530 // We should have a way to back out this alignment restriction if we "can" later.
1531 // but it is not harmful.
1532 //
Guillaume Chateletaff45e42019-09-05 10:00:22 +00001533 DestBB->setLogAlignment(2);
Reed Kotler2fc05be2013-11-21 05:13:23 +00001534 Br.MaxDisp = ((1<<24)-1) * 2;
Reed Kotlerad450f22013-11-29 22:32:56 +00001535 MI->setDesc(TII->get(Mips::JalB16));
Reed Kotler2fc05be2013-11-21 05:13:23 +00001536 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001537 BBInfo[MBB->getNumber()].Size += 2;
1538 adjustBBOffsetsAfter(MBB);
1539 HasFarJump = true;
1540 ++NumUBrFixed;
1541
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001542 LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI);
Reed Kotler0f007fc2013-11-05 08:14:14 +00001543
1544 return true;
1545}
1546
1547/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1548/// far away to fit in its displacement field. It is converted to an inverse
1549/// conditional branch + an unconditional branch to the destination.
1550bool
1551MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1552 MachineInstr *MI = Br.MI;
Reed Kotler0d409e22013-11-28 00:56:37 +00001553 unsigned TargetOperand = branchTargetOperand(MI);
1554 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1555 unsigned Opcode = MI->getOpcode();
1556 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1557 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1558
1559 // Check to see if the DestBB is already in-range.
1560 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1561 Br.MaxDisp = LongFormMaxOff;
1562 MI->setDesc(TII->get(LongFormOpcode));
1563 return true;
1564 }
Reed Kotler0f007fc2013-11-05 08:14:14 +00001565
1566 // Add an unconditional branch to the destination and invert the branch
1567 // condition to jump over it:
Reed Kotlerad450f22013-11-29 22:32:56 +00001568 // bteqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001569 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001570 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001571 // b L1
1572 // L2:
Reed Kotler0f007fc2013-11-05 08:14:14 +00001573
1574 // If the branch is at the end of its MBB and that has a fall-through block,
1575 // direct the updated conditional branch to the fall-through block. Otherwise,
1576 // split the MBB before the next instruction.
1577 MachineBasicBlock *MBB = MI->getParent();
1578 MachineInstr *BMI = &MBB->back();
1579 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Reed Kotler47f3c64a2013-12-19 00:43:08 +00001580 unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
Fangrui Songf78650a2018-07-30 19:41:25 +00001581
Reed Kotler0f007fc2013-11-05 08:14:14 +00001582 ++NumCBrFixed;
1583 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001584 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Daniel Sandersf9d8b8c2016-05-06 13:23:51 +00001585 BMI->isUnconditionalBranch()) {
Reed Kotler0f007fc2013-11-05 08:14:14 +00001586 // Last MI in the BB is an unconditional branch. Can we simply invert the
1587 // condition and swap destinations:
Reed Kotlerad450f22013-11-29 22:32:56 +00001588 // beqz L1
Reed Kotler0f007fc2013-11-05 08:14:14 +00001589 // b L2
1590 // =>
Reed Kotlerad450f22013-11-29 22:32:56 +00001591 // bnez L2
Reed Kotler0f007fc2013-11-05 08:14:14 +00001592 // b L1
Reed Kotlerad450f22013-11-29 22:32:56 +00001593 unsigned BMITargetOperand = branchTargetOperand(BMI);
Fangrui Songf78650a2018-07-30 19:41:25 +00001594 MachineBasicBlock *NewDest =
Reed Kotlerad450f22013-11-29 22:32:56 +00001595 BMI->getOperand(BMITargetOperand).getMBB();
Reed Kotler0f007fc2013-11-05 08:14:14 +00001596 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001597 LLVM_DEBUG(
1598 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
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001619 LLVM_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;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001657 LLVM_DEBUG(dbgs() << "constant island constant " << *I << "\n");
Reed Kotler91ae9822013-10-27 21:57:36 +00001658 J = I->getNumOperands();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001659 LLVM_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();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001663 LLVM_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);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001669 LLVM_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}