blob: 00c92fcddde756cceddd2d10fd8176fa2b9a4b1f [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
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000426
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000427 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000428 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000429
Evan Cheng7fa69642007-01-30 01:18:38 +0000430 // Iteratively place constant pool entries and fix up branches until there
431 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000432 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000433 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000434 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000435 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000436 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000437 CPChange |= handleConstantPoolUser(i);
Evan Cheng82ff0222009-08-07 07:35:21 +0000438 if (CPChange && ++NoCPIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000439 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000440 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000441
Bob Wilson2f9be502009-10-15 20:49:47 +0000442 // Clear NewWaterList now. If we split a block for branches, it should
443 // appear as "new water" for the next iteration of constant pool placement.
444 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000445
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000446 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000447 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000448 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000449 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000450 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000451 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000452 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000453
454 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000455 break;
456 MadeChange = true;
457 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000458
Evan Chengdb73d682009-08-14 00:32:16 +0000459 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000460 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000461 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000462
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000463 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000464 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000465
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000466 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
467 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000468 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000469 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000470
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000471 // Save the mapping between original and cloned constpool entries.
472 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
473 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
474 const CPEntry & CPE = CPEntries[i][j];
475 AFI->recordCPEClone(i, CPE.CPI);
476 }
477 }
478
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000479 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000480
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000481 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000482 WaterList.clear();
483 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000484 CPEntries.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000485 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000486 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000487 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000488
489 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000490}
491
Jim Grosbach190e7b62012-03-23 23:07:03 +0000492/// doInitialPlacement - Perform the initial placement of the constant pool
Evan Cheng10043e22007-01-19 07:51:42 +0000493/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000494void
Jim Grosbach190e7b62012-03-23 23:07:03 +0000495ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000496 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000497 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
498 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000499
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000500 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000501 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000502
503 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000504 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000505
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000506 // The function needs to be as aligned as the basic blocks. The linker may
507 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000508 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000509
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000510 // Order the entries in BB by descending alignment. That ensures correct
511 // alignment of all entries as long as BB is sufficiently aligned. Keep
512 // track of the insertion point for each alignment. We are going to bucket
513 // sort the entries as they are created.
514 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000515
Evan Cheng10043e22007-01-19 07:51:42 +0000516 // Add all of the constants from the constant pool to the end block, use an
517 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000518 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000519
Eric Christopher8b770652015-01-26 19:03:15 +0000520 const DataLayout &TD = *MF->getTarget().getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000521 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000522 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000523 assert(Size >= 4 && "Too small constant pool entry");
524 unsigned Align = CPs[i].getAlignment();
525 assert(isPowerOf2_32(Align) && "Invalid alignment");
526 // Verify that all constant pool entries are a multiple of their alignment.
527 // If not, we would have to pad them out so that instructions stay aligned.
528 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
529
530 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
531 unsigned LogAlign = Log2_32(Align);
532 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000533 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000534 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000535 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000536 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000537
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000538 // Ensure that future entries with higher alignment get inserted before
539 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000540 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000541 if (InsPoint[a] == InsAt)
542 InsPoint[a] = CPEMI;
543
Evan Cheng8b7700f2007-02-09 20:54:44 +0000544 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000545 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000546 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000547 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
548 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000549 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000550 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000551}
552
Dale Johannesene18b13b2007-02-23 05:02:36 +0000553/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000554/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000555bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000556 // Get the next machine basic block in the function.
557 MachineFunction::iterator MBBI = MBB;
Jim Grosbach84511e12010-06-02 21:53:11 +0000558 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000559 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000560 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000561
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000562 MachineBasicBlock *NextBB = std::next(MBBI);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000563 if (std::find(MBB->succ_begin(), MBB->succ_end(), NextBB) == MBB->succ_end())
564 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000565
Tim Northoverab85dcc2014-11-13 17:58:51 +0000566 // Try to analyze the end of the block. A potential fallthrough may already
567 // have an unconditional branch for whatever reason.
568 MachineBasicBlock *TBB, *FBB;
569 SmallVector<MachineOperand, 4> Cond;
570 bool TooDifficult = TII->AnalyzeBranch(*MBB, TBB, FBB, Cond);
571 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000572}
573
Evan Cheng8b7700f2007-02-09 20:54:44 +0000574/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
575/// look up the corresponding CPEntry.
576ARMConstantIslands::CPEntry
577*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
578 const MachineInstr *CPEMI) {
579 std::vector<CPEntry> &CPEs = CPEntries[CPI];
580 // Number of entries per constpool index should be small, just do a
581 // linear search.
582 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
583 if (CPEs[i].CPEMI == CPEMI)
584 return &CPEs[i];
585 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000586 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000587}
588
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000589/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000590/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000591unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
592 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
593
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000594 unsigned CPI = CPEMI->getOperand(1).getIndex();
595 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
596 unsigned Align = MCP->getConstants()[CPI].getAlignment();
597 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
598 return Log2_32(Align);
599}
600
Jim Grosbach190e7b62012-03-23 23:07:03 +0000601/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000602/// information about the sizes of each block and the locations of all
603/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000604void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000605 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach5d577142009-11-12 17:25:07 +0000606 MBBI != E; ++MBBI) {
607 MachineBasicBlock &MBB = *MBBI;
608
Jim Grosbach5d577142009-11-12 17:25:07 +0000609 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach9785e592009-11-16 18:58:52 +0000610 I != E; ++I)
Evan Cheng7f8e5632011-12-07 07:15:52 +0000611 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach9785e592009-11-16 18:58:52 +0000612 T2JumpTables.push_back(I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000613 }
614}
615
Jim Grosbach190e7b62012-03-23 23:07:03 +0000616/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000617/// information about the sizes of each block, the location of all the water,
618/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000619void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000620initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000621 BBInfo.clear();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000622 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000623
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000624 // First thing, compute the size of all basic blocks, and see if the function
625 // has any inline assembly in it. If so, we have to be conservative about
626 // alignment assumptions, as we don't know for sure the size of any
627 // instructions in the inline assembly.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000628 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000629 computeBlockSize(I);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000630
631 // The known bits of the entry block offset are determined by the function
632 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000633 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000634
635 // Compute block offsets and known bits.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000636 adjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000637
Bill Wendling18581a42010-12-21 01:54:40 +0000638 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000639 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Cheng10043e22007-01-19 07:51:42 +0000640 MBBI != E; ++MBBI) {
641 MachineBasicBlock &MBB = *MBBI;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000642
Evan Cheng10043e22007-01-19 07:51:42 +0000643 // If this block doesn't fall through into the next MBB, then this is
644 // 'water' that a constant pool island could be placed.
645 if (!BBHasFallthrough(&MBB))
646 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000647
Evan Cheng10043e22007-01-19 07:51:42 +0000648 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
649 I != E; ++I) {
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000650 if (I->isDebugValue())
651 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000652
Evan Cheng22c7cf52007-01-25 03:12:46 +0000653 int Opc = I->getOpcode();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000654 if (I->isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000655 bool isCond = false;
656 unsigned Bits = 0;
657 unsigned Scale = 1;
658 int UOpc = Opc;
659 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000660 default:
661 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000662 case ARM::t2BR_JT:
663 T2JumpTables.push_back(I);
664 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000665 case ARM::Bcc:
666 isCond = true;
667 UOpc = ARM::B;
668 // Fallthrough
669 case ARM::B:
670 Bits = 24;
671 Scale = 4;
672 break;
673 case ARM::tBcc:
674 isCond = true;
675 UOpc = ARM::tB;
676 Bits = 8;
677 Scale = 2;
678 break;
679 case ARM::tB:
680 Bits = 11;
681 Scale = 2;
682 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000683 case ARM::t2Bcc:
684 isCond = true;
685 UOpc = ARM::t2B;
686 Bits = 20;
687 Scale = 2;
688 break;
689 case ARM::t2B:
690 Bits = 24;
691 Scale = 2;
692 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000693 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000694
695 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000696 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengf9a4c692007-02-01 10:16:15 +0000697 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000698 }
699
Evan Cheng7fa69642007-01-30 01:18:38 +0000700 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
701 PushPopMIs.push_back(I);
702
Evan Chengd2919a12009-07-23 18:27:47 +0000703 if (Opc == ARM::CONSTPOOL_ENTRY)
704 continue;
705
Evan Cheng10043e22007-01-19 07:51:42 +0000706 // Scan the instructions for constant pool operands.
707 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000708 if (I->getOperand(op).isCPI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000709 // We found one. The addressing mode tells us the max displacement
710 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000711
Evan Cheng10043e22007-01-19 07:51:42 +0000712 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000713 unsigned Bits = 0;
714 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000715 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000716 bool IsSoImm = false;
717
718 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000719 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000720 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000721
722 // Taking the address of a CP entry.
723 case ARM::LEApcrel:
724 // This takes a SoImm, which is 8 bit immediate rotated. We'll
725 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000726 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000727 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000728 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000729 Scale = 4;
730 NegOk = true;
731 IsSoImm = true;
732 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000733 case ARM::t2LEApcrel:
Evan Chengd2919a12009-07-23 18:27:47 +0000734 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000735 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000736 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000737 case ARM::tLEApcrel:
738 Bits = 8;
739 Scale = 4;
740 break;
741
David Majnemer452f1f92013-06-04 17:46:15 +0000742 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000743 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000744 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000745 case ARM::t2LDRpci:
Evan Chengfd522992007-02-01 20:44:52 +0000746 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000747 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000748 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000749
750 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000751 Bits = 8;
752 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000753 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000754
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000755 case ARM::VLDRD:
756 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000757 Bits = 8;
758 Scale = 4; // +-(offset_8*4)
759 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000760 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000761 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000762
Evan Cheng10043e22007-01-19 07:51:42 +0000763 // Remember that this is a user of a CP entry.
Chris Lattnera5bb3702007-12-30 23:10:15 +0000764 unsigned CPI = I->getOperand(op).getIndex();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000765 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000766 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd2919a12009-07-23 18:27:47 +0000767 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000768
769 // Increment corresponding CPEntry reference count.
770 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
771 assert(CPE && "Cannot find a corresponding CPEntry!");
772 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000773
Evan Cheng10043e22007-01-19 07:51:42 +0000774 // Instructions can only use one CP entry, don't bother scanning the
775 // rest of the operands.
776 break;
777 }
778 }
Evan Cheng10043e22007-01-19 07:51:42 +0000779 }
780}
781
Jim Grosbach190e7b62012-03-23 23:07:03 +0000782/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000783/// This function updates BBInfo directly.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000784void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000785 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
786 BBI.Size = 0;
787 BBI.Unalign = 0;
788 BBI.PostAlign = 0;
789
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000790 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
791 ++I) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000792 BBI.Size += TII->GetInstSizeInBytes(I);
793 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
794 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesen14e024d2011-12-08 01:22:39 +0000795 if (I->isInlineAsm())
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000796 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000797 // Also consider instructions that may be shrunk later.
798 else if (isThumb && mayOptimizeThumb2Instruction(I))
799 BBI.Unalign = 1;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000800 }
801
802 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000803 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000804 BBI.PostAlign = 2;
Chad Rosier73b02822012-07-06 23:13:38 +0000805 MBB->getParent()->ensureAlignment(2);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000806 }
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000807}
808
Jim Grosbach190e7b62012-03-23 23:07:03 +0000809/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000810/// from the start of the function. This offset changes as stuff is moved
811/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000812unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000813 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000814
Evan Cheng10043e22007-01-19 07:51:42 +0000815 // The offset is composed of two things: the sum of the sizes of all MBB's
816 // before this instruction's block, and the offset from the start of the block
817 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000818 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000819
820 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000821 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000822 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +0000823 Offset += TII->GetInstSizeInBytes(I);
Evan Cheng10043e22007-01-19 07:51:42 +0000824 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000825 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000826}
827
828/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
829/// ID.
830static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
831 const MachineBasicBlock *RHS) {
832 return LHS->getNumber() < RHS->getNumber();
833}
834
Jim Grosbach190e7b62012-03-23 23:07:03 +0000835/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000836/// machine function, it upsets all of the block numbers. Renumber the blocks
837/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000838void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000839 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000840 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000841
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000842 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000843 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000844 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000845
846 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000847 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000848 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000849 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
850 CompareMBBNumbers);
851 WaterList.insert(IP, NewBB);
852}
853
854
855/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000856/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000857/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000858MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000859 MachineBasicBlock *OrigBB = MI->getParent();
860
861 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000862 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000863 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Cheng10043e22007-01-19 07:51:42 +0000864 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000865 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000866
Evan Cheng10043e22007-01-19 07:51:42 +0000867 // Splice the instructions starting with MI over to NewBB.
868 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000869
Evan Cheng10043e22007-01-19 07:51:42 +0000870 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000871 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000872 // There doesn't seem to be meaningful DebugInfo available; this doesn't
873 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000874 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000875 if (!isThumb)
876 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
877 else
878 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
879 .addImm(ARMCC::AL).addReg(0);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000880 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000881
Evan Cheng10043e22007-01-19 07:51:42 +0000882 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000883 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000884
Evan Cheng10043e22007-01-19 07:51:42 +0000885 // OrigBB branches to NewBB.
886 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000887
Evan Cheng10043e22007-01-19 07:51:42 +0000888 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000889 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000890 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000891 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000892
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000893 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000894 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000895 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000896
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000897 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000898 // available water after it (but not if it's already there, which happens
899 // when splitting before a conditional branch that is followed by an
900 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000901 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +0000902 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
903 CompareMBBNumbers);
904 MachineBasicBlock* WaterBB = *IP;
905 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000906 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000907 else
908 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000909 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000910
Dale Johannesenc17dd572010-07-23 22:50:23 +0000911 // Figure out how large the OrigBB is. As the first half of the original
912 // block, it cannot contain a tablejump. The size includes
913 // the new jump we added. (It should be possible to do this without
914 // recounting everything, but it's very confusing, and this is rarely
915 // executed.)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000916 computeBlockSize(OrigBB);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000917
Dale Johannesenc17dd572010-07-23 22:50:23 +0000918 // Figure out how large the NewMBB is. As the second half of the original
919 // block, it may contain a tablejump.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000920 computeBlockSize(NewBB);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000921
Dale Johannesen01ee5752007-02-25 00:47:03 +0000922 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000923 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000924
925 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000926}
927
Jim Grosbach190e7b62012-03-23 23:07:03 +0000928/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000929/// displacement computation. Update U.KnownAlignment to match its current
930/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000931unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
932 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000933 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
934 unsigned KnownBits = BBI.internalKnownBits();
935
936 // The value read from PC is offset from the actual instruction address.
937 UserOffset += (isThumb ? 4 : 8);
938
939 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
940 // Make sure U.getMaxDisp() returns a constrained range.
941 U.KnownAlignment = (KnownBits >= 2);
942
943 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
944 // purposes of the displacement computation; compensate for that here.
945 // For unknown alignments, getMaxDisp() constrains the range instead.
946 if (isThumb && U.KnownAlignment)
947 UserOffset &= ~3u;
948
949 return UserOffset;
950}
951
Jim Grosbach190e7b62012-03-23 23:07:03 +0000952/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000953/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000954/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +0000955/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000956/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
957/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000958bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +0000959 unsigned TrialOffset, unsigned MaxDisp,
960 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +0000961 if (UserOffset <= TrialOffset) {
962 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +0000963 if (TrialOffset - UserOffset <= MaxDisp)
964 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000965 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000966 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +0000967 if (UserOffset - TrialOffset <= 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 }
971 return false;
972}
973
Jim Grosbach190e7b62012-03-23 23:07:03 +0000974/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +0000975/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000976///
977/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000978bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000979 MachineBasicBlock* Water, CPUser &U,
980 unsigned &Growth) {
981 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
982 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
983 unsigned NextBlockOffset, NextBlockAlignment;
984 MachineFunction::const_iterator NextBlock = Water;
985 if (++NextBlock == MF->end()) {
986 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
987 NextBlockAlignment = 0;
988 } else {
989 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
990 NextBlockAlignment = NextBlock->getAlignment();
991 }
992 unsigned Size = U.CPEMI->getOperand(2).getImm();
993 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +0000994
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000995 // The CPE may be able to hide in the alignment padding before the next
996 // block. It may also cause more padding to be required if it is more aligned
997 // that the next block.
998 if (CPEEnd > NextBlockOffset) {
999 Growth = CPEEnd - NextBlockOffset;
1000 // Compute the padding that would go at the end of the CPE to align the next
1001 // block.
1002 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1003
1004 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001005 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001006 // in blocks between CPE and the user.
1007 if (CPEOffset < UserOffset)
1008 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1009 } else
1010 // CPE fits in existing padding.
1011 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001012
Jim Grosbach190e7b62012-03-23 23:07:03 +00001013 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001014}
1015
Jim Grosbach190e7b62012-03-23 23:07:03 +00001016/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001017/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001018bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001019 MachineInstr *CPEMI, unsigned MaxDisp,
1020 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001021 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001022
Dale Johannesene18b13b2007-02-23 05:02:36 +00001023 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001024 DEBUG({
1025 unsigned Block = MI->getParent()->getNumber();
1026 const BasicBlockInfo &BBI = BBInfo[Block];
1027 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1028 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001029 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001030 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001031 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1032 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1033 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001034 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001035 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001036
Jim Grosbach190e7b62012-03-23 23:07:03 +00001037 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001038}
1039
Evan Chenge4510972009-01-28 00:53:34 +00001040#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001041/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1042/// unconditionally branches to its only successor.
1043static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1044 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1045 return false;
1046
1047 MachineBasicBlock *Succ = *MBB->succ_begin();
1048 MachineBasicBlock *Pred = *MBB->pred_begin();
1049 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001050 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1051 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001052 return PredMI->getOperand(0).getMBB() == Succ;
1053 return false;
1054}
Evan Chenge4510972009-01-28 00:53:34 +00001055#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001056
Jim Grosbach190e7b62012-03-23 23:07:03 +00001057void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001058 unsigned BBNum = BB->getNumber();
1059 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001060 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001061 // Include the alignment of the current block.
1062 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1063 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1064 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001065
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001066 // This is where block i begins. Stop if the offset is already correct,
1067 // and we have updated 2 blocks. This is the maximum number of blocks
1068 // changed before calling this function.
1069 if (i > BBNum + 2 &&
1070 BBInfo[i].Offset == Offset &&
1071 BBInfo[i].KnownBits == KnownBits)
1072 break;
1073
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001074 BBInfo[i].Offset = Offset;
1075 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001076 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001077}
1078
Jim Grosbach190e7b62012-03-23 23:07:03 +00001079/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001080/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001081/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001082/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001083
Jim Grosbach190e7b62012-03-23 23:07:03 +00001084bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1085 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001086 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001087 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1088 assert(CPE && "Unexpected!");
1089 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001090 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001091 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001092 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001093 return true;
1094 }
1095 return false;
1096}
1097
Dale Johannesene18b13b2007-02-23 05:02:36 +00001098/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1099/// if not, see if an in-range clone of the CPE is in range, and if so,
1100/// change the data structures so the user references the clone. Returns:
1101/// 0 = no existing entry found
1102/// 1 = entry found, and there were no code insertions or deletions
1103/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001104int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001105{
1106 MachineInstr *UserMI = U.MI;
1107 MachineInstr *CPEMI = U.CPEMI;
1108
1109 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001110 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1111 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001112 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001113 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001114 }
1115
Dale Johannesene18b13b2007-02-23 05:02:36 +00001116 // No. Look for previously created clones of the CPE that are in range.
Chris Lattnera5bb3702007-12-30 23:10:15 +00001117 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001118 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1119 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1120 // We already tried this one
1121 if (CPEs[i].CPEMI == CPEMI)
1122 continue;
1123 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001124 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001125 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001126 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001127 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001128 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001129 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001130 // Point the CPUser node to the replacement
1131 U.CPEMI = CPEs[i].CPEMI;
1132 // Change the CPI in the instruction operand to refer to the clone.
1133 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001134 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001135 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001136 break;
1137 }
1138 // Adjust the refcount of the clone...
1139 CPEs[i].RefCount++;
1140 // ...and the original. If we didn't remove the old entry, none of the
1141 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001142 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001143 }
1144 }
1145 return 0;
1146}
1147
Dale Johannesen440995b2007-02-28 18:41:23 +00001148/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1149/// the specific unconditional branch instruction.
1150static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001151 switch (Opc) {
1152 case ARM::tB:
1153 return ((1<<10)-1)*2;
1154 case ARM::t2B:
1155 return ((1<<23)-1)*2;
1156 default:
1157 break;
1158 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001159
David Goodwin27303cd2009-06-30 18:04:13 +00001160 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001161}
1162
Jim Grosbach190e7b62012-03-23 23:07:03 +00001163/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001164/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001165/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001166/// is set to the WaterList entry. For Thumb, prefer water that will not
1167/// introduce padding to water that will. To ensure that this pass
1168/// terminates, the CPE location for a particular CPUser is only allowed to
1169/// move to a lower address, so search backward from the end of the list and
1170/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001171bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Bob Wilson2f9be502009-10-15 20:49:47 +00001172 water_iterator &WaterIter) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001173 if (WaterList.empty())
1174 return false;
1175
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001176 unsigned BestGrowth = ~0u;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001177 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001178 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001179 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001180 // Check if water is in range and is either at a lower address than the
1181 // current "high water mark" or a new water block that was created since
1182 // the previous iteration by inserting an unconditional branch. In the
1183 // latter case, we want to allow resetting the high water mark back to
1184 // this new water since we haven't seen it before. Inserting branches
1185 // should be relatively uncommon and when it does happen, we want to be
1186 // sure to take advantage of it for all the CPEs near that block, so that
1187 // we don't insert more branches than necessary.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001188 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001189 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001190 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001191 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1192 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001193 // This is the least amount of required padding seen so far.
1194 BestGrowth = Growth;
1195 WaterIter = IP;
1196 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1197 << " Growth=" << Growth << '\n');
1198
1199 // Keep looking unless it is perfect.
1200 if (BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001201 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001202 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001203 if (IP == B)
1204 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001205 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001206 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001207}
1208
Jim Grosbach190e7b62012-03-23 23:07:03 +00001209/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001210/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1211/// block is used if in range, and the conditional branch munged so control
1212/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001213/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001214/// block following which the new island can be inserted (the WaterList
1215/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001216void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001217 unsigned UserOffset,
1218 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001219 CPUser &U = CPUsers[CPUserIndex];
1220 MachineInstr *UserMI = U.MI;
1221 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001222 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001223 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001224 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001225
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001226 // If the block does not end in an unconditional branch already, and if the
1227 // end of the block is within range, make new water there. (The addition
1228 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001229 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001230 if (BBHasFallthrough(UserMBB)) {
1231 // Size of branch to insert.
1232 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001233 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001234 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001235
Jim Grosbach190e7b62012-03-23 23:07:03 +00001236 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001237 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1238 << format(", expected CPE offset %#x\n", CPEOffset));
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001239 NewMBB = std::next(MachineFunction::iterator(UserMBB));
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001240 // Add an unconditional branch from UserMBB to fallthrough block. Record
1241 // it for branch lengthening; this new branch will not get out of range,
1242 // but if the preceding conditional branch is out of range, the targets
1243 // will be exchanged, and the altered branch may be out of range, so the
1244 // machinery has to know about it.
1245 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1246 if (!isThumb)
1247 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1248 else
1249 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1250 .addImm(ARMCC::AL).addReg(0);
1251 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1252 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1253 MaxDisp, false, UncondBr));
Akira Hatanaka442b40c2015-01-08 20:44:50 +00001254 computeBlockSize(UserMBB);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001255 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001256 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001257 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001258 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001259
1260 // What a big block. Find a place within the block to split it. This is a
1261 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1262 // entries are 4 bytes: if instruction I references island CPE, and
1263 // instruction I+1 references CPE', it will not work well to put CPE as far
1264 // forward as possible, since then CPE' cannot immediately follow it (that
1265 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1266 // need to create a new island. So, we make a first guess, then walk through
1267 // the instructions between the one currently being looked at and the
1268 // possible insertion point, and make sure any other instructions that
1269 // reference CPEs will be able to use the same island area; if not, we back
1270 // up the insertion point.
1271
1272 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001273 // point where we can add a 4-byte branch instruction, and then align to
1274 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001275 unsigned LogAlign = MF->getAlignment();
1276 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1277 unsigned KnownBits = UserBBI.internalKnownBits();
1278 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001279 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001280 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1281 BaseInsertOffset));
1282
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001283 // The 4 in the following is for the unconditional branch we'll be inserting
1284 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001285 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001286 BaseInsertOffset -= 4;
1287
1288 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1289 << " la=" << LogAlign
1290 << " kb=" << KnownBits
1291 << " up=" << UPad << '\n');
1292
1293 // This could point off the end of the block if we've already got constant
1294 // pool entries following this block; only the last one is in the water list.
1295 // Back past any possible branches (allow for a conditional and a maximally
1296 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001297 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001298 // Ensure BaseInsertOffset is larger than the offset of the instruction
1299 // following UserMI so that the loop which searches for the split point
1300 // iterates at least once.
1301 BaseInsertOffset =
1302 std::max(UserBBI.postOffset() - UPad - 8,
1303 UserOffset + TII->GetInstSizeInBytes(UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001304 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1305 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001306 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001307 CPEMI->getOperand(2).getImm();
1308 MachineBasicBlock::iterator MI = UserMI;
1309 ++MI;
1310 unsigned CPUIndex = CPUserIndex+1;
1311 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001312 MachineInstr *LastIT = nullptr;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001313 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1314 Offset < BaseInsertOffset;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001315 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001316 assert(MI != UserMBB->end() && "Fell off end of block");
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001317 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1318 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001319 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001320 // Shift intertion point by one unit of alignment so it is within reach.
1321 BaseInsertOffset -= 1u << LogAlign;
1322 EndInsertOffset -= 1u << LogAlign;
1323 }
1324 // This is overly conservative, as we don't account for CPEMIs being
1325 // reused within the block, but it doesn't matter much. Also assume CPEs
1326 // are added in order with alignment padding. We may eventually be able
1327 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001328 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001329 CPUIndex++;
1330 }
1331
1332 // Remember the last IT instruction.
1333 if (MI->getOpcode() == ARM::t2IT)
1334 LastIT = MI;
1335 }
1336
1337 --MI;
1338
1339 // Avoid splitting an IT block.
1340 if (LastIT) {
1341 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001342 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001343 if (CC != ARMCC::AL)
1344 MI = LastIT;
1345 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001346
1347 // We really must not split an IT block.
1348 DEBUG(unsigned PredReg;
1349 assert(!isThumb || getITInstrPredicate(MI, PredReg) == ARMCC::AL));
1350
Jim Grosbach190e7b62012-03-23 23:07:03 +00001351 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001352}
1353
Jim Grosbach190e7b62012-03-23 23:07:03 +00001354/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001355/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001356/// place in-range. Return true if we changed any addresses (thus must run
1357/// another pass of branch lengthening), false otherwise.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001358bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001359 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001360 MachineInstr *UserMI = U.MI;
1361 MachineInstr *CPEMI = U.CPEMI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001362 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001363 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001364 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001365 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001366
Dale Johannesene18b13b2007-02-23 05:02:36 +00001367 // See if the current entry is within range, or there is a clone of it
1368 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001369 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001370 if (result==1) return false;
1371 else if (result==2) return true;
1372
1373 // No existing clone of this CPE is within range.
1374 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001375 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001376
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001377 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001378 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001379 MachineBasicBlock *NewMBB;
1380 water_iterator IP;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001381 if (findAvailableWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001382 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001383 MachineBasicBlock *WaterBB = *IP;
1384
1385 // If the original WaterList entry was "new water" on this iteration,
1386 // propagate that to the new island. This is just keeping NewWaterList
1387 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001388 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001389 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001390
Bob Wilson2f9be502009-10-15 20:49:47 +00001391 // The new CPE goes before the following block (NewMBB).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001392 NewMBB = std::next(MachineFunction::iterator(WaterBB));
Bob Wilson2f9be502009-10-15 20:49:47 +00001393
1394 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001395 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001396 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001397 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001398
Jim Grosbach190e7b62012-03-23 23:07:03 +00001399 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001400 // called while handling branches so that the water will be seen on the
1401 // next iteration for constant pools, but in this context, we don't want
1402 // it. Check for this so it will be removed from the WaterList.
1403 // Also remove any entry from NewWaterList.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001404 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
Bob Wilson2f9be502009-10-15 20:49:47 +00001405 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1406 if (IP != WaterList.end())
1407 NewWaterList.erase(WaterBB);
1408
1409 // We are adding new water. Update NewWaterList.
1410 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001411 }
1412
Bob Wilson2f9be502009-10-15 20:49:47 +00001413 // Remove the original WaterList entry; we want subsequent insertions in
1414 // this vicinity to go after the one we're about to insert. This
1415 // considerably reduces the number of times we have to move the same CPE
1416 // more than once and is also important to ensure the algorithm terminates.
1417 if (IP != WaterList.end())
1418 WaterList.erase(IP);
1419
Dale Johannesene18b13b2007-02-23 05:02:36 +00001420 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001421 MF->insert(NewMBB, NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001422
1423 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001424 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001425
1426 // Decrement the old entry, and remove it if refcount becomes 0.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001427 decrementCPEReferenceCount(CPI, CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001428
1429 // Now that we have an island to add the CPE to, clone the original CPE and
1430 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001431 U.HighWaterMark = NewIsland;
Chris Lattner6f306d72010-04-02 20:16:16 +00001432 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Cheng10043e22007-01-19 07:51:42 +00001433 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001434 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001435 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001436
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001437 // Mark the basic block as aligned as required by the const-pool entry.
1438 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001439
Evan Cheng10043e22007-01-19 07:51:42 +00001440 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001441 BBInfo[NewIsland->getNumber()].Size += Size;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001442 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001443
Evan Cheng10043e22007-01-19 07:51:42 +00001444 // Finally, change the CPI in the instruction operand to be ID.
1445 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001446 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001447 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001448 break;
1449 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001450
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001451 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001452 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001453
Evan Cheng10043e22007-01-19 07:51:42 +00001454 return true;
1455}
1456
Jim Grosbach190e7b62012-03-23 23:07:03 +00001457/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001458/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001459void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001460 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001461 unsigned Size = CPEMI->getOperand(2).getImm();
1462 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001463 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001464 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001465 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001466 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001467
Evan Chengab28b9a2013-02-21 18:37:54 +00001468 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001469 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001470 } else
1471 // Entries are sorted by descending alignment, so realign from the front.
1472 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1473
Jim Grosbach190e7b62012-03-23 23:07:03 +00001474 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001475 // An island has only one predecessor BB and one successor BB. Check if
1476 // this BB's predecessor jumps directly to this BB's successor. This
1477 // shouldn't happen currently.
1478 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1479 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001480}
1481
Jim Grosbach190e7b62012-03-23 23:07:03 +00001482/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001483/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001484bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001485 unsigned MadeChange = false;
1486 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1487 std::vector<CPEntry> &CPEs = CPEntries[i];
1488 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1489 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001490 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001491 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001492 MadeChange = true;
1493 }
1494 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001495 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001496 return MadeChange;
1497}
1498
Jim Grosbach190e7b62012-03-23 23:07:03 +00001499/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001500/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001501bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001502 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001503 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001504 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001505 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001506
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001507 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001508 << " from BB#" << MI->getParent()->getNumber()
1509 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001510 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001511 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001512
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001513 if (BrOffset <= DestOffset) {
1514 // Branch before the Dest.
1515 if (DestOffset-BrOffset <= MaxDisp)
1516 return true;
1517 } else {
1518 if (BrOffset-DestOffset <= MaxDisp)
1519 return true;
1520 }
1521 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001522}
1523
Jim Grosbach190e7b62012-03-23 23:07:03 +00001524/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001525/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001526bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001527 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001528 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001529
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001530 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001531 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001532 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001533
Evan Cheng7fa69642007-01-30 01:18:38 +00001534 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001535 return fixupUnconditionalBr(Br);
1536 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001537}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001538
Jim Grosbach190e7b62012-03-23 23:07:03 +00001539/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001540/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001541/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001542/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001543bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001544ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001545 MachineInstr *MI = Br.MI;
1546 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001547 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001548 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001549
1550 // Use BL to implement far jump.
1551 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001552 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001553 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001554 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001555 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001556 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001557
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001558 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001559
Evan Cheng7fa69642007-01-30 01:18:38 +00001560 return true;
1561}
1562
Jim Grosbach190e7b62012-03-23 23:07:03 +00001563/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001564/// far away to fit in its displacement field. It is converted to an inverse
1565/// conditional branch + an unconditional branch to the destination.
1566bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001567ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001568 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001569 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001570
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001571 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001572 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001573 // blt L1
1574 // =>
1575 // bge L2
1576 // b L1
1577 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001578 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001579 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001580 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001581
1582 // If the branch is at the end of its MBB and that has a fall-through block,
1583 // direct the updated conditional branch to the fall-through block. Otherwise,
1584 // split the MBB before the next instruction.
1585 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001586 MachineInstr *BMI = &MBB->back();
1587 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001588
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001589 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001590 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001591 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001592 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001593 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001594 // condition and swap destinations:
1595 // beq L1
1596 // b L2
1597 // =>
1598 // bne L2
1599 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001600 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001601 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001602 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001603 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001604 BMI->getOperand(0).setMBB(DestBB);
1605 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001606 MI->getOperand(1).setImm(CC);
1607 return true;
1608 }
1609 }
1610 }
1611
1612 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001613 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001614 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001615 // branch to the destination.
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +00001616 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001617 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001618 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001619 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001620 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001621 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001622
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001623 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001624 << " also invert condition and change dest. to BB#"
1625 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001626
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001627 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001628 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001629 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001630 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001631 Br.MI = &MBB->back();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001632 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001633 if (isThumb)
1634 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1635 .addImm(ARMCC::AL).addReg(0);
1636 else
1637 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001638 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001639 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001640 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001641
1642 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001643 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001644 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001645 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001646 return true;
1647}
Evan Cheng7fa69642007-01-30 01:18:38 +00001648
Jim Grosbach190e7b62012-03-23 23:07:03 +00001649/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001650/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1651/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001652bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001653 bool MadeChange = false;
1654 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1655 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001656 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001657 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001658 MI->getOperand(2).getReg() == ARM::PC &&
1659 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001660 // Create the new insn and copy the predicate from the old.
1661 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1662 .addOperand(MI->getOperand(0))
1663 .addOperand(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001664 MI->eraseFromParent();
1665 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001666 }
1667 }
1668 return MadeChange;
1669}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001670
Jim Grosbach190e7b62012-03-23 23:07:03 +00001671// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001672// below may shrink MI.
1673bool
1674ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1675 switch(MI->getOpcode()) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001676 // optimizeThumb2Instructions.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001677 case ARM::t2LEApcrel:
1678 case ARM::t2LDRpci:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001679 // optimizeThumb2Branches.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001680 case ARM::t2B:
1681 case ARM::t2Bcc:
1682 case ARM::tBcc:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001683 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001684 case ARM::t2BR_JT:
1685 return true;
1686 }
1687 return false;
1688}
1689
Jim Grosbach190e7b62012-03-23 23:07:03 +00001690bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001691 bool MadeChange = false;
1692
1693 // Shrink ADR and LDR from constantpool.
1694 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1695 CPUser &U = CPUsers[i];
1696 unsigned Opcode = U.MI->getOpcode();
1697 unsigned NewOpc = 0;
1698 unsigned Scale = 1;
1699 unsigned Bits = 0;
1700 switch (Opcode) {
1701 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001702 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001703 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1704 NewOpc = ARM::tLEApcrel;
1705 Bits = 8;
1706 Scale = 4;
1707 }
1708 break;
1709 case ARM::t2LDRpci:
1710 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1711 NewOpc = ARM::tLDRpci;
1712 Bits = 8;
1713 Scale = 4;
1714 }
1715 break;
1716 }
1717
1718 if (!NewOpc)
1719 continue;
1720
Jim Grosbach190e7b62012-03-23 23:07:03 +00001721 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001722 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001723
1724 // Be conservative with inline asm.
1725 if (!U.KnownAlignment)
1726 MaxOffs -= 2;
1727
Evan Chengdb73d682009-08-14 00:32:16 +00001728 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001729 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001730 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001731 U.MI->setDesc(TII->get(NewOpc));
1732 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001733 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001734 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001735 ++NumT2CPShrunk;
1736 MadeChange = true;
1737 }
1738 }
1739
Jim Grosbach190e7b62012-03-23 23:07:03 +00001740 MadeChange |= optimizeThumb2Branches();
1741 MadeChange |= optimizeThumb2JumpTables();
Evan Chengdb73d682009-08-14 00:32:16 +00001742 return MadeChange;
1743}
1744
Jim Grosbach190e7b62012-03-23 23:07:03 +00001745bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001746 bool MadeChange = false;
1747
1748 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1749 ImmBranch &Br = ImmBranches[i];
1750 unsigned Opcode = Br.MI->getOpcode();
1751 unsigned NewOpc = 0;
1752 unsigned Scale = 1;
1753 unsigned Bits = 0;
1754 switch (Opcode) {
1755 default: break;
1756 case ARM::t2B:
1757 NewOpc = ARM::tB;
1758 Bits = 11;
1759 Scale = 2;
1760 break;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001761 case ARM::t2Bcc: {
Evan Chenge41903b2009-08-14 18:31:44 +00001762 NewOpc = ARM::tBcc;
1763 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001764 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001765 break;
1766 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001767 }
1768 if (NewOpc) {
1769 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1770 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001771 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001772 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001773 Br.MI->setDesc(TII->get(NewOpc));
1774 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001775 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001776 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001777 ++NumT2BrShrunk;
1778 MadeChange = true;
1779 }
1780 }
1781
1782 Opcode = Br.MI->getOpcode();
1783 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001784 continue;
1785
Evan Cheng6bb95252012-01-14 01:53:46 +00001786 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1787 // so this transformation is not safe.
1788 if (!Br.MI->killsRegister(ARM::CPSR))
1789 continue;
1790
Evan Cheng6f29ad92009-10-31 23:46:45 +00001791 NewOpc = 0;
1792 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001793 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001794 if (Pred == ARMCC::EQ)
1795 NewOpc = ARM::tCBZ;
1796 else if (Pred == ARMCC::NE)
1797 NewOpc = ARM::tCBNZ;
1798 if (!NewOpc)
1799 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001800 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001801 // Check if the distance is within 126. Subtract starting offset by 2
1802 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001803 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001804 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001805 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001806 MachineBasicBlock::iterator CmpMI = Br.MI;
1807 if (CmpMI != Br.MI->getParent()->begin()) {
1808 --CmpMI;
1809 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1810 unsigned Reg = CmpMI->getOperand(0).getReg();
Craig Topperf6e7e122012-03-27 07:21:54 +00001811 Pred = getInstrPredicate(CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001812 if (Pred == ARMCC::AL &&
1813 CmpMI->getOperand(1).getImm() == 0 &&
1814 isARMLowRegister(Reg)) {
1815 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001816 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001817 MachineInstr *NewBR =
1818 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1819 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1820 CmpMI->eraseFromParent();
1821 Br.MI->eraseFromParent();
1822 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001823 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001824 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001825 ++NumCBZ;
1826 MadeChange = true;
1827 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001828 }
1829 }
Evan Chenge41903b2009-08-14 18:31:44 +00001830 }
1831 }
1832
1833 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001834}
1835
Jim Grosbach190e7b62012-03-23 23:07:03 +00001836/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00001837/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001838bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00001839 bool MadeChange = false;
1840
1841 // FIXME: After the tables are shrunk, can we get rid some of the
1842 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001843 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00001844 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001845
Evan Chengc6d70ae2009-07-29 02:18:14 +00001846 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1847 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1848 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00001849 const MCInstrDesc &MCID = MI->getDesc();
1850 unsigned NumOps = MCID.getNumOperands();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001851 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Chengc6d70ae2009-07-29 02:18:14 +00001852 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1853 unsigned JTI = JTOP.getIndex();
1854 assert(JTI < JT.size());
1855
Jim Grosbach8d92ec42009-11-11 02:47:19 +00001856 bool ByteOk = true;
1857 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001858 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00001859 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001860 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1861 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001862 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00001863 // Negative offset is not ok. FIXME: We should change BB layout to make
1864 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00001865 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00001866 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00001867 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00001868 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00001869 HalfWordOk = false;
1870 if (!ByteOk && !HalfWordOk)
1871 break;
1872 }
1873
1874 if (ByteOk || HalfWordOk) {
1875 MachineBasicBlock *MBB = MI->getParent();
1876 unsigned BaseReg = MI->getOperand(0).getReg();
1877 bool BaseRegKill = MI->getOperand(0).isKill();
1878 if (!BaseRegKill)
1879 continue;
1880 unsigned IdxReg = MI->getOperand(1).getReg();
1881 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbach40eda102010-07-07 22:51:22 +00001882
1883 // Scan backwards to find the instruction that defines the base
1884 // register. Due to post-RA scheduling, we can't count on it
1885 // immediately preceding the branch instruction.
Evan Chengc6d70ae2009-07-29 02:18:14 +00001886 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbach40eda102010-07-07 22:51:22 +00001887 MachineBasicBlock::iterator B = MBB->begin();
1888 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1889 --PrevI;
1890
1891 // If for some reason we didn't find it, we can't do anything, so
1892 // just skip this one.
1893 if (!PrevI->definesRegister(BaseReg))
Evan Chengc6d70ae2009-07-29 02:18:14 +00001894 continue;
1895
Jim Grosbach40eda102010-07-07 22:51:22 +00001896 MachineInstr *AddrMI = PrevI;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001897 bool OptOk = true;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001898 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbach40eda102010-07-07 22:51:22 +00001899 // Make sure it only defines the base register and kills any uses
1900 // other than the index register.
Evan Chengc6d70ae2009-07-29 02:18:14 +00001901 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1902 const MachineOperand &MO = AddrMI->getOperand(k);
1903 if (!MO.isReg() || !MO.getReg())
1904 continue;
1905 if (MO.isDef() && MO.getReg() != BaseReg) {
1906 OptOk = false;
1907 break;
1908 }
1909 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1910 OptOk = false;
1911 break;
1912 }
1913 }
1914 if (!OptOk)
1915 continue;
1916
Owen Anderson9a4d4282010-12-13 22:51:08 +00001917 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbach40eda102010-07-07 22:51:22 +00001918 // that gave us the initial base register definition.
1919 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1920 ;
1921
Owen Anderson9a4d4282010-12-13 22:51:08 +00001922 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chengdb73d682009-08-14 00:32:16 +00001923 // to delete it as well.
Jim Grosbach40eda102010-07-07 22:51:22 +00001924 MachineInstr *LeaMI = PrevI;
Evan Chengdb73d682009-08-14 00:32:16 +00001925 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson9a4d4282010-12-13 22:51:08 +00001926 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Chengc6d70ae2009-07-29 02:18:14 +00001927 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Chenge64f48b2009-08-01 06:13:52 +00001928 OptOk = false;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001929
Evan Chenge64f48b2009-08-01 06:13:52 +00001930 if (!OptOk)
1931 continue;
1932
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001933 DEBUG(dbgs() << "Shrink JT: " << *MI << " addr: " << *AddrMI
1934 << " lea: " << *LeaMI);
Jim Grosbach81af4f92010-11-29 21:28:32 +00001935 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Chad Rosier620fb222014-12-12 23:27:40 +00001936 MachineBasicBlock::iterator MI_JT = MI;
1937 MachineInstr *NewJTMI =
1938 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Evan Chenge64f48b2009-08-01 06:13:52 +00001939 .addReg(IdxReg, getKillRegState(IdxRegKill))
1940 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1941 .addImm(MI->getOperand(JTOpIdx+1).getImm());
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001942 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00001943 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1944 // is 2-byte aligned. For now, asm printer will fix it up.
1945 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1946 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1947 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1948 OrigSize += TII->GetInstSizeInBytes(MI);
1949
1950 AddrMI->eraseFromParent();
1951 LeaMI->eraseFromParent();
1952 MI->eraseFromParent();
1953
1954 int delta = OrigSize - NewSize;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001955 BBInfo[MBB->getNumber()].Size -= delta;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001956 adjustBBOffsetsAfter(MBB);
Evan Chenge64f48b2009-08-01 06:13:52 +00001957
1958 ++NumTBs;
1959 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001960 }
1961 }
1962
1963 return MadeChange;
1964}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00001965
Jim Grosbach190e7b62012-03-23 23:07:03 +00001966/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00001967/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001968bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00001969 bool MadeChange = false;
1970
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001971 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00001972 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001973
Jim Grosbach5d577142009-11-12 17:25:07 +00001974 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1975 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1976 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00001977 const MCInstrDesc &MCID = MI->getDesc();
1978 unsigned NumOps = MCID.getNumOperands();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001979 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach5d577142009-11-12 17:25:07 +00001980 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1981 unsigned JTI = JTOP.getIndex();
1982 assert(JTI < JT.size());
1983
1984 // We prefer if target blocks for the jump table come after the jump
1985 // instruction so we can use TB[BH]. Loop through the target blocks
1986 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00001987 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00001988 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1989 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1990 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00001991 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00001992
Jim Grosbach9785e592009-11-16 18:58:52 +00001993 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00001994 // The destination precedes the switch. Try to move the block forward
1995 // so we have a positive offset.
1996 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00001997 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00001998 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00001999 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002000 MadeChange = true;
2001 }
2002 }
2003 }
2004
2005 return MadeChange;
2006}
2007
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002008MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002009adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002010 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002011 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002012 // table that branches back to the actual target. This is a very simple
2013 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002014 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002015 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002016 SmallVector<MachineOperand, 4> CondPrior;
2017 MachineFunction::iterator BBi = BB;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002018 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002019
Jim Grosbach47d5e332009-11-16 17:10:56 +00002020 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002021 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002022
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002023 // If the block ends in an unconditional branch, move it. The prior block
2024 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002025 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002026 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002027 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002028 BB->moveAfter(JTBB);
2029 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002030 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002031 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002032 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002033 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002034 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002035 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002036
2037 // Create a new MBB for the code after the jump BB.
2038 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002039 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002040 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002041 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002042
2043 // Add an unconditional branch from NewBB to BB.
2044 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2045 // correspond directly to anything in the source.
2046 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson29cfe6c2011-09-09 21:48:23 +00002047 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2048 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002049
Jim Grosbach43d21082009-11-14 20:10:18 +00002050 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002051 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002052
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002053 // Update the CFG.
2054 NewBB->addSuccessor(BB);
2055 JTBB->removeSuccessor(BB);
2056 JTBB->addSuccessor(NewBB);
2057
Jim Grosbach5d577142009-11-12 17:25:07 +00002058 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002059 return NewBB;
2060}