blob: 29405eb65d52757aaa14541ef4adac4d2637e6f3 [file] [log] [blame]
Bill Wendling18581a42010-12-21 01:54:40 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
Evan Cheng10043e22007-01-19 07:51:42 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Cheng10043e22007-01-19 07:51:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
Evan Cheng10043e22007-01-19 07:51:42 +000016#include "ARM.h"
Evan Cheng22c7cf52007-01-25 03:12:46 +000017#include "ARMMachineFunctionInfo.h"
Evan Chenga20cde32011-07-20 23:34:39 +000018#include "MCTargetDesc/ARMAddressingModes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "Thumb2InstrInfo.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
Evan Cheng10043e22007-01-19 07:51:42 +000024#include "llvm/CodeGen/MachineConstantPool.h"
25#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Chengc6d70ae2009-07-29 02:18:14 +000026#include "llvm/CodeGen/MachineJumpTableInfo.h"
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Support/CommandLine.h"
Evan Cheng10043e22007-01-19 07:51:42 +000030#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +000032#include "llvm/Support/Format.h"
Chris Lattnera6f074f2009-08-23 03:41:05 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetMachine.h"
Bob Wilson2f9be502009-10-15 20:49:47 +000035#include <algorithm>
Evan Cheng10043e22007-01-19 07:51:42 +000036using namespace llvm;
37
Chandler Carruth84e68b22014-04-22 02:41:26 +000038#define DEBUG_TYPE "arm-cp-islands"
39
Evan Chengdb73d682009-08-14 00:32:16 +000040STATISTIC(NumCPEs, "Number of constpool entries");
41STATISTIC(NumSplit, "Number of uncond branches inserted");
42STATISTIC(NumCBrFixed, "Number of cond branches fixed");
43STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
44STATISTIC(NumTBs, "Number of table branches generated");
45STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Chenge41903b2009-08-14 18:31:44 +000046STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Cheng6f29ad92009-10-31 23:46:45 +000047STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000048STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach5d577142009-11-12 17:25:07 +000049STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000050
51
52static cl::opt<bool>
Jim Grosbachcdde77c2009-11-17 21:24:11 +000053AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach8d92ec42009-11-11 02:47:19 +000054 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Cheng10043e22007-01-19 07:51:42 +000055
Jakob Stoklund Olesen2a05f692011-12-16 16:07:41 +000056// FIXME: This option should be removed once it has received sufficient testing.
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +000057static cl::opt<bool>
Jakob Stoklund Olesencba8e8c2011-12-15 22:14:45 +000058AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(true),
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +000059 cl::desc("Align constant islands in code"));
60
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +000061/// UnknownPadding - Return the worst case padding that could result from
62/// unknown offset bits. This does not include alignment padding caused by
63/// known offset bits.
64///
65/// @param LogAlign log2(alignment)
66/// @param KnownBits Number of known low offset bits.
67static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
68 if (KnownBits < LogAlign)
69 return (1u << LogAlign) - (1u << KnownBits);
70 return 0;
71}
72
Evan Cheng10043e22007-01-19 07:51:42 +000073namespace {
Dale Johannesene18b13b2007-02-23 05:02:36 +000074 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Cheng10043e22007-01-19 07:51:42 +000075 /// requires constant pool entries to be scattered among the instructions
76 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesene18b13b2007-02-23 05:02:36 +000077 /// constant pool; instead, it places constants wherever it feels like with
Evan Cheng10043e22007-01-19 07:51:42 +000078 /// special instructions.
79 ///
80 /// The terminology used in this pass includes:
81 /// Islands - Clumps of constants placed in the function.
82 /// Water - Potential places where an island could be formed.
83 /// CPE - A constant pool entry that has been placed somewhere, which
84 /// tracks a list of users.
Nick Lewycky02d5f772009-10-25 06:33:48 +000085 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000086 /// BasicBlockInfo - Information about the offset and size of a single
87 /// basic block.
88 struct BasicBlockInfo {
89 /// Offset - Distance from the beginning of the function to the beginning
90 /// of this basic block.
91 ///
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +000092 /// Offsets are computed assuming worst case padding before an aligned
93 /// block. This means that subtracting basic block offsets always gives a
94 /// conservative estimate of the real distance which may be smaller.
95 ///
96 /// Because worst case padding is used, the computed offset of an aligned
97 /// block may not actually be aligned.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000098 unsigned Offset;
Bob Wilson2f4e56f2009-05-12 17:09:30 +000099
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000100 /// Size - Size of the basic block in bytes. If the block contains
101 /// inline assembly, this is a worst case estimate.
102 ///
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000103 /// The size does not include any alignment padding whether from the
104 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000105 unsigned Size;
106
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000107 /// KnownBits - The number of low bits in Offset that are known to be
108 /// exact. The remaining bits of Offset are an upper bound.
109 uint8_t KnownBits;
110
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000111 /// Unalign - When non-zero, the block contains instructions (inline asm)
112 /// of unknown size. The real size may be smaller than Size bytes by a
113 /// multiple of 1 << Unalign.
114 uint8_t Unalign;
115
116 /// PostAlign - When non-zero, the block terminator contains a .align
117 /// directive, so the end of the block is aligned to 1 << PostAlign
118 /// bytes.
119 uint8_t PostAlign;
120
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000121 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
122 PostAlign(0) {}
Jakob Stoklund Olesenaf748e12011-12-07 01:22:52 +0000123
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +0000124 /// Compute the number of known offset bits internally to this block.
125 /// This number should be used to predict worst case padding when
126 /// splitting the block.
127 unsigned internalKnownBits() const {
Jakob Stoklund Olesen8503ba92012-04-30 20:19:00 +0000128 unsigned Bits = Unalign ? Unalign : KnownBits;
129 // If the block size isn't a multiple of the known bits, assume the
130 // worst case padding.
131 if (Size & ((1u << Bits) - 1))
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000132 Bits = countTrailingZeros(Size);
Jakob Stoklund Olesen8503ba92012-04-30 20:19:00 +0000133 return Bits;
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +0000134 }
135
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000136 /// Compute the offset immediately following this block. If LogAlign is
137 /// specified, return the offset the successor block will get if it has
138 /// this alignment.
139 unsigned postOffset(unsigned LogAlign = 0) const {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000140 unsigned PO = Offset + Size;
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000141 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
142 if (!LA)
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000143 return PO;
144 // Add alignment padding from the terminator.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +0000145 return PO + UnknownPadding(LA, internalKnownBits());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000146 }
147
148 /// Compute the number of known low bits of postOffset. If this block
149 /// contains inline asm, the number of known bits drops to the
150 /// instruction alignment. An aligned terminator may increase the number
151 /// of know bits.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000152 /// If LogAlign is given, also consider the alignment of the next block.
153 unsigned postKnownBits(unsigned LogAlign = 0) const {
154 return std::max(std::max(unsigned(PostAlign), LogAlign),
155 internalKnownBits());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000156 }
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000157 };
158
159 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen01ee5752007-02-25 00:47:03 +0000160
Evan Cheng10043e22007-01-19 07:51:42 +0000161 /// WaterList - A sorted list of basic blocks where islands could be placed
162 /// (i.e. blocks that don't fall through to the following block, due
163 /// to a return, unreachable, or unconditional branch).
Evan Cheng540f5e02007-02-09 23:59:14 +0000164 std::vector<MachineBasicBlock*> WaterList;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000165
Bob Wilson2f9be502009-10-15 20:49:47 +0000166 /// NewWaterList - The subset of WaterList that was created since the
167 /// previous iteration by inserting unconditional branches.
168 SmallSet<MachineBasicBlock*, 4> NewWaterList;
169
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000170 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
171
Evan Cheng10043e22007-01-19 07:51:42 +0000172 /// CPUser - One user of a constant pool, keeping the machine instruction
173 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson68ead6c2009-10-15 05:52:29 +0000174 /// allowed from the instruction to the CP. The HighWaterMark records the
175 /// highest basic block where a new CPEntry can be placed. To ensure this
176 /// pass terminates, the CP entries are initially placed at the end of the
177 /// function and then move monotonically to lower addresses. The
178 /// exception to this rule is when the current CP entry for a particular
179 /// CPUser is out of range, but there is another CP entry for the same
180 /// constant value in range. We want to use the existing in-range CP
181 /// entry, but if it later moves out of range, the search for new water
182 /// should resume where it left off. The HighWaterMark is used to record
183 /// that point.
Evan Cheng10043e22007-01-19 07:51:42 +0000184 struct CPUser {
185 MachineInstr *MI;
186 MachineInstr *CPEMI;
Bob Wilson68ead6c2009-10-15 05:52:29 +0000187 MachineBasicBlock *HighWaterMark;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000188 private:
Evan Cheng10043e22007-01-19 07:51:42 +0000189 unsigned MaxDisp;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000190 public:
Evan Cheng87aaa192009-07-21 23:56:01 +0000191 bool NegOk;
Evan Chengd2919a12009-07-23 18:27:47 +0000192 bool IsSoImm;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000193 bool KnownAlignment;
Evan Chengd2919a12009-07-23 18:27:47 +0000194 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
195 bool neg, bool soimm)
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000196 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
197 KnownAlignment(false) {
Bob Wilson68ead6c2009-10-15 05:52:29 +0000198 HighWaterMark = CPEMI->getParent();
199 }
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000200 /// getMaxDisp - Returns the maximum displacement supported by MI.
201 /// Correct for unknown alignment.
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000202 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000203 unsigned getMaxDisp() const {
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000204 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000205 }
Evan Cheng10043e22007-01-19 07:51:42 +0000206 };
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000207
Evan Cheng10043e22007-01-19 07:51:42 +0000208 /// CPUsers - Keep track of all of the machine instructions that use various
209 /// constant pools and their max displacement.
Evan Cheng540f5e02007-02-09 23:59:14 +0000210 std::vector<CPUser> CPUsers;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000211
Evan Cheng8b7700f2007-02-09 20:54:44 +0000212 /// CPEntry - One per constant pool entry, keeping the machine instruction
213 /// pointer, the constpool index, and the number of CPUser's which
214 /// reference this entry.
215 struct CPEntry {
216 MachineInstr *CPEMI;
217 unsigned CPI;
218 unsigned RefCount;
219 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
220 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
221 };
222
223 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesene18b13b2007-02-23 05:02:36 +0000224 /// instructions. For each original constpool index (i.e. those that
225 /// existed upon entry to this pass), it keeps a vector of entries.
226 /// Original elements are cloned as we go along; the clones are
227 /// put in the vector of the original element, but have distinct CPIs.
Evan Cheng8b7700f2007-02-09 20:54:44 +0000228 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000229
Evan Cheng22c7cf52007-01-25 03:12:46 +0000230 /// ImmBranch - One per immediate branch, keeping the machine instruction
231 /// pointer, conditional or unconditional, the max displacement,
232 /// and (if isCond is true) the corresponding unconditional branch
233 /// opcode.
234 struct ImmBranch {
235 MachineInstr *MI;
Evan Cheng010ae382007-01-25 23:18:59 +0000236 unsigned MaxDisp : 31;
237 bool isCond : 1;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000238 int UncondBr;
Evan Cheng010ae382007-01-25 23:18:59 +0000239 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
240 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Cheng22c7cf52007-01-25 03:12:46 +0000241 };
242
Evan Chengc95f95b2007-05-16 05:14:06 +0000243 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Cheng22c7cf52007-01-25 03:12:46 +0000244 ///
Evan Cheng540f5e02007-02-09 23:59:14 +0000245 std::vector<ImmBranch> ImmBranches;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000246
Evan Cheng7fa69642007-01-30 01:18:38 +0000247 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
248 ///
Evan Cheng8b7700f2007-02-09 20:54:44 +0000249 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Cheng7fa69642007-01-30 01:18:38 +0000250
Evan Chengc6d70ae2009-07-29 02:18:14 +0000251 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
252 SmallVector<MachineInstr*, 4> T2JumpTables;
253
Evan Cheng7fa69642007-01-30 01:18:38 +0000254 /// HasFarJump - True if any far jump instruction has been emitted during
255 /// the branch fix up pass.
256 bool HasFarJump;
257
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000258 MachineFunction *MF;
259 MachineConstantPool *MCP;
Craig Topper07720d82012-03-25 23:49:58 +0000260 const ARMBaseInstrInfo *TII;
Evan Chenge64f48b2009-08-01 06:13:52 +0000261 const ARMSubtarget *STI;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000262 ARMFunctionInfo *AFI;
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000263 bool isThumb;
Evan Chengd2919a12009-07-23 18:27:47 +0000264 bool isThumb1;
David Goodwin27303cd2009-06-30 18:04:13 +0000265 bool isThumb2;
Evan Cheng10043e22007-01-19 07:51:42 +0000266 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000267 static char ID;
Owen Andersona7aed182010-08-06 18:33:48 +0000268 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +0000269
Craig Topper6bc27bf2014-03-10 02:09:33 +0000270 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng10043e22007-01-19 07:51:42 +0000271
Craig Topper6bc27bf2014-03-10 02:09:33 +0000272 const char *getPassName() const override {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000273 return "ARM constant island placement and branch shortening pass";
Evan Cheng10043e22007-01-19 07:51:42 +0000274 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000275
Evan Cheng10043e22007-01-19 07:51:42 +0000276 private:
Jim Grosbach190e7b62012-03-23 23:07:03 +0000277 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000278 bool BBHasFallthrough(MachineBasicBlock *MBB);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000279 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000280 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000281 void scanFunctionJumpTables();
282 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
283 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
284 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
285 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
286 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
287 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
288 bool findAvailableWater(CPUser&U, unsigned UserOffset,
289 water_iterator &WaterIter);
290 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000291 MachineBasicBlock *&NewMBB);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000292 bool handleConstantPoolUser(unsigned CPUserIndex);
293 void removeDeadCPEMI(MachineInstr *CPEMI);
294 bool removeUnusedCPEntries();
295 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
296 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
297 bool DoDump = false);
298 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000299 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000300 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
301 bool fixupImmediateBr(ImmBranch &Br);
302 bool fixupConditionalBr(ImmBranch &Br);
303 bool fixupUnconditionalBr(ImmBranch &Br);
304 bool undoLRSpillRestore();
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000305 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
Jim Grosbach190e7b62012-03-23 23:07:03 +0000306 bool optimizeThumb2Instructions();
307 bool optimizeThumb2Branches();
308 bool reorderThumb2JumpTables();
309 bool optimizeThumb2JumpTables();
310 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000311 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000312
Jim Grosbach190e7b62012-03-23 23:07:03 +0000313 void computeBlockSize(MachineBasicBlock *MBB);
314 unsigned getOffsetOf(MachineInstr *MI) const;
315 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000316 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000317 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000318
Jim Grosbach190e7b62012-03-23 23:07:03 +0000319 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000320 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000321 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000322 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000323 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000324 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000325 }
Evan Cheng10043e22007-01-19 07:51:42 +0000326 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000327 char ARMConstantIslands::ID = 0;
Evan Cheng10043e22007-01-19 07:51:42 +0000328}
329
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000330/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000331void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000332#ifndef NDEBUG
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000333 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd2919a12009-07-23 18:27:47 +0000334 MBBI != E; ++MBBI) {
335 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesenbd97f5d2011-12-08 01:10:05 +0000336 unsigned MBBId = MBB->getNumber();
Jakob Stoklund Olesenbd97f5d2011-12-08 01:10:05 +0000337 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000338 }
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000339 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000340 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
341 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000342 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000343 // Verify offset using the real max displacement without the safety
344 // adjustment.
345 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000346 /* DoDump = */ true)) {
347 DEBUG(dbgs() << "OK\n");
348 continue;
349 }
350 DEBUG(dbgs() << "Out of range.\n");
351 dumpBBs();
352 DEBUG(MF->dump());
353 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000354 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000355#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000356}
357
358/// print block size and offset information - debugging
359void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000360 DEBUG({
361 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
362 const BasicBlockInfo &BBI = BBInfo[J];
363 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
364 << " kb=" << unsigned(BBI.KnownBits)
365 << " ua=" << unsigned(BBI.Unalign)
366 << " pa=" << unsigned(BBI.PostAlign)
367 << format(" size=%#x\n", BBInfo[J].Size);
368 }
369 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000370}
371
Evan Cheng22c7cf52007-01-25 03:12:46 +0000372/// createARMConstantIslandPass - returns an instance of the constpool
373/// island pass.
Evan Cheng10043e22007-01-19 07:51:42 +0000374FunctionPass *llvm::createARMConstantIslandPass() {
375 return new ARMConstantIslands();
376}
377
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000378bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
379 MF = &mf;
380 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000381
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000382 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000383 << MCP->getConstants().size() << " CP entries, aligned to "
384 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000385
Eric Christopherd9134482014-08-04 21:25:23 +0000386 TII = (const ARMBaseInstrInfo *)MF->getTarget()
387 .getSubtargetImpl()
388 ->getInstrInfo();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000389 AFI = MF->getInfo<ARMFunctionInfo>();
390 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000391
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000392 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000393 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000394 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000395
396 HasFarJump = false;
397
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000398 // This pass invalidates liveness information when it splits basic blocks.
399 MF->getRegInfo().invalidateLiveness();
400
Evan Cheng10043e22007-01-19 07:51:42 +0000401 // Renumber all of the machine basic blocks in the function, guaranteeing that
402 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000403 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000404
Jim Grosbach5d577142009-11-12 17:25:07 +0000405 // Try to reorder and otherwise adjust the block layout to make good use
406 // of the TB[BH] instructions.
407 bool MadeChange = false;
408 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000409 scanFunctionJumpTables();
410 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000411 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000412 T2JumpTables.clear();
413 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000414 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000415 }
416
Evan Chengf6d0fa32009-07-31 18:28:05 +0000417 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd2919a12009-07-23 18:27:47 +0000418 // This is so we can keep exact track of where the alignment padding goes.
419
Chris Lattnerfeba1e22010-01-27 23:37:36 +0000420 // ARM and Thumb2 functions need to be 4-byte aligned.
421 if (!isThumb1)
Chad Rosier73b02822012-07-06 23:13:38 +0000422 MF->ensureAlignment(2); // 2 = log2(4)
Dale Johannesenfdfb7572007-04-23 20:09:04 +0000423
Evan Cheng10043e22007-01-19 07:51:42 +0000424 // Perform the initial placement of the constant pool entries. To start with,
425 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000426 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000427 if (!MCP->isEmpty())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000428 doInitialPlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000429
Evan Cheng10043e22007-01-19 07:51:42 +0000430 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000431 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000432
Evan Cheng10043e22007-01-19 07:51:42 +0000433 // Do the initial scan of the function, building up information about the
434 // sizes of each block, the location of all the water, and finding all of the
435 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000436 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000437 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000438 DEBUG(dumpBBs());
439
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000440
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000441 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000442 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000443
Evan Cheng7fa69642007-01-30 01:18:38 +0000444 // Iteratively place constant pool entries and fix up branches until there
445 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000446 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000447 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000448 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000449 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000450 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000451 CPChange |= handleConstantPoolUser(i);
Evan Cheng82ff0222009-08-07 07:35:21 +0000452 if (CPChange && ++NoCPIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000453 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000454 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000455
Bob Wilson2f9be502009-10-15 20:49:47 +0000456 // Clear NewWaterList now. If we split a block for branches, it should
457 // appear as "new water" for the next iteration of constant pool placement.
458 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000459
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000460 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000461 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000462 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000463 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000464 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000465 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000466 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000467
468 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000469 break;
470 MadeChange = true;
471 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000472
Evan Chengdb73d682009-08-14 00:32:16 +0000473 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000474 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000475 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000476
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000477 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000478 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000479
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000480 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
481 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000482 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000483 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000484
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000485 // Save the mapping between original and cloned constpool entries.
486 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
487 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
488 const CPEntry & CPE = CPEntries[i][j];
489 AFI->recordCPEClone(i, CPE.CPI);
490 }
491 }
492
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000493 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000494
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000495 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000496 WaterList.clear();
497 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000498 CPEntries.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000499 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000500 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000501 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000502
503 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000504}
505
Jim Grosbach190e7b62012-03-23 23:07:03 +0000506/// doInitialPlacement - Perform the initial placement of the constant pool
Evan Cheng10043e22007-01-19 07:51:42 +0000507/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000508void
Jim Grosbach190e7b62012-03-23 23:07:03 +0000509ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000510 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000511 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
512 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000513
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000514 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000515 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000516
517 // Mark the basic block as required by the const-pool.
518 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
519 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
520
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000521 // The function needs to be as aligned as the basic blocks. The linker may
522 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000523 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000524
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000525 // Order the entries in BB by descending alignment. That ensures correct
526 // alignment of all entries as long as BB is sufficiently aligned. Keep
527 // track of the insertion point for each alignment. We are going to bucket
528 // sort the entries as they are created.
529 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000530
Evan Cheng10043e22007-01-19 07:51:42 +0000531 // Add all of the constants from the constant pool to the end block, use an
532 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000533 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000534
Eric Christopherfc6de422014-08-05 02:39:49 +0000535 const DataLayout &TD = *MF->getSubtarget().getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000536 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000537 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000538 assert(Size >= 4 && "Too small constant pool entry");
539 unsigned Align = CPs[i].getAlignment();
540 assert(isPowerOf2_32(Align) && "Invalid alignment");
541 // Verify that all constant pool entries are a multiple of their alignment.
542 // If not, we would have to pad them out so that instructions stay aligned.
543 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
544
545 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
546 unsigned LogAlign = Log2_32(Align);
547 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000548 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000549 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000550 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000551 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000552
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000553 // Ensure that future entries with higher alignment get inserted before
554 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000555 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000556 if (InsPoint[a] == InsAt)
557 InsPoint[a] = CPEMI;
558
Evan Cheng8b7700f2007-02-09 20:54:44 +0000559 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000560 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000561 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000562 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
563 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000564 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000565 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000566}
567
Dale Johannesene18b13b2007-02-23 05:02:36 +0000568/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000569/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000570bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000571 // Get the next machine basic block in the function.
572 MachineFunction::iterator MBBI = MBB;
Jim Grosbach84511e12010-06-02 21:53:11 +0000573 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000574 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000575 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000576
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000577 MachineBasicBlock *NextBB = std::next(MBBI);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000578 if (std::find(MBB->succ_begin(), MBB->succ_end(), NextBB) == MBB->succ_end())
579 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000580
Tim Northoverab85dcc2014-11-13 17:58:51 +0000581 // Try to analyze the end of the block. A potential fallthrough may already
582 // have an unconditional branch for whatever reason.
583 MachineBasicBlock *TBB, *FBB;
584 SmallVector<MachineOperand, 4> Cond;
585 bool TooDifficult = TII->AnalyzeBranch(*MBB, TBB, FBB, Cond);
586 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000587}
588
Evan Cheng8b7700f2007-02-09 20:54:44 +0000589/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
590/// look up the corresponding CPEntry.
591ARMConstantIslands::CPEntry
592*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
593 const MachineInstr *CPEMI) {
594 std::vector<CPEntry> &CPEs = CPEntries[CPI];
595 // Number of entries per constpool index should be small, just do a
596 // linear search.
597 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
598 if (CPEs[i].CPEMI == CPEMI)
599 return &CPEs[i];
600 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000601 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000602}
603
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000604/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000605/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000606unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
607 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
608
609 // Everything is 4-byte aligned unless AlignConstantIslands is set.
610 if (!AlignConstantIslands)
611 return 2;
612
613 unsigned CPI = CPEMI->getOperand(1).getIndex();
614 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
615 unsigned Align = MCP->getConstants()[CPI].getAlignment();
616 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
617 return Log2_32(Align);
618}
619
Jim Grosbach190e7b62012-03-23 23:07:03 +0000620/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000621/// information about the sizes of each block and the locations of all
622/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000623void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000624 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach5d577142009-11-12 17:25:07 +0000625 MBBI != E; ++MBBI) {
626 MachineBasicBlock &MBB = *MBBI;
627
Jim Grosbach5d577142009-11-12 17:25:07 +0000628 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach9785e592009-11-16 18:58:52 +0000629 I != E; ++I)
Evan Cheng7f8e5632011-12-07 07:15:52 +0000630 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach9785e592009-11-16 18:58:52 +0000631 T2JumpTables.push_back(I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000632 }
633}
634
Jim Grosbach190e7b62012-03-23 23:07:03 +0000635/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000636/// information about the sizes of each block, the location of all the water,
637/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000638void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000639initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000640 BBInfo.clear();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000641 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000642
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000643 // First thing, compute the size of all basic blocks, and see if the function
644 // has any inline assembly in it. If so, we have to be conservative about
645 // alignment assumptions, as we don't know for sure the size of any
646 // instructions in the inline assembly.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000647 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000648 computeBlockSize(I);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000649
650 // The known bits of the entry block offset are determined by the function
651 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000652 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000653
654 // Compute block offsets and known bits.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000655 adjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000656
Bill Wendling18581a42010-12-21 01:54:40 +0000657 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000658 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Cheng10043e22007-01-19 07:51:42 +0000659 MBBI != E; ++MBBI) {
660 MachineBasicBlock &MBB = *MBBI;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000661
Evan Cheng10043e22007-01-19 07:51:42 +0000662 // If this block doesn't fall through into the next MBB, then this is
663 // 'water' that a constant pool island could be placed.
664 if (!BBHasFallthrough(&MBB))
665 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000666
Evan Cheng10043e22007-01-19 07:51:42 +0000667 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
668 I != E; ++I) {
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000669 if (I->isDebugValue())
670 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000671
Evan Cheng22c7cf52007-01-25 03:12:46 +0000672 int Opc = I->getOpcode();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000673 if (I->isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000674 bool isCond = false;
675 unsigned Bits = 0;
676 unsigned Scale = 1;
677 int UOpc = Opc;
678 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000679 default:
680 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000681 case ARM::t2BR_JT:
682 T2JumpTables.push_back(I);
683 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000684 case ARM::Bcc:
685 isCond = true;
686 UOpc = ARM::B;
687 // Fallthrough
688 case ARM::B:
689 Bits = 24;
690 Scale = 4;
691 break;
692 case ARM::tBcc:
693 isCond = true;
694 UOpc = ARM::tB;
695 Bits = 8;
696 Scale = 2;
697 break;
698 case ARM::tB:
699 Bits = 11;
700 Scale = 2;
701 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000702 case ARM::t2Bcc:
703 isCond = true;
704 UOpc = ARM::t2B;
705 Bits = 20;
706 Scale = 2;
707 break;
708 case ARM::t2B:
709 Bits = 24;
710 Scale = 2;
711 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000712 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000713
714 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000715 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengf9a4c692007-02-01 10:16:15 +0000716 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000717 }
718
Evan Cheng7fa69642007-01-30 01:18:38 +0000719 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
720 PushPopMIs.push_back(I);
721
Evan Chengd2919a12009-07-23 18:27:47 +0000722 if (Opc == ARM::CONSTPOOL_ENTRY)
723 continue;
724
Evan Cheng10043e22007-01-19 07:51:42 +0000725 // Scan the instructions for constant pool operands.
726 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000727 if (I->getOperand(op).isCPI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000728 // We found one. The addressing mode tells us the max displacement
729 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000730
Evan Cheng10043e22007-01-19 07:51:42 +0000731 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000732 unsigned Bits = 0;
733 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000734 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000735 bool IsSoImm = false;
736
737 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000738 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000739 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000740
741 // Taking the address of a CP entry.
742 case ARM::LEApcrel:
743 // This takes a SoImm, which is 8 bit immediate rotated. We'll
744 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000745 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000746 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000747 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000748 Scale = 4;
749 NegOk = true;
750 IsSoImm = true;
751 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000752 case ARM::t2LEApcrel:
Evan Chengd2919a12009-07-23 18:27:47 +0000753 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000754 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000755 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000756 case ARM::tLEApcrel:
757 Bits = 8;
758 Scale = 4;
759 break;
760
David Majnemer452f1f92013-06-04 17:46:15 +0000761 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000762 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000763 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000764 case ARM::t2LDRpci:
Evan Chengfd522992007-02-01 20:44:52 +0000765 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000766 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000767 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000768
769 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000770 Bits = 8;
771 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000772 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000773
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000774 case ARM::VLDRD:
775 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000776 Bits = 8;
777 Scale = 4; // +-(offset_8*4)
778 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000779 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000780 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000781
Evan Cheng10043e22007-01-19 07:51:42 +0000782 // Remember that this is a user of a CP entry.
Chris Lattnera5bb3702007-12-30 23:10:15 +0000783 unsigned CPI = I->getOperand(op).getIndex();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000784 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000785 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd2919a12009-07-23 18:27:47 +0000786 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000787
788 // Increment corresponding CPEntry reference count.
789 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
790 assert(CPE && "Cannot find a corresponding CPEntry!");
791 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000792
Evan Cheng10043e22007-01-19 07:51:42 +0000793 // Instructions can only use one CP entry, don't bother scanning the
794 // rest of the operands.
795 break;
796 }
797 }
Evan Cheng10043e22007-01-19 07:51:42 +0000798 }
799}
800
Jim Grosbach190e7b62012-03-23 23:07:03 +0000801/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000802/// This function updates BBInfo directly.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000803void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000804 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
805 BBI.Size = 0;
806 BBI.Unalign = 0;
807 BBI.PostAlign = 0;
808
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000809 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
810 ++I) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000811 BBI.Size += TII->GetInstSizeInBytes(I);
812 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
813 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesen14e024d2011-12-08 01:22:39 +0000814 if (I->isInlineAsm())
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000815 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000816 // Also consider instructions that may be shrunk later.
817 else if (isThumb && mayOptimizeThumb2Instruction(I))
818 BBI.Unalign = 1;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000819 }
820
821 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000822 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000823 BBI.PostAlign = 2;
Chad Rosier73b02822012-07-06 23:13:38 +0000824 MBB->getParent()->ensureAlignment(2);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000825 }
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000826}
827
Jim Grosbach190e7b62012-03-23 23:07:03 +0000828/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000829/// from the start of the function. This offset changes as stuff is moved
830/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000831unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000832 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000833
Evan Cheng10043e22007-01-19 07:51:42 +0000834 // The offset is composed of two things: the sum of the sizes of all MBB's
835 // before this instruction's block, and the offset from the start of the block
836 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000837 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000838
839 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000840 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000841 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +0000842 Offset += TII->GetInstSizeInBytes(I);
Evan Cheng10043e22007-01-19 07:51:42 +0000843 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000844 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000845}
846
847/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
848/// ID.
849static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
850 const MachineBasicBlock *RHS) {
851 return LHS->getNumber() < RHS->getNumber();
852}
853
Jim Grosbach190e7b62012-03-23 23:07:03 +0000854/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000855/// machine function, it upsets all of the block numbers. Renumber the blocks
856/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000857void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000858 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000859 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000860
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000861 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000862 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000863 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000864
865 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000866 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000867 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000868 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
869 CompareMBBNumbers);
870 WaterList.insert(IP, NewBB);
871}
872
873
874/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000875/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000876/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000877MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000878 MachineBasicBlock *OrigBB = MI->getParent();
879
880 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000881 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000882 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Cheng10043e22007-01-19 07:51:42 +0000883 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000884 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000885
Evan Cheng10043e22007-01-19 07:51:42 +0000886 // Splice the instructions starting with MI over to NewBB.
887 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000888
Evan Cheng10043e22007-01-19 07:51:42 +0000889 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000890 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000891 // There doesn't seem to be meaningful DebugInfo available; this doesn't
892 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000893 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000894 if (!isThumb)
895 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
896 else
897 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
898 .addImm(ARMCC::AL).addReg(0);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000899 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000900
Evan Cheng10043e22007-01-19 07:51:42 +0000901 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000902 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000903
Evan Cheng10043e22007-01-19 07:51:42 +0000904 // OrigBB branches to NewBB.
905 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000906
Evan Cheng10043e22007-01-19 07:51:42 +0000907 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000908 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000909 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000910 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000911
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000912 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000913 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000914 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000915
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000916 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000917 // available water after it (but not if it's already there, which happens
918 // when splitting before a conditional branch that is followed by an
919 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000920 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +0000921 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
922 CompareMBBNumbers);
923 MachineBasicBlock* WaterBB = *IP;
924 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000925 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000926 else
927 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000928 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000929
Dale Johannesenc17dd572010-07-23 22:50:23 +0000930 // Figure out how large the OrigBB is. As the first half of the original
931 // block, it cannot contain a tablejump. The size includes
932 // the new jump we added. (It should be possible to do this without
933 // recounting everything, but it's very confusing, and this is rarely
934 // executed.)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000935 computeBlockSize(OrigBB);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000936
Dale Johannesenc17dd572010-07-23 22:50:23 +0000937 // Figure out how large the NewMBB is. As the second half of the original
938 // block, it may contain a tablejump.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000939 computeBlockSize(NewBB);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000940
Dale Johannesen01ee5752007-02-25 00:47:03 +0000941 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000942 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000943
944 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000945}
946
Jim Grosbach190e7b62012-03-23 23:07:03 +0000947/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000948/// displacement computation. Update U.KnownAlignment to match its current
949/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000950unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
951 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000952 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
953 unsigned KnownBits = BBI.internalKnownBits();
954
955 // The value read from PC is offset from the actual instruction address.
956 UserOffset += (isThumb ? 4 : 8);
957
958 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
959 // Make sure U.getMaxDisp() returns a constrained range.
960 U.KnownAlignment = (KnownBits >= 2);
961
962 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
963 // purposes of the displacement computation; compensate for that here.
964 // For unknown alignments, getMaxDisp() constrains the range instead.
965 if (isThumb && U.KnownAlignment)
966 UserOffset &= ~3u;
967
968 return UserOffset;
969}
970
Jim Grosbach190e7b62012-03-23 23:07:03 +0000971/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000972/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000973/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +0000974/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000975/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
976/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000977bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +0000978 unsigned TrialOffset, unsigned MaxDisp,
979 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +0000980 if (UserOffset <= TrialOffset) {
981 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +0000982 if (TrialOffset - UserOffset <= MaxDisp)
983 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000984 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000985 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +0000986 if (UserOffset - TrialOffset <= MaxDisp)
987 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000988 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000989 }
990 return false;
991}
992
Jim Grosbach190e7b62012-03-23 23:07:03 +0000993/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +0000994/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000995///
996/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000997bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000998 MachineBasicBlock* Water, CPUser &U,
999 unsigned &Growth) {
1000 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1001 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1002 unsigned NextBlockOffset, NextBlockAlignment;
1003 MachineFunction::const_iterator NextBlock = Water;
1004 if (++NextBlock == MF->end()) {
1005 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1006 NextBlockAlignment = 0;
1007 } else {
1008 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1009 NextBlockAlignment = NextBlock->getAlignment();
1010 }
1011 unsigned Size = U.CPEMI->getOperand(2).getImm();
1012 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001013
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001014 // The CPE may be able to hide in the alignment padding before the next
1015 // block. It may also cause more padding to be required if it is more aligned
1016 // that the next block.
1017 if (CPEEnd > NextBlockOffset) {
1018 Growth = CPEEnd - NextBlockOffset;
1019 // Compute the padding that would go at the end of the CPE to align the next
1020 // block.
1021 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1022
1023 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001024 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001025 // in blocks between CPE and the user.
1026 if (CPEOffset < UserOffset)
1027 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1028 } else
1029 // CPE fits in existing padding.
1030 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001031
Jim Grosbach190e7b62012-03-23 23:07:03 +00001032 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001033}
1034
Jim Grosbach190e7b62012-03-23 23:07:03 +00001035/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001036/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001037bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001038 MachineInstr *CPEMI, unsigned MaxDisp,
1039 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001040 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001041
Dale Johannesene18b13b2007-02-23 05:02:36 +00001042 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001043 DEBUG({
1044 unsigned Block = MI->getParent()->getNumber();
1045 const BasicBlockInfo &BBI = BBInfo[Block];
1046 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1047 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001048 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001049 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001050 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1051 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1052 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001053 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001054 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001055
Jim Grosbach190e7b62012-03-23 23:07:03 +00001056 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001057}
1058
Evan Chenge4510972009-01-28 00:53:34 +00001059#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001060/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1061/// unconditionally branches to its only successor.
1062static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1063 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1064 return false;
1065
1066 MachineBasicBlock *Succ = *MBB->succ_begin();
1067 MachineBasicBlock *Pred = *MBB->pred_begin();
1068 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001069 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1070 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001071 return PredMI->getOperand(0).getMBB() == Succ;
1072 return false;
1073}
Evan Chenge4510972009-01-28 00:53:34 +00001074#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001075
Jim Grosbach190e7b62012-03-23 23:07:03 +00001076void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001077 unsigned BBNum = BB->getNumber();
1078 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001079 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001080 // Include the alignment of the current block.
1081 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1082 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1083 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001084
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001085 // This is where block i begins. Stop if the offset is already correct,
1086 // and we have updated 2 blocks. This is the maximum number of blocks
1087 // changed before calling this function.
1088 if (i > BBNum + 2 &&
1089 BBInfo[i].Offset == Offset &&
1090 BBInfo[i].KnownBits == KnownBits)
1091 break;
1092
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001093 BBInfo[i].Offset = Offset;
1094 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001095 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001096}
1097
Jim Grosbach190e7b62012-03-23 23:07:03 +00001098/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001099/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001100/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001101/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001102
Jim Grosbach190e7b62012-03-23 23:07:03 +00001103bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1104 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001105 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001106 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1107 assert(CPE && "Unexpected!");
1108 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001109 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001110 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001111 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001112 return true;
1113 }
1114 return false;
1115}
1116
Dale Johannesene18b13b2007-02-23 05:02:36 +00001117/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1118/// if not, see if an in-range clone of the CPE is in range, and if so,
1119/// change the data structures so the user references the clone. Returns:
1120/// 0 = no existing entry found
1121/// 1 = entry found, and there were no code insertions or deletions
1122/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001123int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001124{
1125 MachineInstr *UserMI = U.MI;
1126 MachineInstr *CPEMI = U.CPEMI;
1127
1128 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001129 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1130 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001131 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001132 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001133 }
1134
Dale Johannesene18b13b2007-02-23 05:02:36 +00001135 // No. Look for previously created clones of the CPE that are in range.
Chris Lattnera5bb3702007-12-30 23:10:15 +00001136 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001137 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1138 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1139 // We already tried this one
1140 if (CPEs[i].CPEMI == CPEMI)
1141 continue;
1142 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001143 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001144 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001145 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001146 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001147 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001148 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001149 // Point the CPUser node to the replacement
1150 U.CPEMI = CPEs[i].CPEMI;
1151 // Change the CPI in the instruction operand to refer to the clone.
1152 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001153 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001154 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001155 break;
1156 }
1157 // Adjust the refcount of the clone...
1158 CPEs[i].RefCount++;
1159 // ...and the original. If we didn't remove the old entry, none of the
1160 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001161 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001162 }
1163 }
1164 return 0;
1165}
1166
Dale Johannesen440995b2007-02-28 18:41:23 +00001167/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1168/// the specific unconditional branch instruction.
1169static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001170 switch (Opc) {
1171 case ARM::tB:
1172 return ((1<<10)-1)*2;
1173 case ARM::t2B:
1174 return ((1<<23)-1)*2;
1175 default:
1176 break;
1177 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001178
David Goodwin27303cd2009-06-30 18:04:13 +00001179 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001180}
1181
Jim Grosbach190e7b62012-03-23 23:07:03 +00001182/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001183/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001184/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001185/// is set to the WaterList entry. For Thumb, prefer water that will not
1186/// introduce padding to water that will. To ensure that this pass
1187/// terminates, the CPE location for a particular CPUser is only allowed to
1188/// move to a lower address, so search backward from the end of the list and
1189/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001190bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Bob Wilson2f9be502009-10-15 20:49:47 +00001191 water_iterator &WaterIter) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001192 if (WaterList.empty())
1193 return false;
1194
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001195 unsigned BestGrowth = ~0u;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001196 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001197 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001198 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001199 // Check if water is in range and is either at a lower address than the
1200 // current "high water mark" or a new water block that was created since
1201 // the previous iteration by inserting an unconditional branch. In the
1202 // latter case, we want to allow resetting the high water mark back to
1203 // this new water since we haven't seen it before. Inserting branches
1204 // should be relatively uncommon and when it does happen, we want to be
1205 // sure to take advantage of it for all the CPEs near that block, so that
1206 // we don't insert more branches than necessary.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001207 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001208 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001209 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001210 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1211 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001212 // This is the least amount of required padding seen so far.
1213 BestGrowth = Growth;
1214 WaterIter = IP;
1215 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1216 << " Growth=" << Growth << '\n');
1217
1218 // Keep looking unless it is perfect.
1219 if (BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001220 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001221 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001222 if (IP == B)
1223 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001224 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001225 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001226}
1227
Jim Grosbach190e7b62012-03-23 23:07:03 +00001228/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001229/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1230/// block is used if in range, and the conditional branch munged so control
1231/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001232/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001233/// block following which the new island can be inserted (the WaterList
1234/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001235void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001236 unsigned UserOffset,
1237 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001238 CPUser &U = CPUsers[CPUserIndex];
1239 MachineInstr *UserMI = U.MI;
1240 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001241 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001242 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001243 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001244
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001245 // If the block does not end in an unconditional branch already, and if the
1246 // end of the block is within range, make new water there. (The addition
1247 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001248 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001249 if (BBHasFallthrough(UserMBB)) {
1250 // Size of branch to insert.
1251 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001252 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001253 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001254
Jim Grosbach190e7b62012-03-23 23:07:03 +00001255 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001256 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1257 << format(", expected CPE offset %#x\n", CPEOffset));
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001258 NewMBB = std::next(MachineFunction::iterator(UserMBB));
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001259 // Add an unconditional branch from UserMBB to fallthrough block. Record
1260 // it for branch lengthening; this new branch will not get out of range,
1261 // but if the preceding conditional branch is out of range, the targets
1262 // will be exchanged, and the altered branch may be out of range, so the
1263 // machinery has to know about it.
1264 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1265 if (!isThumb)
1266 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1267 else
1268 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1269 .addImm(ARMCC::AL).addReg(0);
1270 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1271 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1272 MaxDisp, false, UncondBr));
1273 BBInfo[UserMBB->getNumber()].Size += Delta;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001274 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001275 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001276 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001277 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001278
1279 // What a big block. Find a place within the block to split it. This is a
1280 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1281 // entries are 4 bytes: if instruction I references island CPE, and
1282 // instruction I+1 references CPE', it will not work well to put CPE as far
1283 // forward as possible, since then CPE' cannot immediately follow it (that
1284 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1285 // need to create a new island. So, we make a first guess, then walk through
1286 // the instructions between the one currently being looked at and the
1287 // possible insertion point, and make sure any other instructions that
1288 // reference CPEs will be able to use the same island area; if not, we back
1289 // up the insertion point.
1290
1291 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001292 // point where we can add a 4-byte branch instruction, and then align to
1293 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001294 unsigned LogAlign = MF->getAlignment();
1295 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1296 unsigned KnownBits = UserBBI.internalKnownBits();
1297 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001298 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001299 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1300 BaseInsertOffset));
1301
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001302 // The 4 in the following is for the unconditional branch we'll be inserting
1303 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001304 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001305 BaseInsertOffset -= 4;
1306
1307 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1308 << " la=" << LogAlign
1309 << " kb=" << KnownBits
1310 << " up=" << UPad << '\n');
1311
1312 // This could point off the end of the block if we've already got constant
1313 // pool entries following this block; only the last one is in the water list.
1314 // Back past any possible branches (allow for a conditional and a maximally
1315 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001316 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001317 // Ensure BaseInsertOffset is larger than the offset of the instruction
1318 // following UserMI so that the loop which searches for the split point
1319 // iterates at least once.
1320 BaseInsertOffset =
1321 std::max(UserBBI.postOffset() - UPad - 8,
1322 UserOffset + TII->GetInstSizeInBytes(UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001323 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1324 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001325 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001326 CPEMI->getOperand(2).getImm();
1327 MachineBasicBlock::iterator MI = UserMI;
1328 ++MI;
1329 unsigned CPUIndex = CPUserIndex+1;
1330 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001331 MachineInstr *LastIT = nullptr;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001332 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1333 Offset < BaseInsertOffset;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001334 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001335 assert(MI != UserMBB->end() && "Fell off end of block");
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001336 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1337 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001338 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001339 // Shift intertion point by one unit of alignment so it is within reach.
1340 BaseInsertOffset -= 1u << LogAlign;
1341 EndInsertOffset -= 1u << LogAlign;
1342 }
1343 // This is overly conservative, as we don't account for CPEMIs being
1344 // reused within the block, but it doesn't matter much. Also assume CPEs
1345 // are added in order with alignment padding. We may eventually be able
1346 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001347 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001348 CPUIndex++;
1349 }
1350
1351 // Remember the last IT instruction.
1352 if (MI->getOpcode() == ARM::t2IT)
1353 LastIT = MI;
1354 }
1355
1356 --MI;
1357
1358 // Avoid splitting an IT block.
1359 if (LastIT) {
1360 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001361 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001362 if (CC != ARMCC::AL)
1363 MI = LastIT;
1364 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001365
1366 // We really must not split an IT block.
1367 DEBUG(unsigned PredReg;
1368 assert(!isThumb || getITInstrPredicate(MI, PredReg) == ARMCC::AL));
1369
Jim Grosbach190e7b62012-03-23 23:07:03 +00001370 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001371}
1372
Jim Grosbach190e7b62012-03-23 23:07:03 +00001373/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001374/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001375/// place in-range. Return true if we changed any addresses (thus must run
1376/// another pass of branch lengthening), false otherwise.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001377bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001378 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001379 MachineInstr *UserMI = U.MI;
1380 MachineInstr *CPEMI = U.CPEMI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001381 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001382 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001383 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001384 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001385
Dale Johannesene18b13b2007-02-23 05:02:36 +00001386 // See if the current entry is within range, or there is a clone of it
1387 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001388 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001389 if (result==1) return false;
1390 else if (result==2) return true;
1391
1392 // No existing clone of this CPE is within range.
1393 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001394 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001395
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001396 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001397 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001398 MachineBasicBlock *NewMBB;
1399 water_iterator IP;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001400 if (findAvailableWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001401 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001402 MachineBasicBlock *WaterBB = *IP;
1403
1404 // If the original WaterList entry was "new water" on this iteration,
1405 // propagate that to the new island. This is just keeping NewWaterList
1406 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001407 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001408 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001409
Bob Wilson2f9be502009-10-15 20:49:47 +00001410 // The new CPE goes before the following block (NewMBB).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001411 NewMBB = std::next(MachineFunction::iterator(WaterBB));
Bob Wilson2f9be502009-10-15 20:49:47 +00001412
1413 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001414 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001415 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001416 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001417
Jim Grosbach190e7b62012-03-23 23:07:03 +00001418 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001419 // called while handling branches so that the water will be seen on the
1420 // next iteration for constant pools, but in this context, we don't want
1421 // it. Check for this so it will be removed from the WaterList.
1422 // Also remove any entry from NewWaterList.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001423 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
Bob Wilson2f9be502009-10-15 20:49:47 +00001424 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1425 if (IP != WaterList.end())
1426 NewWaterList.erase(WaterBB);
1427
1428 // We are adding new water. Update NewWaterList.
1429 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001430 }
1431
Bob Wilson2f9be502009-10-15 20:49:47 +00001432 // Remove the original WaterList entry; we want subsequent insertions in
1433 // this vicinity to go after the one we're about to insert. This
1434 // considerably reduces the number of times we have to move the same CPE
1435 // more than once and is also important to ensure the algorithm terminates.
1436 if (IP != WaterList.end())
1437 WaterList.erase(IP);
1438
Dale Johannesene18b13b2007-02-23 05:02:36 +00001439 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001440 MF->insert(NewMBB, NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001441
1442 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001443 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001444
1445 // Decrement the old entry, and remove it if refcount becomes 0.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001446 decrementCPEReferenceCount(CPI, CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001447
1448 // Now that we have an island to add the CPE to, clone the original CPE and
1449 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001450 U.HighWaterMark = NewIsland;
Chris Lattner6f306d72010-04-02 20:16:16 +00001451 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Cheng10043e22007-01-19 07:51:42 +00001452 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001453 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001454 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001455
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001456 // Mark the basic block as aligned as required by the const-pool entry.
1457 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001458
Evan Cheng10043e22007-01-19 07:51:42 +00001459 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001460 BBInfo[NewIsland->getNumber()].Size += Size;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001461 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001462
Evan Cheng10043e22007-01-19 07:51:42 +00001463 // Finally, change the CPI in the instruction operand to be ID.
1464 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001465 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001466 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001467 break;
1468 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001469
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001470 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001471 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001472
Evan Cheng10043e22007-01-19 07:51:42 +00001473 return true;
1474}
1475
Jim Grosbach190e7b62012-03-23 23:07:03 +00001476/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001477/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001478void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001479 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001480 unsigned Size = CPEMI->getOperand(2).getImm();
1481 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001482 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001483 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001484 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001485 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001486
Evan Chengab28b9a2013-02-21 18:37:54 +00001487 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001488 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001489 } else
1490 // Entries are sorted by descending alignment, so realign from the front.
1491 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1492
Jim Grosbach190e7b62012-03-23 23:07:03 +00001493 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001494 // An island has only one predecessor BB and one successor BB. Check if
1495 // this BB's predecessor jumps directly to this BB's successor. This
1496 // shouldn't happen currently.
1497 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1498 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001499}
1500
Jim Grosbach190e7b62012-03-23 23:07:03 +00001501/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001502/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001503bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001504 unsigned MadeChange = false;
1505 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1506 std::vector<CPEntry> &CPEs = CPEntries[i];
1507 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1508 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001509 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001510 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001511 MadeChange = true;
1512 }
1513 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001514 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001515 return MadeChange;
1516}
1517
Jim Grosbach190e7b62012-03-23 23:07:03 +00001518/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001519/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001520bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001521 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001522 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001523 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001524 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001525
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001526 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001527 << " from BB#" << MI->getParent()->getNumber()
1528 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001529 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001530 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001531
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001532 if (BrOffset <= DestOffset) {
1533 // Branch before the Dest.
1534 if (DestOffset-BrOffset <= MaxDisp)
1535 return true;
1536 } else {
1537 if (BrOffset-DestOffset <= MaxDisp)
1538 return true;
1539 }
1540 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001541}
1542
Jim Grosbach190e7b62012-03-23 23:07:03 +00001543/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001544/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001545bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001546 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001547 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001548
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001549 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001550 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001551 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001552
Evan Cheng7fa69642007-01-30 01:18:38 +00001553 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001554 return fixupUnconditionalBr(Br);
1555 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001556}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001557
Jim Grosbach190e7b62012-03-23 23:07:03 +00001558/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001559/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001560/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001561/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001562bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001563ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001564 MachineInstr *MI = Br.MI;
1565 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001566 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001567 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001568
1569 // Use BL to implement far jump.
1570 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001571 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001572 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001573 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001574 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001575 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001576
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001577 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001578
Evan Cheng7fa69642007-01-30 01:18:38 +00001579 return true;
1580}
1581
Jim Grosbach190e7b62012-03-23 23:07:03 +00001582/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001583/// far away to fit in its displacement field. It is converted to an inverse
1584/// conditional branch + an unconditional branch to the destination.
1585bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001586ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001587 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001588 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001589
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001590 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001591 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001592 // blt L1
1593 // =>
1594 // bge L2
1595 // b L1
1596 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001597 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001598 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001599 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001600
1601 // If the branch is at the end of its MBB and that has a fall-through block,
1602 // direct the updated conditional branch to the fall-through block. Otherwise,
1603 // split the MBB before the next instruction.
1604 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001605 MachineInstr *BMI = &MBB->back();
1606 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001607
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001608 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001609 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001610 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001611 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001612 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001613 // condition and swap destinations:
1614 // beq L1
1615 // b L2
1616 // =>
1617 // bne L2
1618 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001619 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001620 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001621 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001622 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001623 BMI->getOperand(0).setMBB(DestBB);
1624 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001625 MI->getOperand(1).setImm(CC);
1626 return true;
1627 }
1628 }
1629 }
1630
1631 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001632 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001633 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001634 // branch to the destination.
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +00001635 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001636 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001637 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001638 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001639 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001640 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001641
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001642 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001643 << " also invert condition and change dest. to BB#"
1644 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001645
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001646 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001647 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001648 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001649 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001650 Br.MI = &MBB->back();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001651 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001652 if (isThumb)
1653 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1654 .addImm(ARMCC::AL).addReg(0);
1655 else
1656 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001657 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001658 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001659 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001660
1661 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001662 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001663 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001664 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001665 return true;
1666}
Evan Cheng7fa69642007-01-30 01:18:38 +00001667
Jim Grosbach190e7b62012-03-23 23:07:03 +00001668/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001669/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1670/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001671bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001672 bool MadeChange = false;
1673 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1674 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001675 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001676 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001677 MI->getOperand(2).getReg() == ARM::PC &&
1678 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001679 // Create the new insn and copy the predicate from the old.
1680 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1681 .addOperand(MI->getOperand(0))
1682 .addOperand(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001683 MI->eraseFromParent();
1684 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001685 }
1686 }
1687 return MadeChange;
1688}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001689
Jim Grosbach190e7b62012-03-23 23:07:03 +00001690// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001691// below may shrink MI.
1692bool
1693ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1694 switch(MI->getOpcode()) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001695 // optimizeThumb2Instructions.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001696 case ARM::t2LEApcrel:
1697 case ARM::t2LDRpci:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001698 // optimizeThumb2Branches.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001699 case ARM::t2B:
1700 case ARM::t2Bcc:
1701 case ARM::tBcc:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001702 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001703 case ARM::t2BR_JT:
1704 return true;
1705 }
1706 return false;
1707}
1708
Jim Grosbach190e7b62012-03-23 23:07:03 +00001709bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001710 bool MadeChange = false;
1711
1712 // Shrink ADR and LDR from constantpool.
1713 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1714 CPUser &U = CPUsers[i];
1715 unsigned Opcode = U.MI->getOpcode();
1716 unsigned NewOpc = 0;
1717 unsigned Scale = 1;
1718 unsigned Bits = 0;
1719 switch (Opcode) {
1720 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001721 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001722 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1723 NewOpc = ARM::tLEApcrel;
1724 Bits = 8;
1725 Scale = 4;
1726 }
1727 break;
1728 case ARM::t2LDRpci:
1729 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1730 NewOpc = ARM::tLDRpci;
1731 Bits = 8;
1732 Scale = 4;
1733 }
1734 break;
1735 }
1736
1737 if (!NewOpc)
1738 continue;
1739
Jim Grosbach190e7b62012-03-23 23:07:03 +00001740 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001741 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001742
1743 // Be conservative with inline asm.
1744 if (!U.KnownAlignment)
1745 MaxOffs -= 2;
1746
Evan Chengdb73d682009-08-14 00:32:16 +00001747 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001748 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001749 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001750 U.MI->setDesc(TII->get(NewOpc));
1751 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001752 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001753 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001754 ++NumT2CPShrunk;
1755 MadeChange = true;
1756 }
1757 }
1758
Jim Grosbach190e7b62012-03-23 23:07:03 +00001759 MadeChange |= optimizeThumb2Branches();
1760 MadeChange |= optimizeThumb2JumpTables();
Evan Chengdb73d682009-08-14 00:32:16 +00001761 return MadeChange;
1762}
1763
Jim Grosbach190e7b62012-03-23 23:07:03 +00001764bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001765 bool MadeChange = false;
1766
1767 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1768 ImmBranch &Br = ImmBranches[i];
1769 unsigned Opcode = Br.MI->getOpcode();
1770 unsigned NewOpc = 0;
1771 unsigned Scale = 1;
1772 unsigned Bits = 0;
1773 switch (Opcode) {
1774 default: break;
1775 case ARM::t2B:
1776 NewOpc = ARM::tB;
1777 Bits = 11;
1778 Scale = 2;
1779 break;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001780 case ARM::t2Bcc: {
Evan Chenge41903b2009-08-14 18:31:44 +00001781 NewOpc = ARM::tBcc;
1782 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001783 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001784 break;
1785 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001786 }
1787 if (NewOpc) {
1788 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1789 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001790 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001791 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001792 Br.MI->setDesc(TII->get(NewOpc));
1793 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001794 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001795 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001796 ++NumT2BrShrunk;
1797 MadeChange = true;
1798 }
1799 }
1800
1801 Opcode = Br.MI->getOpcode();
1802 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001803 continue;
1804
Evan Cheng6bb95252012-01-14 01:53:46 +00001805 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1806 // so this transformation is not safe.
1807 if (!Br.MI->killsRegister(ARM::CPSR))
1808 continue;
1809
Evan Cheng6f29ad92009-10-31 23:46:45 +00001810 NewOpc = 0;
1811 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001812 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001813 if (Pred == ARMCC::EQ)
1814 NewOpc = ARM::tCBZ;
1815 else if (Pred == ARMCC::NE)
1816 NewOpc = ARM::tCBNZ;
1817 if (!NewOpc)
1818 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001819 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001820 // Check if the distance is within 126. Subtract starting offset by 2
1821 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001822 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001823 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001824 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001825 MachineBasicBlock::iterator CmpMI = Br.MI;
1826 if (CmpMI != Br.MI->getParent()->begin()) {
1827 --CmpMI;
1828 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1829 unsigned Reg = CmpMI->getOperand(0).getReg();
Craig Topperf6e7e122012-03-27 07:21:54 +00001830 Pred = getInstrPredicate(CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001831 if (Pred == ARMCC::AL &&
1832 CmpMI->getOperand(1).getImm() == 0 &&
1833 isARMLowRegister(Reg)) {
1834 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001835 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001836 MachineInstr *NewBR =
1837 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1838 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1839 CmpMI->eraseFromParent();
1840 Br.MI->eraseFromParent();
1841 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001842 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001843 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001844 ++NumCBZ;
1845 MadeChange = true;
1846 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001847 }
1848 }
Evan Chenge41903b2009-08-14 18:31:44 +00001849 }
1850 }
1851
1852 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001853}
1854
Jim Grosbach190e7b62012-03-23 23:07:03 +00001855/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00001856/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001857bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00001858 bool MadeChange = false;
1859
1860 // FIXME: After the tables are shrunk, can we get rid some of the
1861 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001862 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00001863 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001864
Evan Chengc6d70ae2009-07-29 02:18:14 +00001865 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1866 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1867 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00001868 const MCInstrDesc &MCID = MI->getDesc();
1869 unsigned NumOps = MCID.getNumOperands();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001870 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Chengc6d70ae2009-07-29 02:18:14 +00001871 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1872 unsigned JTI = JTOP.getIndex();
1873 assert(JTI < JT.size());
1874
Jim Grosbach8d92ec42009-11-11 02:47:19 +00001875 bool ByteOk = true;
1876 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001877 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00001878 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001879 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1880 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001881 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00001882 // Negative offset is not ok. FIXME: We should change BB layout to make
1883 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00001884 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00001885 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00001886 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00001887 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00001888 HalfWordOk = false;
1889 if (!ByteOk && !HalfWordOk)
1890 break;
1891 }
1892
1893 if (ByteOk || HalfWordOk) {
1894 MachineBasicBlock *MBB = MI->getParent();
1895 unsigned BaseReg = MI->getOperand(0).getReg();
1896 bool BaseRegKill = MI->getOperand(0).isKill();
1897 if (!BaseRegKill)
1898 continue;
1899 unsigned IdxReg = MI->getOperand(1).getReg();
1900 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbach40eda102010-07-07 22:51:22 +00001901
1902 // Scan backwards to find the instruction that defines the base
1903 // register. Due to post-RA scheduling, we can't count on it
1904 // immediately preceding the branch instruction.
Evan Chengc6d70ae2009-07-29 02:18:14 +00001905 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbach40eda102010-07-07 22:51:22 +00001906 MachineBasicBlock::iterator B = MBB->begin();
1907 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1908 --PrevI;
1909
1910 // If for some reason we didn't find it, we can't do anything, so
1911 // just skip this one.
1912 if (!PrevI->definesRegister(BaseReg))
Evan Chengc6d70ae2009-07-29 02:18:14 +00001913 continue;
1914
Jim Grosbach40eda102010-07-07 22:51:22 +00001915 MachineInstr *AddrMI = PrevI;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001916 bool OptOk = true;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001917 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbach40eda102010-07-07 22:51:22 +00001918 // Make sure it only defines the base register and kills any uses
1919 // other than the index register.
Evan Chengc6d70ae2009-07-29 02:18:14 +00001920 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1921 const MachineOperand &MO = AddrMI->getOperand(k);
1922 if (!MO.isReg() || !MO.getReg())
1923 continue;
1924 if (MO.isDef() && MO.getReg() != BaseReg) {
1925 OptOk = false;
1926 break;
1927 }
1928 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1929 OptOk = false;
1930 break;
1931 }
1932 }
1933 if (!OptOk)
1934 continue;
1935
Owen Anderson9a4d4282010-12-13 22:51:08 +00001936 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbach40eda102010-07-07 22:51:22 +00001937 // that gave us the initial base register definition.
1938 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1939 ;
1940
Owen Anderson9a4d4282010-12-13 22:51:08 +00001941 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chengdb73d682009-08-14 00:32:16 +00001942 // to delete it as well.
Jim Grosbach40eda102010-07-07 22:51:22 +00001943 MachineInstr *LeaMI = PrevI;
Evan Chengdb73d682009-08-14 00:32:16 +00001944 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson9a4d4282010-12-13 22:51:08 +00001945 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Chengc6d70ae2009-07-29 02:18:14 +00001946 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Chenge64f48b2009-08-01 06:13:52 +00001947 OptOk = false;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001948
Evan Chenge64f48b2009-08-01 06:13:52 +00001949 if (!OptOk)
1950 continue;
1951
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001952 DEBUG(dbgs() << "Shrink JT: " << *MI << " addr: " << *AddrMI
1953 << " lea: " << *LeaMI);
Jim Grosbach81af4f92010-11-29 21:28:32 +00001954 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Chenge64f48b2009-08-01 06:13:52 +00001955 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1956 .addReg(IdxReg, getKillRegState(IdxRegKill))
1957 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1958 .addImm(MI->getOperand(JTOpIdx+1).getImm());
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001959 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00001960 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1961 // is 2-byte aligned. For now, asm printer will fix it up.
1962 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1963 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1964 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1965 OrigSize += TII->GetInstSizeInBytes(MI);
1966
1967 AddrMI->eraseFromParent();
1968 LeaMI->eraseFromParent();
1969 MI->eraseFromParent();
1970
1971 int delta = OrigSize - NewSize;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001972 BBInfo[MBB->getNumber()].Size -= delta;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001973 adjustBBOffsetsAfter(MBB);
Evan Chenge64f48b2009-08-01 06:13:52 +00001974
1975 ++NumTBs;
1976 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001977 }
1978 }
1979
1980 return MadeChange;
1981}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00001982
Jim Grosbach190e7b62012-03-23 23:07:03 +00001983/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00001984/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001985bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00001986 bool MadeChange = false;
1987
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001988 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00001989 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001990
Jim Grosbach5d577142009-11-12 17:25:07 +00001991 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1992 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1993 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00001994 const MCInstrDesc &MCID = MI->getDesc();
1995 unsigned NumOps = MCID.getNumOperands();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001996 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach5d577142009-11-12 17:25:07 +00001997 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1998 unsigned JTI = JTOP.getIndex();
1999 assert(JTI < JT.size());
2000
2001 // We prefer if target blocks for the jump table come after the jump
2002 // instruction so we can use TB[BH]. Loop through the target blocks
2003 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002004 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002005 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2006 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2007 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002008 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002009
Jim Grosbach9785e592009-11-16 18:58:52 +00002010 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002011 // The destination precedes the switch. Try to move the block forward
2012 // so we have a positive offset.
2013 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002014 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002015 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002016 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002017 MadeChange = true;
2018 }
2019 }
2020 }
2021
2022 return MadeChange;
2023}
2024
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002025MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002026adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002027 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002028 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002029 // table that branches back to the actual target. This is a very simple
2030 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002031 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002032 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002033 SmallVector<MachineOperand, 4> CondPrior;
2034 MachineFunction::iterator BBi = BB;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002035 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002036
Jim Grosbach47d5e332009-11-16 17:10:56 +00002037 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002038 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002039
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002040 // If the block ends in an unconditional branch, move it. The prior block
2041 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002042 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002043 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002044 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002045 BB->moveAfter(JTBB);
2046 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002047 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002048 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002049 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002050 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002051 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002052 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002053
2054 // Create a new MBB for the code after the jump BB.
2055 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002056 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002057 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002058 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002059
2060 // Add an unconditional branch from NewBB to BB.
2061 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2062 // correspond directly to anything in the source.
2063 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson29cfe6c2011-09-09 21:48:23 +00002064 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2065 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002066
Jim Grosbach43d21082009-11-14 20:10:18 +00002067 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002068 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002069
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002070 // Update the CFG.
2071 NewBB->addSuccessor(BB);
2072 JTBB->removeSuccessor(BB);
2073 JTBB->addSuccessor(NewBB);
2074
Jim Grosbach5d577142009-11-12 17:25:07 +00002075 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002076 return NewBB;
2077}