blob: 0a47400c490d97cad8bdc7b5aa49b97fd1c84472 [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 Olesen146ac7b2011-12-10 02:55:10 +000056/// UnknownPadding - Return the worst case padding that could result from
57/// unknown offset bits. This does not include alignment padding caused by
58/// known offset bits.
59///
60/// @param LogAlign log2(alignment)
61/// @param KnownBits Number of known low offset bits.
62static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
63 if (KnownBits < LogAlign)
64 return (1u << LogAlign) - (1u << KnownBits);
65 return 0;
66}
67
Evan Cheng10043e22007-01-19 07:51:42 +000068namespace {
Dale Johannesene18b13b2007-02-23 05:02:36 +000069 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Cheng10043e22007-01-19 07:51:42 +000070 /// requires constant pool entries to be scattered among the instructions
71 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesene18b13b2007-02-23 05:02:36 +000072 /// constant pool; instead, it places constants wherever it feels like with
Evan Cheng10043e22007-01-19 07:51:42 +000073 /// special instructions.
74 ///
75 /// The terminology used in this pass includes:
76 /// Islands - Clumps of constants placed in the function.
77 /// Water - Potential places where an island could be formed.
78 /// CPE - A constant pool entry that has been placed somewhere, which
79 /// tracks a list of users.
Nick Lewycky02d5f772009-10-25 06:33:48 +000080 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000081 /// BasicBlockInfo - Information about the offset and size of a single
82 /// basic block.
83 struct BasicBlockInfo {
84 /// Offset - Distance from the beginning of the function to the beginning
85 /// of this basic block.
86 ///
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +000087 /// Offsets are computed assuming worst case padding before an aligned
88 /// block. This means that subtracting basic block offsets always gives a
89 /// conservative estimate of the real distance which may be smaller.
90 ///
91 /// Because worst case padding is used, the computed offset of an aligned
92 /// block may not actually be aligned.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000093 unsigned Offset;
Bob Wilson2f4e56f2009-05-12 17:09:30 +000094
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000095 /// Size - Size of the basic block in bytes. If the block contains
96 /// inline assembly, this is a worst case estimate.
97 ///
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +000098 /// The size does not include any alignment padding whether from the
99 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000100 unsigned Size;
101
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000102 /// KnownBits - The number of low bits in Offset that are known to be
103 /// exact. The remaining bits of Offset are an upper bound.
104 uint8_t KnownBits;
105
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000106 /// Unalign - When non-zero, the block contains instructions (inline asm)
107 /// of unknown size. The real size may be smaller than Size bytes by a
108 /// multiple of 1 << Unalign.
109 uint8_t Unalign;
110
111 /// PostAlign - When non-zero, the block terminator contains a .align
112 /// directive, so the end of the block is aligned to 1 << PostAlign
113 /// bytes.
114 uint8_t PostAlign;
115
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000116 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
117 PostAlign(0) {}
Jakob Stoklund Olesenaf748e12011-12-07 01:22:52 +0000118
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +0000119 /// Compute the number of known offset bits internally to this block.
120 /// This number should be used to predict worst case padding when
121 /// splitting the block.
122 unsigned internalKnownBits() const {
Jakob Stoklund Olesen8503ba92012-04-30 20:19:00 +0000123 unsigned Bits = Unalign ? Unalign : KnownBits;
124 // If the block size isn't a multiple of the known bits, assume the
125 // worst case padding.
126 if (Size & ((1u << Bits) - 1))
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000127 Bits = countTrailingZeros(Size);
Jakob Stoklund Olesen8503ba92012-04-30 20:19:00 +0000128 return Bits;
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +0000129 }
130
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000131 /// Compute the offset immediately following this block. If LogAlign is
132 /// specified, return the offset the successor block will get if it has
133 /// this alignment.
134 unsigned postOffset(unsigned LogAlign = 0) const {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000135 unsigned PO = Offset + Size;
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000136 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
137 if (!LA)
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000138 return PO;
139 // Add alignment padding from the terminator.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +0000140 return PO + UnknownPadding(LA, internalKnownBits());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000141 }
142
143 /// Compute the number of known low bits of postOffset. If this block
144 /// contains inline asm, the number of known bits drops to the
145 /// instruction alignment. An aligned terminator may increase the number
146 /// of know bits.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000147 /// If LogAlign is given, also consider the alignment of the next block.
148 unsigned postKnownBits(unsigned LogAlign = 0) const {
149 return std::max(std::max(unsigned(PostAlign), LogAlign),
150 internalKnownBits());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000151 }
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000152 };
153
154 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen01ee5752007-02-25 00:47:03 +0000155
Evan Cheng10043e22007-01-19 07:51:42 +0000156 /// WaterList - A sorted list of basic blocks where islands could be placed
157 /// (i.e. blocks that don't fall through to the following block, due
158 /// to a return, unreachable, or unconditional branch).
Evan Cheng540f5e02007-02-09 23:59:14 +0000159 std::vector<MachineBasicBlock*> WaterList;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000160
Bob Wilson2f9be502009-10-15 20:49:47 +0000161 /// NewWaterList - The subset of WaterList that was created since the
162 /// previous iteration by inserting unconditional branches.
163 SmallSet<MachineBasicBlock*, 4> NewWaterList;
164
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000165 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
166
Evan Cheng10043e22007-01-19 07:51:42 +0000167 /// CPUser - One user of a constant pool, keeping the machine instruction
168 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson68ead6c2009-10-15 05:52:29 +0000169 /// allowed from the instruction to the CP. The HighWaterMark records the
170 /// highest basic block where a new CPEntry can be placed. To ensure this
171 /// pass terminates, the CP entries are initially placed at the end of the
172 /// function and then move monotonically to lower addresses. The
173 /// exception to this rule is when the current CP entry for a particular
174 /// CPUser is out of range, but there is another CP entry for the same
175 /// constant value in range. We want to use the existing in-range CP
176 /// entry, but if it later moves out of range, the search for new water
177 /// should resume where it left off. The HighWaterMark is used to record
178 /// that point.
Evan Cheng10043e22007-01-19 07:51:42 +0000179 struct CPUser {
180 MachineInstr *MI;
181 MachineInstr *CPEMI;
Bob Wilson68ead6c2009-10-15 05:52:29 +0000182 MachineBasicBlock *HighWaterMark;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000183 private:
Evan Cheng10043e22007-01-19 07:51:42 +0000184 unsigned MaxDisp;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000185 public:
Evan Cheng87aaa192009-07-21 23:56:01 +0000186 bool NegOk;
Evan Chengd2919a12009-07-23 18:27:47 +0000187 bool IsSoImm;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000188 bool KnownAlignment;
Evan Chengd2919a12009-07-23 18:27:47 +0000189 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
190 bool neg, bool soimm)
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000191 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
192 KnownAlignment(false) {
Bob Wilson68ead6c2009-10-15 05:52:29 +0000193 HighWaterMark = CPEMI->getParent();
194 }
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000195 /// getMaxDisp - Returns the maximum displacement supported by MI.
196 /// Correct for unknown alignment.
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000197 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000198 unsigned getMaxDisp() const {
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000199 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000200 }
Evan Cheng10043e22007-01-19 07:51:42 +0000201 };
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000202
Evan Cheng10043e22007-01-19 07:51:42 +0000203 /// CPUsers - Keep track of all of the machine instructions that use various
204 /// constant pools and their max displacement.
Evan Cheng540f5e02007-02-09 23:59:14 +0000205 std::vector<CPUser> CPUsers;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000206
Evan Cheng8b7700f2007-02-09 20:54:44 +0000207 /// CPEntry - One per constant pool entry, keeping the machine instruction
208 /// pointer, the constpool index, and the number of CPUser's which
209 /// reference this entry.
210 struct CPEntry {
211 MachineInstr *CPEMI;
212 unsigned CPI;
213 unsigned RefCount;
214 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
215 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
216 };
217
218 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesene18b13b2007-02-23 05:02:36 +0000219 /// instructions. For each original constpool index (i.e. those that
220 /// existed upon entry to this pass), it keeps a vector of entries.
221 /// Original elements are cloned as we go along; the clones are
222 /// put in the vector of the original element, but have distinct CPIs.
Evan Cheng8b7700f2007-02-09 20:54:44 +0000223 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000224
Evan Cheng22c7cf52007-01-25 03:12:46 +0000225 /// ImmBranch - One per immediate branch, keeping the machine instruction
226 /// pointer, conditional or unconditional, the max displacement,
227 /// and (if isCond is true) the corresponding unconditional branch
228 /// opcode.
229 struct ImmBranch {
230 MachineInstr *MI;
Evan Cheng010ae382007-01-25 23:18:59 +0000231 unsigned MaxDisp : 31;
232 bool isCond : 1;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000233 int UncondBr;
Evan Cheng010ae382007-01-25 23:18:59 +0000234 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
235 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Cheng22c7cf52007-01-25 03:12:46 +0000236 };
237
Evan Chengc95f95b2007-05-16 05:14:06 +0000238 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Cheng22c7cf52007-01-25 03:12:46 +0000239 ///
Evan Cheng540f5e02007-02-09 23:59:14 +0000240 std::vector<ImmBranch> ImmBranches;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000241
Evan Cheng7fa69642007-01-30 01:18:38 +0000242 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
243 ///
Evan Cheng8b7700f2007-02-09 20:54:44 +0000244 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Cheng7fa69642007-01-30 01:18:38 +0000245
Evan Chengc6d70ae2009-07-29 02:18:14 +0000246 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
247 SmallVector<MachineInstr*, 4> T2JumpTables;
248
Evan Cheng7fa69642007-01-30 01:18:38 +0000249 /// HasFarJump - True if any far jump instruction has been emitted during
250 /// the branch fix up pass.
251 bool HasFarJump;
252
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000253 MachineFunction *MF;
254 MachineConstantPool *MCP;
Craig Topper07720d82012-03-25 23:49:58 +0000255 const ARMBaseInstrInfo *TII;
Evan Chenge64f48b2009-08-01 06:13:52 +0000256 const ARMSubtarget *STI;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000257 ARMFunctionInfo *AFI;
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000258 bool isThumb;
Evan Chengd2919a12009-07-23 18:27:47 +0000259 bool isThumb1;
David Goodwin27303cd2009-06-30 18:04:13 +0000260 bool isThumb2;
Evan Cheng10043e22007-01-19 07:51:42 +0000261 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000262 static char ID;
Owen Andersona7aed182010-08-06 18:33:48 +0000263 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +0000264
Craig Topper6bc27bf2014-03-10 02:09:33 +0000265 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng10043e22007-01-19 07:51:42 +0000266
Craig Topper6bc27bf2014-03-10 02:09:33 +0000267 const char *getPassName() const override {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000268 return "ARM constant island placement and branch shortening pass";
Evan Cheng10043e22007-01-19 07:51:42 +0000269 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000270
Evan Cheng10043e22007-01-19 07:51:42 +0000271 private:
Jim Grosbach190e7b62012-03-23 23:07:03 +0000272 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000273 bool BBHasFallthrough(MachineBasicBlock *MBB);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000274 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000275 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000276 void scanFunctionJumpTables();
277 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
278 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
279 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
280 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
281 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
282 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
283 bool findAvailableWater(CPUser&U, unsigned UserOffset,
284 water_iterator &WaterIter);
285 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000286 MachineBasicBlock *&NewMBB);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000287 bool handleConstantPoolUser(unsigned CPUserIndex);
288 void removeDeadCPEMI(MachineInstr *CPEMI);
289 bool removeUnusedCPEntries();
290 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
291 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
292 bool DoDump = false);
293 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000294 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000295 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
296 bool fixupImmediateBr(ImmBranch &Br);
297 bool fixupConditionalBr(ImmBranch &Br);
298 bool fixupUnconditionalBr(ImmBranch &Br);
299 bool undoLRSpillRestore();
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000300 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
Jim Grosbach190e7b62012-03-23 23:07:03 +0000301 bool optimizeThumb2Instructions();
302 bool optimizeThumb2Branches();
303 bool reorderThumb2JumpTables();
304 bool optimizeThumb2JumpTables();
305 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000306 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000307
Jim Grosbach190e7b62012-03-23 23:07:03 +0000308 void computeBlockSize(MachineBasicBlock *MBB);
309 unsigned getOffsetOf(MachineInstr *MI) const;
310 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000311 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000312 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000313
Jim Grosbach190e7b62012-03-23 23:07:03 +0000314 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000315 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000316 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000317 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000318 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000319 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000320 }
Evan Cheng10043e22007-01-19 07:51:42 +0000321 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000322 char ARMConstantIslands::ID = 0;
Evan Cheng10043e22007-01-19 07:51:42 +0000323}
324
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000325/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000326void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000327#ifndef NDEBUG
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000328 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd2919a12009-07-23 18:27:47 +0000329 MBBI != E; ++MBBI) {
330 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesenbd97f5d2011-12-08 01:10:05 +0000331 unsigned MBBId = MBB->getNumber();
Jakob Stoklund Olesenbd97f5d2011-12-08 01:10:05 +0000332 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000333 }
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000334 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000335 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
336 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000337 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000338 // Verify offset using the real max displacement without the safety
339 // adjustment.
340 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000341 /* DoDump = */ true)) {
342 DEBUG(dbgs() << "OK\n");
343 continue;
344 }
345 DEBUG(dbgs() << "Out of range.\n");
346 dumpBBs();
347 DEBUG(MF->dump());
348 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000349 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000350#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000351}
352
353/// print block size and offset information - debugging
354void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000355 DEBUG({
356 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
357 const BasicBlockInfo &BBI = BBInfo[J];
358 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
359 << " kb=" << unsigned(BBI.KnownBits)
360 << " ua=" << unsigned(BBI.Unalign)
361 << " pa=" << unsigned(BBI.PostAlign)
362 << format(" size=%#x\n", BBInfo[J].Size);
363 }
364 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000365}
366
Evan Cheng22c7cf52007-01-25 03:12:46 +0000367/// createARMConstantIslandPass - returns an instance of the constpool
368/// island pass.
Evan Cheng10043e22007-01-19 07:51:42 +0000369FunctionPass *llvm::createARMConstantIslandPass() {
370 return new ARMConstantIslands();
371}
372
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000373bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
374 MF = &mf;
375 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000376
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000377 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000378 << MCP->getConstants().size() << " CP entries, aligned to "
379 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000380
Eric Christopher1b21f002015-01-29 00:19:33 +0000381 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
382 TII = STI->getInstrInfo();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000383 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000384
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000385 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000386 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000387 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000388
389 HasFarJump = false;
390
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000391 // This pass invalidates liveness information when it splits basic blocks.
392 MF->getRegInfo().invalidateLiveness();
393
Evan Cheng10043e22007-01-19 07:51:42 +0000394 // Renumber all of the machine basic blocks in the function, guaranteeing that
395 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000396 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000397
Jim Grosbach5d577142009-11-12 17:25:07 +0000398 // Try to reorder and otherwise adjust the block layout to make good use
399 // of the TB[BH] instructions.
400 bool MadeChange = false;
401 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000402 scanFunctionJumpTables();
403 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000404 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000405 T2JumpTables.clear();
406 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000407 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000408 }
409
Evan Cheng10043e22007-01-19 07:51:42 +0000410 // Perform the initial placement of the constant pool entries. To start with,
411 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000412 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000413 if (!MCP->isEmpty())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000414 doInitialPlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000415
Evan Cheng10043e22007-01-19 07:51:42 +0000416 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000417 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000418
Evan Cheng10043e22007-01-19 07:51:42 +0000419 // Do the initial scan of the function, building up information about the
420 // sizes of each block, the location of all the water, and finding all of the
421 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000422 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000423 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000424 DEBUG(dumpBBs());
425
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000426 // Functions with jump tables need an alignment of 4 because they use the ADR
427 // instruction, which aligns the PC to 4 bytes before adding an offset.
428 if (!T2JumpTables.empty())
429 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000430
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000431 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000432 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000433
Evan Cheng7fa69642007-01-30 01:18:38 +0000434 // Iteratively place constant pool entries and fix up branches until there
435 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000436 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000437 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000438 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000439 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000440 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000441 CPChange |= handleConstantPoolUser(i);
Evan Cheng82ff0222009-08-07 07:35:21 +0000442 if (CPChange && ++NoCPIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000443 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000444 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000445
Bob Wilson2f9be502009-10-15 20:49:47 +0000446 // Clear NewWaterList now. If we split a block for branches, it should
447 // appear as "new water" for the next iteration of constant pool placement.
448 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000449
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000450 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000451 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000452 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000453 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000454 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000455 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000456 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000457
458 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000459 break;
460 MadeChange = true;
461 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000462
Evan Chengdb73d682009-08-14 00:32:16 +0000463 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000464 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000465 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000466
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000467 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000468 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000469
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000470 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
471 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000472 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000473 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000474
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000475 // Save the mapping between original and cloned constpool entries.
476 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
477 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
478 const CPEntry & CPE = CPEntries[i][j];
479 AFI->recordCPEClone(i, CPE.CPI);
480 }
481 }
482
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000483 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000484
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000485 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000486 WaterList.clear();
487 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000488 CPEntries.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000489 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000490 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000491 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000492
493 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000494}
495
Jim Grosbach190e7b62012-03-23 23:07:03 +0000496/// doInitialPlacement - Perform the initial placement of the constant pool
Evan Cheng10043e22007-01-19 07:51:42 +0000497/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000498void
Jim Grosbach190e7b62012-03-23 23:07:03 +0000499ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000500 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000501 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
502 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000503
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000504 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000505 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000506
507 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000508 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000509
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000510 // The function needs to be as aligned as the basic blocks. The linker may
511 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000512 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000513
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000514 // Order the entries in BB by descending alignment. That ensures correct
515 // alignment of all entries as long as BB is sufficiently aligned. Keep
516 // track of the insertion point for each alignment. We are going to bucket
517 // sort the entries as they are created.
518 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000519
Evan Cheng10043e22007-01-19 07:51:42 +0000520 // Add all of the constants from the constant pool to the end block, use an
521 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000522 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000523
Eric Christopher8b770652015-01-26 19:03:15 +0000524 const DataLayout &TD = *MF->getTarget().getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000525 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000526 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000527 assert(Size >= 4 && "Too small constant pool entry");
528 unsigned Align = CPs[i].getAlignment();
529 assert(isPowerOf2_32(Align) && "Invalid alignment");
530 // Verify that all constant pool entries are a multiple of their alignment.
531 // If not, we would have to pad them out so that instructions stay aligned.
532 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
533
534 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
535 unsigned LogAlign = Log2_32(Align);
536 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000537 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000538 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000539 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000540 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000541
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000542 // Ensure that future entries with higher alignment get inserted before
543 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000544 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000545 if (InsPoint[a] == InsAt)
546 InsPoint[a] = CPEMI;
547
Evan Cheng8b7700f2007-02-09 20:54:44 +0000548 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000549 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000550 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000551 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
552 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000553 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000554 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000555}
556
Dale Johannesene18b13b2007-02-23 05:02:36 +0000557/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000558/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000559bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000560 // Get the next machine basic block in the function.
561 MachineFunction::iterator MBBI = MBB;
Jim Grosbach84511e12010-06-02 21:53:11 +0000562 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000563 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000564 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000565
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000566 MachineBasicBlock *NextBB = std::next(MBBI);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000567 if (std::find(MBB->succ_begin(), MBB->succ_end(), NextBB) == MBB->succ_end())
568 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000569
Tim Northoverab85dcc2014-11-13 17:58:51 +0000570 // Try to analyze the end of the block. A potential fallthrough may already
571 // have an unconditional branch for whatever reason.
572 MachineBasicBlock *TBB, *FBB;
573 SmallVector<MachineOperand, 4> Cond;
574 bool TooDifficult = TII->AnalyzeBranch(*MBB, TBB, FBB, Cond);
575 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000576}
577
Evan Cheng8b7700f2007-02-09 20:54:44 +0000578/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
579/// look up the corresponding CPEntry.
580ARMConstantIslands::CPEntry
581*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
582 const MachineInstr *CPEMI) {
583 std::vector<CPEntry> &CPEs = CPEntries[CPI];
584 // Number of entries per constpool index should be small, just do a
585 // linear search.
586 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
587 if (CPEs[i].CPEMI == CPEMI)
588 return &CPEs[i];
589 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000590 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000591}
592
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000593/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000594/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000595unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
596 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
597
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000598 unsigned CPI = CPEMI->getOperand(1).getIndex();
599 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
600 unsigned Align = MCP->getConstants()[CPI].getAlignment();
601 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
602 return Log2_32(Align);
603}
604
Jim Grosbach190e7b62012-03-23 23:07:03 +0000605/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000606/// information about the sizes of each block and the locations of all
607/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000608void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000609 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach5d577142009-11-12 17:25:07 +0000610 MBBI != E; ++MBBI) {
611 MachineBasicBlock &MBB = *MBBI;
612
Jim Grosbach5d577142009-11-12 17:25:07 +0000613 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach9785e592009-11-16 18:58:52 +0000614 I != E; ++I)
Evan Cheng7f8e5632011-12-07 07:15:52 +0000615 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach9785e592009-11-16 18:58:52 +0000616 T2JumpTables.push_back(I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000617 }
618}
619
Jim Grosbach190e7b62012-03-23 23:07:03 +0000620/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000621/// information about the sizes of each block, the location of all the water,
622/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000623void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000624initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000625 BBInfo.clear();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000626 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000627
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000628 // First thing, compute the size of all basic blocks, and see if the function
629 // has any inline assembly in it. If so, we have to be conservative about
630 // alignment assumptions, as we don't know for sure the size of any
631 // instructions in the inline assembly.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000632 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000633 computeBlockSize(I);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000634
635 // The known bits of the entry block offset are determined by the function
636 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000637 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000638
639 // Compute block offsets and known bits.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000640 adjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000641
Bill Wendling18581a42010-12-21 01:54:40 +0000642 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000643 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Cheng10043e22007-01-19 07:51:42 +0000644 MBBI != E; ++MBBI) {
645 MachineBasicBlock &MBB = *MBBI;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000646
Evan Cheng10043e22007-01-19 07:51:42 +0000647 // If this block doesn't fall through into the next MBB, then this is
648 // 'water' that a constant pool island could be placed.
649 if (!BBHasFallthrough(&MBB))
650 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000651
Evan Cheng10043e22007-01-19 07:51:42 +0000652 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
653 I != E; ++I) {
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000654 if (I->isDebugValue())
655 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000656
Evan Cheng22c7cf52007-01-25 03:12:46 +0000657 int Opc = I->getOpcode();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000658 if (I->isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000659 bool isCond = false;
660 unsigned Bits = 0;
661 unsigned Scale = 1;
662 int UOpc = Opc;
663 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000664 default:
665 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000666 case ARM::t2BR_JT:
667 T2JumpTables.push_back(I);
668 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000669 case ARM::Bcc:
670 isCond = true;
671 UOpc = ARM::B;
672 // Fallthrough
673 case ARM::B:
674 Bits = 24;
675 Scale = 4;
676 break;
677 case ARM::tBcc:
678 isCond = true;
679 UOpc = ARM::tB;
680 Bits = 8;
681 Scale = 2;
682 break;
683 case ARM::tB:
684 Bits = 11;
685 Scale = 2;
686 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000687 case ARM::t2Bcc:
688 isCond = true;
689 UOpc = ARM::t2B;
690 Bits = 20;
691 Scale = 2;
692 break;
693 case ARM::t2B:
694 Bits = 24;
695 Scale = 2;
696 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000697 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000698
699 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000700 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengf9a4c692007-02-01 10:16:15 +0000701 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000702 }
703
Evan Cheng7fa69642007-01-30 01:18:38 +0000704 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
705 PushPopMIs.push_back(I);
706
Evan Chengd2919a12009-07-23 18:27:47 +0000707 if (Opc == ARM::CONSTPOOL_ENTRY)
708 continue;
709
Evan Cheng10043e22007-01-19 07:51:42 +0000710 // Scan the instructions for constant pool operands.
711 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000712 if (I->getOperand(op).isCPI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000713 // We found one. The addressing mode tells us the max displacement
714 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000715
Evan Cheng10043e22007-01-19 07:51:42 +0000716 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000717 unsigned Bits = 0;
718 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000719 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000720 bool IsSoImm = false;
721
722 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000723 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000724 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000725
726 // Taking the address of a CP entry.
727 case ARM::LEApcrel:
728 // This takes a SoImm, which is 8 bit immediate rotated. We'll
729 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000730 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000731 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000732 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000733 Scale = 4;
734 NegOk = true;
735 IsSoImm = true;
736 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000737 case ARM::t2LEApcrel:
Evan Chengd2919a12009-07-23 18:27:47 +0000738 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000739 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000740 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000741 case ARM::tLEApcrel:
742 Bits = 8;
743 Scale = 4;
744 break;
745
David Majnemer452f1f92013-06-04 17:46:15 +0000746 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000747 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000748 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000749 case ARM::t2LDRpci:
Evan Chengfd522992007-02-01 20:44:52 +0000750 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000751 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000752 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000753
754 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000755 Bits = 8;
756 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000757 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000758
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000759 case ARM::VLDRD:
760 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000761 Bits = 8;
762 Scale = 4; // +-(offset_8*4)
763 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000764 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000765 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000766
Evan Cheng10043e22007-01-19 07:51:42 +0000767 // Remember that this is a user of a CP entry.
Chris Lattnera5bb3702007-12-30 23:10:15 +0000768 unsigned CPI = I->getOperand(op).getIndex();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000769 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000770 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd2919a12009-07-23 18:27:47 +0000771 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000772
773 // Increment corresponding CPEntry reference count.
774 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
775 assert(CPE && "Cannot find a corresponding CPEntry!");
776 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000777
Evan Cheng10043e22007-01-19 07:51:42 +0000778 // Instructions can only use one CP entry, don't bother scanning the
779 // rest of the operands.
780 break;
781 }
782 }
Evan Cheng10043e22007-01-19 07:51:42 +0000783 }
784}
785
Jim Grosbach190e7b62012-03-23 23:07:03 +0000786/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000787/// This function updates BBInfo directly.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000788void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000789 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
790 BBI.Size = 0;
791 BBI.Unalign = 0;
792 BBI.PostAlign = 0;
793
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000794 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
795 ++I) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000796 BBI.Size += TII->GetInstSizeInBytes(I);
797 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
798 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesen14e024d2011-12-08 01:22:39 +0000799 if (I->isInlineAsm())
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000800 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000801 // Also consider instructions that may be shrunk later.
802 else if (isThumb && mayOptimizeThumb2Instruction(I))
803 BBI.Unalign = 1;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000804 }
805
806 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000807 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000808 BBI.PostAlign = 2;
Chad Rosier73b02822012-07-06 23:13:38 +0000809 MBB->getParent()->ensureAlignment(2);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000810 }
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000811}
812
Jim Grosbach190e7b62012-03-23 23:07:03 +0000813/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000814/// from the start of the function. This offset changes as stuff is moved
815/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000816unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000817 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000818
Evan Cheng10043e22007-01-19 07:51:42 +0000819 // The offset is composed of two things: the sum of the sizes of all MBB's
820 // before this instruction's block, and the offset from the start of the block
821 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000822 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000823
824 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000825 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000826 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +0000827 Offset += TII->GetInstSizeInBytes(I);
Evan Cheng10043e22007-01-19 07:51:42 +0000828 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000829 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000830}
831
832/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
833/// ID.
834static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
835 const MachineBasicBlock *RHS) {
836 return LHS->getNumber() < RHS->getNumber();
837}
838
Jim Grosbach190e7b62012-03-23 23:07:03 +0000839/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000840/// machine function, it upsets all of the block numbers. Renumber the blocks
841/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000842void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000843 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000844 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000845
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000846 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000847 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000848 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000849
850 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000851 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000852 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000853 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
854 CompareMBBNumbers);
855 WaterList.insert(IP, NewBB);
856}
857
858
859/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000860/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000861/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000862MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000863 MachineBasicBlock *OrigBB = MI->getParent();
864
865 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000866 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000867 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Cheng10043e22007-01-19 07:51:42 +0000868 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000869 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000870
Evan Cheng10043e22007-01-19 07:51:42 +0000871 // Splice the instructions starting with MI over to NewBB.
872 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000873
Evan Cheng10043e22007-01-19 07:51:42 +0000874 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000875 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000876 // There doesn't seem to be meaningful DebugInfo available; this doesn't
877 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000878 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000879 if (!isThumb)
880 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
881 else
882 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
883 .addImm(ARMCC::AL).addReg(0);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000884 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000885
Evan Cheng10043e22007-01-19 07:51:42 +0000886 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000887 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000888
Evan Cheng10043e22007-01-19 07:51:42 +0000889 // OrigBB branches to NewBB.
890 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000891
Evan Cheng10043e22007-01-19 07:51:42 +0000892 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000893 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000894 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000895 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000896
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000897 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000898 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000899 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000900
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000901 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000902 // available water after it (but not if it's already there, which happens
903 // when splitting before a conditional branch that is followed by an
904 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000905 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +0000906 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
907 CompareMBBNumbers);
908 MachineBasicBlock* WaterBB = *IP;
909 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000910 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000911 else
912 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000913 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000914
Dale Johannesenc17dd572010-07-23 22:50:23 +0000915 // Figure out how large the OrigBB is. As the first half of the original
916 // block, it cannot contain a tablejump. The size includes
917 // the new jump we added. (It should be possible to do this without
918 // recounting everything, but it's very confusing, and this is rarely
919 // executed.)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000920 computeBlockSize(OrigBB);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000921
Dale Johannesenc17dd572010-07-23 22:50:23 +0000922 // Figure out how large the NewMBB is. As the second half of the original
923 // block, it may contain a tablejump.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000924 computeBlockSize(NewBB);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000925
Dale Johannesen01ee5752007-02-25 00:47:03 +0000926 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000927 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000928
929 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000930}
931
Jim Grosbach190e7b62012-03-23 23:07:03 +0000932/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000933/// displacement computation. Update U.KnownAlignment to match its current
934/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000935unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
936 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000937 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
938 unsigned KnownBits = BBI.internalKnownBits();
939
940 // The value read from PC is offset from the actual instruction address.
941 UserOffset += (isThumb ? 4 : 8);
942
943 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
944 // Make sure U.getMaxDisp() returns a constrained range.
945 U.KnownAlignment = (KnownBits >= 2);
946
947 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
948 // purposes of the displacement computation; compensate for that here.
949 // For unknown alignments, getMaxDisp() constrains the range instead.
950 if (isThumb && U.KnownAlignment)
951 UserOffset &= ~3u;
952
953 return UserOffset;
954}
955
Jim Grosbach190e7b62012-03-23 23:07:03 +0000956/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000957/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000958/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +0000959/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000960/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
961/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000962bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +0000963 unsigned TrialOffset, unsigned MaxDisp,
964 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +0000965 if (UserOffset <= TrialOffset) {
966 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +0000967 if (TrialOffset - UserOffset <= MaxDisp)
968 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000969 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000970 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +0000971 if (UserOffset - TrialOffset <= MaxDisp)
972 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000973 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000974 }
975 return false;
976}
977
Jim Grosbach190e7b62012-03-23 23:07:03 +0000978/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +0000979/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000980///
981/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000982bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000983 MachineBasicBlock* Water, CPUser &U,
984 unsigned &Growth) {
985 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
986 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
987 unsigned NextBlockOffset, NextBlockAlignment;
988 MachineFunction::const_iterator NextBlock = Water;
989 if (++NextBlock == MF->end()) {
990 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
991 NextBlockAlignment = 0;
992 } else {
993 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
994 NextBlockAlignment = NextBlock->getAlignment();
995 }
996 unsigned Size = U.CPEMI->getOperand(2).getImm();
997 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +0000998
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000999 // The CPE may be able to hide in the alignment padding before the next
1000 // block. It may also cause more padding to be required if it is more aligned
1001 // that the next block.
1002 if (CPEEnd > NextBlockOffset) {
1003 Growth = CPEEnd - NextBlockOffset;
1004 // Compute the padding that would go at the end of the CPE to align the next
1005 // block.
1006 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1007
1008 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001009 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001010 // in blocks between CPE and the user.
1011 if (CPEOffset < UserOffset)
1012 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1013 } else
1014 // CPE fits in existing padding.
1015 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001016
Jim Grosbach190e7b62012-03-23 23:07:03 +00001017 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001018}
1019
Jim Grosbach190e7b62012-03-23 23:07:03 +00001020/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001021/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001022bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001023 MachineInstr *CPEMI, unsigned MaxDisp,
1024 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001025 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001026
Dale Johannesene18b13b2007-02-23 05:02:36 +00001027 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001028 DEBUG({
1029 unsigned Block = MI->getParent()->getNumber();
1030 const BasicBlockInfo &BBI = BBInfo[Block];
1031 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1032 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001033 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001034 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001035 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1036 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1037 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001038 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001039 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001040
Jim Grosbach190e7b62012-03-23 23:07:03 +00001041 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001042}
1043
Evan Chenge4510972009-01-28 00:53:34 +00001044#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001045/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1046/// unconditionally branches to its only successor.
1047static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1048 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1049 return false;
1050
1051 MachineBasicBlock *Succ = *MBB->succ_begin();
1052 MachineBasicBlock *Pred = *MBB->pred_begin();
1053 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001054 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1055 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001056 return PredMI->getOperand(0).getMBB() == Succ;
1057 return false;
1058}
Evan Chenge4510972009-01-28 00:53:34 +00001059#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001060
Jim Grosbach190e7b62012-03-23 23:07:03 +00001061void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001062 unsigned BBNum = BB->getNumber();
1063 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001064 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001065 // Include the alignment of the current block.
1066 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1067 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1068 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001069
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001070 // This is where block i begins. Stop if the offset is already correct,
1071 // and we have updated 2 blocks. This is the maximum number of blocks
1072 // changed before calling this function.
1073 if (i > BBNum + 2 &&
1074 BBInfo[i].Offset == Offset &&
1075 BBInfo[i].KnownBits == KnownBits)
1076 break;
1077
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001078 BBInfo[i].Offset = Offset;
1079 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001080 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001081}
1082
Jim Grosbach190e7b62012-03-23 23:07:03 +00001083/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001084/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001085/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001086/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001087
Jim Grosbach190e7b62012-03-23 23:07:03 +00001088bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1089 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001090 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001091 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1092 assert(CPE && "Unexpected!");
1093 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001094 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001095 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001096 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001097 return true;
1098 }
1099 return false;
1100}
1101
Dale Johannesene18b13b2007-02-23 05:02:36 +00001102/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1103/// if not, see if an in-range clone of the CPE is in range, and if so,
1104/// change the data structures so the user references the clone. Returns:
1105/// 0 = no existing entry found
1106/// 1 = entry found, and there were no code insertions or deletions
1107/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001108int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001109{
1110 MachineInstr *UserMI = U.MI;
1111 MachineInstr *CPEMI = U.CPEMI;
1112
1113 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001114 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1115 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001116 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001117 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001118 }
1119
Dale Johannesene18b13b2007-02-23 05:02:36 +00001120 // No. Look for previously created clones of the CPE that are in range.
Chris Lattnera5bb3702007-12-30 23:10:15 +00001121 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001122 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1123 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1124 // We already tried this one
1125 if (CPEs[i].CPEMI == CPEMI)
1126 continue;
1127 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001128 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001129 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001130 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001131 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001132 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001133 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001134 // Point the CPUser node to the replacement
1135 U.CPEMI = CPEs[i].CPEMI;
1136 // Change the CPI in the instruction operand to refer to the clone.
1137 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001138 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001139 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001140 break;
1141 }
1142 // Adjust the refcount of the clone...
1143 CPEs[i].RefCount++;
1144 // ...and the original. If we didn't remove the old entry, none of the
1145 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001146 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001147 }
1148 }
1149 return 0;
1150}
1151
Dale Johannesen440995b2007-02-28 18:41:23 +00001152/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1153/// the specific unconditional branch instruction.
1154static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001155 switch (Opc) {
1156 case ARM::tB:
1157 return ((1<<10)-1)*2;
1158 case ARM::t2B:
1159 return ((1<<23)-1)*2;
1160 default:
1161 break;
1162 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001163
David Goodwin27303cd2009-06-30 18:04:13 +00001164 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001165}
1166
Jim Grosbach190e7b62012-03-23 23:07:03 +00001167/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001168/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001169/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001170/// is set to the WaterList entry. For Thumb, prefer water that will not
1171/// introduce padding to water that will. To ensure that this pass
1172/// terminates, the CPE location for a particular CPUser is only allowed to
1173/// move to a lower address, so search backward from the end of the list and
1174/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001175bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Bob Wilson2f9be502009-10-15 20:49:47 +00001176 water_iterator &WaterIter) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001177 if (WaterList.empty())
1178 return false;
1179
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001180 unsigned BestGrowth = ~0u;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001181 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001182 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001183 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001184 // Check if water is in range and is either at a lower address than the
1185 // current "high water mark" or a new water block that was created since
1186 // the previous iteration by inserting an unconditional branch. In the
1187 // latter case, we want to allow resetting the high water mark back to
1188 // this new water since we haven't seen it before. Inserting branches
1189 // should be relatively uncommon and when it does happen, we want to be
1190 // sure to take advantage of it for all the CPEs near that block, so that
1191 // we don't insert more branches than necessary.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001192 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001193 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001194 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001195 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1196 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001197 // This is the least amount of required padding seen so far.
1198 BestGrowth = Growth;
1199 WaterIter = IP;
1200 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1201 << " Growth=" << Growth << '\n');
1202
1203 // Keep looking unless it is perfect.
1204 if (BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001205 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001206 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001207 if (IP == B)
1208 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001209 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001210 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001211}
1212
Jim Grosbach190e7b62012-03-23 23:07:03 +00001213/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001214/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1215/// block is used if in range, and the conditional branch munged so control
1216/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001217/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001218/// block following which the new island can be inserted (the WaterList
1219/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001220void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001221 unsigned UserOffset,
1222 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001223 CPUser &U = CPUsers[CPUserIndex];
1224 MachineInstr *UserMI = U.MI;
1225 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001226 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001227 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001228 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001229
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001230 // If the block does not end in an unconditional branch already, and if the
1231 // end of the block is within range, make new water there. (The addition
1232 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001233 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001234 if (BBHasFallthrough(UserMBB)) {
1235 // Size of branch to insert.
1236 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001237 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001238 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001239
Jim Grosbach190e7b62012-03-23 23:07:03 +00001240 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001241 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1242 << format(", expected CPE offset %#x\n", CPEOffset));
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001243 NewMBB = std::next(MachineFunction::iterator(UserMBB));
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001244 // Add an unconditional branch from UserMBB to fallthrough block. Record
1245 // it for branch lengthening; this new branch will not get out of range,
1246 // but if the preceding conditional branch is out of range, the targets
1247 // will be exchanged, and the altered branch may be out of range, so the
1248 // machinery has to know about it.
1249 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1250 if (!isThumb)
1251 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1252 else
1253 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1254 .addImm(ARMCC::AL).addReg(0);
1255 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1256 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1257 MaxDisp, false, UncondBr));
Akira Hatanaka442b40c2015-01-08 20:44:50 +00001258 computeBlockSize(UserMBB);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001259 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001260 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001261 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001262 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001263
1264 // What a big block. Find a place within the block to split it. This is a
1265 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1266 // entries are 4 bytes: if instruction I references island CPE, and
1267 // instruction I+1 references CPE', it will not work well to put CPE as far
1268 // forward as possible, since then CPE' cannot immediately follow it (that
1269 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1270 // need to create a new island. So, we make a first guess, then walk through
1271 // the instructions between the one currently being looked at and the
1272 // possible insertion point, and make sure any other instructions that
1273 // reference CPEs will be able to use the same island area; if not, we back
1274 // up the insertion point.
1275
1276 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001277 // point where we can add a 4-byte branch instruction, and then align to
1278 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001279 unsigned LogAlign = MF->getAlignment();
1280 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1281 unsigned KnownBits = UserBBI.internalKnownBits();
1282 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001283 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001284 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1285 BaseInsertOffset));
1286
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001287 // The 4 in the following is for the unconditional branch we'll be inserting
1288 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001289 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001290 BaseInsertOffset -= 4;
1291
1292 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1293 << " la=" << LogAlign
1294 << " kb=" << KnownBits
1295 << " up=" << UPad << '\n');
1296
1297 // This could point off the end of the block if we've already got constant
1298 // pool entries following this block; only the last one is in the water list.
1299 // Back past any possible branches (allow for a conditional and a maximally
1300 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001301 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001302 // Ensure BaseInsertOffset is larger than the offset of the instruction
1303 // following UserMI so that the loop which searches for the split point
1304 // iterates at least once.
1305 BaseInsertOffset =
1306 std::max(UserBBI.postOffset() - UPad - 8,
1307 UserOffset + TII->GetInstSizeInBytes(UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001308 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1309 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001310 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001311 CPEMI->getOperand(2).getImm();
1312 MachineBasicBlock::iterator MI = UserMI;
1313 ++MI;
1314 unsigned CPUIndex = CPUserIndex+1;
1315 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001316 MachineInstr *LastIT = nullptr;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001317 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1318 Offset < BaseInsertOffset;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001319 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001320 assert(MI != UserMBB->end() && "Fell off end of block");
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001321 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1322 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001323 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001324 // Shift intertion point by one unit of alignment so it is within reach.
1325 BaseInsertOffset -= 1u << LogAlign;
1326 EndInsertOffset -= 1u << LogAlign;
1327 }
1328 // This is overly conservative, as we don't account for CPEMIs being
1329 // reused within the block, but it doesn't matter much. Also assume CPEs
1330 // are added in order with alignment padding. We may eventually be able
1331 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001332 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001333 CPUIndex++;
1334 }
1335
1336 // Remember the last IT instruction.
1337 if (MI->getOpcode() == ARM::t2IT)
1338 LastIT = MI;
1339 }
1340
1341 --MI;
1342
1343 // Avoid splitting an IT block.
1344 if (LastIT) {
1345 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001346 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001347 if (CC != ARMCC::AL)
1348 MI = LastIT;
1349 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001350
1351 // We really must not split an IT block.
1352 DEBUG(unsigned PredReg;
1353 assert(!isThumb || getITInstrPredicate(MI, PredReg) == ARMCC::AL));
1354
Jim Grosbach190e7b62012-03-23 23:07:03 +00001355 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001356}
1357
Jim Grosbach190e7b62012-03-23 23:07:03 +00001358/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001359/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001360/// place in-range. Return true if we changed any addresses (thus must run
1361/// another pass of branch lengthening), false otherwise.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001362bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001363 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001364 MachineInstr *UserMI = U.MI;
1365 MachineInstr *CPEMI = U.CPEMI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001366 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001367 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001368 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001369 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001370
Dale Johannesene18b13b2007-02-23 05:02:36 +00001371 // See if the current entry is within range, or there is a clone of it
1372 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001373 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001374 if (result==1) return false;
1375 else if (result==2) return true;
1376
1377 // No existing clone of this CPE is within range.
1378 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001379 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001380
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001381 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001382 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001383 MachineBasicBlock *NewMBB;
1384 water_iterator IP;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001385 if (findAvailableWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001386 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001387 MachineBasicBlock *WaterBB = *IP;
1388
1389 // If the original WaterList entry was "new water" on this iteration,
1390 // propagate that to the new island. This is just keeping NewWaterList
1391 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001392 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001393 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001394
Bob Wilson2f9be502009-10-15 20:49:47 +00001395 // The new CPE goes before the following block (NewMBB).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001396 NewMBB = std::next(MachineFunction::iterator(WaterBB));
Bob Wilson2f9be502009-10-15 20:49:47 +00001397
1398 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001399 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001400 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001401 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001402
Jim Grosbach190e7b62012-03-23 23:07:03 +00001403 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001404 // called while handling branches so that the water will be seen on the
1405 // next iteration for constant pools, but in this context, we don't want
1406 // it. Check for this so it will be removed from the WaterList.
1407 // Also remove any entry from NewWaterList.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001408 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
Bob Wilson2f9be502009-10-15 20:49:47 +00001409 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1410 if (IP != WaterList.end())
1411 NewWaterList.erase(WaterBB);
1412
1413 // We are adding new water. Update NewWaterList.
1414 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001415 }
1416
Bob Wilson2f9be502009-10-15 20:49:47 +00001417 // Remove the original WaterList entry; we want subsequent insertions in
1418 // this vicinity to go after the one we're about to insert. This
1419 // considerably reduces the number of times we have to move the same CPE
1420 // more than once and is also important to ensure the algorithm terminates.
1421 if (IP != WaterList.end())
1422 WaterList.erase(IP);
1423
Dale Johannesene18b13b2007-02-23 05:02:36 +00001424 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001425 MF->insert(NewMBB, NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001426
1427 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001428 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001429
1430 // Decrement the old entry, and remove it if refcount becomes 0.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001431 decrementCPEReferenceCount(CPI, CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001432
1433 // Now that we have an island to add the CPE to, clone the original CPE and
1434 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001435 U.HighWaterMark = NewIsland;
Chris Lattner6f306d72010-04-02 20:16:16 +00001436 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Cheng10043e22007-01-19 07:51:42 +00001437 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001438 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001439 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001440
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001441 // Mark the basic block as aligned as required by the const-pool entry.
1442 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001443
Evan Cheng10043e22007-01-19 07:51:42 +00001444 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001445 BBInfo[NewIsland->getNumber()].Size += Size;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001446 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001447
Evan Cheng10043e22007-01-19 07:51:42 +00001448 // Finally, change the CPI in the instruction operand to be ID.
1449 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001450 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001451 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001452 break;
1453 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001454
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001455 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001456 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001457
Evan Cheng10043e22007-01-19 07:51:42 +00001458 return true;
1459}
1460
Jim Grosbach190e7b62012-03-23 23:07:03 +00001461/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001462/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001463void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001464 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001465 unsigned Size = CPEMI->getOperand(2).getImm();
1466 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001467 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001468 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001469 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001470 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001471
Evan Chengab28b9a2013-02-21 18:37:54 +00001472 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001473 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001474 } else
1475 // Entries are sorted by descending alignment, so realign from the front.
1476 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1477
Jim Grosbach190e7b62012-03-23 23:07:03 +00001478 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001479 // An island has only one predecessor BB and one successor BB. Check if
1480 // this BB's predecessor jumps directly to this BB's successor. This
1481 // shouldn't happen currently.
1482 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1483 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001484}
1485
Jim Grosbach190e7b62012-03-23 23:07:03 +00001486/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001487/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001488bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001489 unsigned MadeChange = false;
1490 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1491 std::vector<CPEntry> &CPEs = CPEntries[i];
1492 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1493 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001494 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001495 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001496 MadeChange = true;
1497 }
1498 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001499 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001500 return MadeChange;
1501}
1502
Jim Grosbach190e7b62012-03-23 23:07:03 +00001503/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001504/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001505bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001506 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001507 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001508 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001509 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001510
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001511 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001512 << " from BB#" << MI->getParent()->getNumber()
1513 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001514 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001515 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001516
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001517 if (BrOffset <= DestOffset) {
1518 // Branch before the Dest.
1519 if (DestOffset-BrOffset <= MaxDisp)
1520 return true;
1521 } else {
1522 if (BrOffset-DestOffset <= MaxDisp)
1523 return true;
1524 }
1525 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001526}
1527
Jim Grosbach190e7b62012-03-23 23:07:03 +00001528/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001529/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001530bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001531 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001532 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001533
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001534 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001535 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001536 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001537
Evan Cheng7fa69642007-01-30 01:18:38 +00001538 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001539 return fixupUnconditionalBr(Br);
1540 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001541}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001542
Jim Grosbach190e7b62012-03-23 23:07:03 +00001543/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001544/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001545/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001546/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001547bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001548ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001549 MachineInstr *MI = Br.MI;
1550 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001551 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001552 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001553
1554 // Use BL to implement far jump.
1555 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001556 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001557 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001558 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001559 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001560 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001561
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001562 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001563
Evan Cheng7fa69642007-01-30 01:18:38 +00001564 return true;
1565}
1566
Jim Grosbach190e7b62012-03-23 23:07:03 +00001567/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001568/// far away to fit in its displacement field. It is converted to an inverse
1569/// conditional branch + an unconditional branch to the destination.
1570bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001571ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001572 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001573 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001574
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001575 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001576 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001577 // blt L1
1578 // =>
1579 // bge L2
1580 // b L1
1581 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001582 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001583 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001584 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001585
1586 // If the branch is at the end of its MBB and that has a fall-through block,
1587 // direct the updated conditional branch to the fall-through block. Otherwise,
1588 // split the MBB before the next instruction.
1589 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001590 MachineInstr *BMI = &MBB->back();
1591 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001592
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001593 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001594 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001595 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001596 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001597 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001598 // condition and swap destinations:
1599 // beq L1
1600 // b L2
1601 // =>
1602 // bne L2
1603 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001604 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001605 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001606 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001607 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001608 BMI->getOperand(0).setMBB(DestBB);
1609 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001610 MI->getOperand(1).setImm(CC);
1611 return true;
1612 }
1613 }
1614 }
1615
1616 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001617 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001618 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001619 // branch to the destination.
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +00001620 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001621 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001622 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001623 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001624 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001625 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001626
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001627 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001628 << " also invert condition and change dest. to BB#"
1629 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001630
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001631 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001632 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001633 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001634 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001635 Br.MI = &MBB->back();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001636 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001637 if (isThumb)
1638 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1639 .addImm(ARMCC::AL).addReg(0);
1640 else
1641 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001642 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001643 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001644 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001645
1646 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001647 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001648 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001649 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001650 return true;
1651}
Evan Cheng7fa69642007-01-30 01:18:38 +00001652
Jim Grosbach190e7b62012-03-23 23:07:03 +00001653/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001654/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1655/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001656bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001657 bool MadeChange = false;
1658 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1659 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001660 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001661 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001662 MI->getOperand(2).getReg() == ARM::PC &&
1663 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001664 // Create the new insn and copy the predicate from the old.
1665 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1666 .addOperand(MI->getOperand(0))
1667 .addOperand(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001668 MI->eraseFromParent();
1669 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001670 }
1671 }
1672 return MadeChange;
1673}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001674
Jim Grosbach190e7b62012-03-23 23:07:03 +00001675// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001676// below may shrink MI.
1677bool
1678ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1679 switch(MI->getOpcode()) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001680 // optimizeThumb2Instructions.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001681 case ARM::t2LEApcrel:
1682 case ARM::t2LDRpci:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001683 // optimizeThumb2Branches.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001684 case ARM::t2B:
1685 case ARM::t2Bcc:
1686 case ARM::tBcc:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001687 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001688 case ARM::t2BR_JT:
1689 return true;
1690 }
1691 return false;
1692}
1693
Jim Grosbach190e7b62012-03-23 23:07:03 +00001694bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001695 bool MadeChange = false;
1696
1697 // Shrink ADR and LDR from constantpool.
1698 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1699 CPUser &U = CPUsers[i];
1700 unsigned Opcode = U.MI->getOpcode();
1701 unsigned NewOpc = 0;
1702 unsigned Scale = 1;
1703 unsigned Bits = 0;
1704 switch (Opcode) {
1705 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001706 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001707 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1708 NewOpc = ARM::tLEApcrel;
1709 Bits = 8;
1710 Scale = 4;
1711 }
1712 break;
1713 case ARM::t2LDRpci:
1714 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1715 NewOpc = ARM::tLDRpci;
1716 Bits = 8;
1717 Scale = 4;
1718 }
1719 break;
1720 }
1721
1722 if (!NewOpc)
1723 continue;
1724
Jim Grosbach190e7b62012-03-23 23:07:03 +00001725 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001726 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001727
1728 // Be conservative with inline asm.
1729 if (!U.KnownAlignment)
1730 MaxOffs -= 2;
1731
Evan Chengdb73d682009-08-14 00:32:16 +00001732 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001733 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001734 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001735 U.MI->setDesc(TII->get(NewOpc));
1736 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001737 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001738 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001739 ++NumT2CPShrunk;
1740 MadeChange = true;
1741 }
1742 }
1743
Jim Grosbach190e7b62012-03-23 23:07:03 +00001744 MadeChange |= optimizeThumb2Branches();
1745 MadeChange |= optimizeThumb2JumpTables();
Evan Chengdb73d682009-08-14 00:32:16 +00001746 return MadeChange;
1747}
1748
Jim Grosbach190e7b62012-03-23 23:07:03 +00001749bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001750 bool MadeChange = false;
1751
Peter Collingbourne167668f2015-04-23 20:31:35 +00001752 // The order in which branches appear in ImmBranches is approximately their
1753 // order within the function body. By visiting later branches first, we reduce
1754 // the distance between earlier forward branches and their targets, making it
1755 // more likely that the cbn?z optimization, which can only apply to forward
1756 // branches, will succeed.
1757 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1758 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001759 unsigned Opcode = Br.MI->getOpcode();
1760 unsigned NewOpc = 0;
1761 unsigned Scale = 1;
1762 unsigned Bits = 0;
1763 switch (Opcode) {
1764 default: break;
1765 case ARM::t2B:
1766 NewOpc = ARM::tB;
1767 Bits = 11;
1768 Scale = 2;
1769 break;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001770 case ARM::t2Bcc: {
Evan Chenge41903b2009-08-14 18:31:44 +00001771 NewOpc = ARM::tBcc;
1772 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001773 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001774 break;
1775 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001776 }
1777 if (NewOpc) {
1778 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1779 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001780 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001781 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001782 Br.MI->setDesc(TII->get(NewOpc));
1783 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001784 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001785 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001786 ++NumT2BrShrunk;
1787 MadeChange = true;
1788 }
1789 }
1790
1791 Opcode = Br.MI->getOpcode();
1792 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001793 continue;
1794
Evan Cheng6bb95252012-01-14 01:53:46 +00001795 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1796 // so this transformation is not safe.
1797 if (!Br.MI->killsRegister(ARM::CPSR))
1798 continue;
1799
Evan Cheng6f29ad92009-10-31 23:46:45 +00001800 NewOpc = 0;
1801 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001802 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001803 if (Pred == ARMCC::EQ)
1804 NewOpc = ARM::tCBZ;
1805 else if (Pred == ARMCC::NE)
1806 NewOpc = ARM::tCBNZ;
1807 if (!NewOpc)
1808 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001809 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001810 // Check if the distance is within 126. Subtract starting offset by 2
1811 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001812 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001813 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001814 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001815 MachineBasicBlock::iterator CmpMI = Br.MI;
1816 if (CmpMI != Br.MI->getParent()->begin()) {
1817 --CmpMI;
1818 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1819 unsigned Reg = CmpMI->getOperand(0).getReg();
Craig Topperf6e7e122012-03-27 07:21:54 +00001820 Pred = getInstrPredicate(CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001821 if (Pred == ARMCC::AL &&
1822 CmpMI->getOperand(1).getImm() == 0 &&
1823 isARMLowRegister(Reg)) {
1824 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001825 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001826 MachineInstr *NewBR =
1827 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1828 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1829 CmpMI->eraseFromParent();
1830 Br.MI->eraseFromParent();
1831 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001832 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001833 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001834 ++NumCBZ;
1835 MadeChange = true;
1836 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001837 }
1838 }
Evan Chenge41903b2009-08-14 18:31:44 +00001839 }
1840 }
1841
1842 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001843}
1844
Jim Grosbach190e7b62012-03-23 23:07:03 +00001845/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00001846/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001847bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00001848 bool MadeChange = false;
1849
1850 // FIXME: After the tables are shrunk, can we get rid some of the
1851 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001852 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00001853 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001854
Evan Chengc6d70ae2009-07-29 02:18:14 +00001855 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1856 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1857 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00001858 const MCInstrDesc &MCID = MI->getDesc();
1859 unsigned NumOps = MCID.getNumOperands();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001860 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Chengc6d70ae2009-07-29 02:18:14 +00001861 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1862 unsigned JTI = JTOP.getIndex();
1863 assert(JTI < JT.size());
1864
Jim Grosbach8d92ec42009-11-11 02:47:19 +00001865 bool ByteOk = true;
1866 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001867 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00001868 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001869 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1870 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001871 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00001872 // Negative offset is not ok. FIXME: We should change BB layout to make
1873 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00001874 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00001875 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00001876 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00001877 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00001878 HalfWordOk = false;
1879 if (!ByteOk && !HalfWordOk)
1880 break;
1881 }
1882
1883 if (ByteOk || HalfWordOk) {
1884 MachineBasicBlock *MBB = MI->getParent();
1885 unsigned BaseReg = MI->getOperand(0).getReg();
1886 bool BaseRegKill = MI->getOperand(0).isKill();
1887 if (!BaseRegKill)
1888 continue;
1889 unsigned IdxReg = MI->getOperand(1).getReg();
1890 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbach40eda102010-07-07 22:51:22 +00001891
1892 // Scan backwards to find the instruction that defines the base
1893 // register. Due to post-RA scheduling, we can't count on it
1894 // immediately preceding the branch instruction.
Evan Chengc6d70ae2009-07-29 02:18:14 +00001895 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbach40eda102010-07-07 22:51:22 +00001896 MachineBasicBlock::iterator B = MBB->begin();
1897 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1898 --PrevI;
1899
1900 // If for some reason we didn't find it, we can't do anything, so
1901 // just skip this one.
1902 if (!PrevI->definesRegister(BaseReg))
Evan Chengc6d70ae2009-07-29 02:18:14 +00001903 continue;
1904
Jim Grosbach40eda102010-07-07 22:51:22 +00001905 MachineInstr *AddrMI = PrevI;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001906 bool OptOk = true;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001907 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbach40eda102010-07-07 22:51:22 +00001908 // Make sure it only defines the base register and kills any uses
1909 // other than the index register.
Evan Chengc6d70ae2009-07-29 02:18:14 +00001910 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1911 const MachineOperand &MO = AddrMI->getOperand(k);
1912 if (!MO.isReg() || !MO.getReg())
1913 continue;
1914 if (MO.isDef() && MO.getReg() != BaseReg) {
1915 OptOk = false;
1916 break;
1917 }
1918 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1919 OptOk = false;
1920 break;
1921 }
1922 }
1923 if (!OptOk)
1924 continue;
1925
Owen Anderson9a4d4282010-12-13 22:51:08 +00001926 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbach40eda102010-07-07 22:51:22 +00001927 // that gave us the initial base register definition.
1928 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1929 ;
1930
Owen Anderson9a4d4282010-12-13 22:51:08 +00001931 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chengdb73d682009-08-14 00:32:16 +00001932 // to delete it as well.
Jim Grosbach40eda102010-07-07 22:51:22 +00001933 MachineInstr *LeaMI = PrevI;
Evan Chengdb73d682009-08-14 00:32:16 +00001934 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson9a4d4282010-12-13 22:51:08 +00001935 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Chengc6d70ae2009-07-29 02:18:14 +00001936 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Chenge64f48b2009-08-01 06:13:52 +00001937 OptOk = false;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001938
Evan Chenge64f48b2009-08-01 06:13:52 +00001939 if (!OptOk)
1940 continue;
1941
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001942 DEBUG(dbgs() << "Shrink JT: " << *MI << " addr: " << *AddrMI
1943 << " lea: " << *LeaMI);
Jim Grosbach81af4f92010-11-29 21:28:32 +00001944 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Chad Rosier620fb222014-12-12 23:27:40 +00001945 MachineBasicBlock::iterator MI_JT = MI;
1946 MachineInstr *NewJTMI =
1947 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Evan Chenge64f48b2009-08-01 06:13:52 +00001948 .addReg(IdxReg, getKillRegState(IdxRegKill))
1949 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1950 .addImm(MI->getOperand(JTOpIdx+1).getImm());
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001951 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00001952 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1953 // is 2-byte aligned. For now, asm printer will fix it up.
1954 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1955 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1956 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1957 OrigSize += TII->GetInstSizeInBytes(MI);
1958
1959 AddrMI->eraseFromParent();
1960 LeaMI->eraseFromParent();
1961 MI->eraseFromParent();
1962
1963 int delta = OrigSize - NewSize;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001964 BBInfo[MBB->getNumber()].Size -= delta;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001965 adjustBBOffsetsAfter(MBB);
Evan Chenge64f48b2009-08-01 06:13:52 +00001966
1967 ++NumTBs;
1968 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001969 }
1970 }
1971
1972 return MadeChange;
1973}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00001974
Jim Grosbach190e7b62012-03-23 23:07:03 +00001975/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00001976/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001977bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00001978 bool MadeChange = false;
1979
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001980 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00001981 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001982
Jim Grosbach5d577142009-11-12 17:25:07 +00001983 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1984 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1985 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00001986 const MCInstrDesc &MCID = MI->getDesc();
1987 unsigned NumOps = MCID.getNumOperands();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001988 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach5d577142009-11-12 17:25:07 +00001989 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1990 unsigned JTI = JTOP.getIndex();
1991 assert(JTI < JT.size());
1992
1993 // We prefer if target blocks for the jump table come after the jump
1994 // instruction so we can use TB[BH]. Loop through the target blocks
1995 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00001996 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00001997 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1998 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1999 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002000 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002001
Jim Grosbach9785e592009-11-16 18:58:52 +00002002 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002003 // The destination precedes the switch. Try to move the block forward
2004 // so we have a positive offset.
2005 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002006 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002007 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002008 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002009 MadeChange = true;
2010 }
2011 }
2012 }
2013
2014 return MadeChange;
2015}
2016
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002017MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002018adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002019 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002020 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002021 // table that branches back to the actual target. This is a very simple
2022 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002023 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002024 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002025 SmallVector<MachineOperand, 4> CondPrior;
2026 MachineFunction::iterator BBi = BB;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002027 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002028
Jim Grosbach47d5e332009-11-16 17:10:56 +00002029 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002030 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002031
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002032 // If the block ends in an unconditional branch, move it. The prior block
2033 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002034 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002035 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002036 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002037 BB->moveAfter(JTBB);
2038 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002039 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002040 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002041 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002042 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002043 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002044 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002045
2046 // Create a new MBB for the code after the jump BB.
2047 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002048 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002049 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002050 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002051
2052 // Add an unconditional branch from NewBB to BB.
2053 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2054 // correspond directly to anything in the source.
2055 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson29cfe6c2011-09-09 21:48:23 +00002056 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2057 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002058
Jim Grosbach43d21082009-11-14 20:10:18 +00002059 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002060 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002061
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002062 // Update the CFG.
2063 NewBB->addSuccessor(BB);
2064 JTBB->removeSuccessor(BB);
2065 JTBB->addSuccessor(NewBB);
2066
Jim Grosbach5d577142009-11-12 17:25:07 +00002067 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002068 return NewBB;
2069}