blob: 6fa5ad7d0522c65021499c9603017c85f815bee6 [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;
Peter Collingbourne7e814d12015-05-21 23:20:55 +0000183 private:
Evan Cheng10043e22007-01-19 07:51:42 +0000184 unsigned MaxDisp;
Peter Collingbourne7e814d12015-05-21 23:20:55 +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
Peter Collingbourne7e814d12015-05-21 23:20:55 +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;
Matthias Braunfa3872e2015-05-18 20:27:55 +0000233 unsigned UncondBr;
234 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
Evan Cheng010ae382007-01-25 23:18:59 +0000235 : 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:
Peter Collingbourne7e814d12015-05-21 23:20:55 +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();
Tim Northover688f7bb2015-05-13 20:28:32 +0000304 unsigned removeDeadDefinitions(MachineInstr *MI, unsigned BaseReg,
305 unsigned IdxReg);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000306 bool optimizeThumb2JumpTables();
307 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000308 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000309
Jim Grosbach190e7b62012-03-23 23:07:03 +0000310 void computeBlockSize(MachineBasicBlock *MBB);
311 unsigned getOffsetOf(MachineInstr *MI) const;
312 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000313 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000314 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000315
Jim Grosbach190e7b62012-03-23 23:07:03 +0000316 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000317 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000318 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000319 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000320 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000321 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000322 }
Evan Cheng10043e22007-01-19 07:51:42 +0000323 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000324 char ARMConstantIslands::ID = 0;
Evan Cheng10043e22007-01-19 07:51:42 +0000325}
326
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000327/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000328void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000329#ifndef NDEBUG
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000330 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd2919a12009-07-23 18:27:47 +0000331 MBBI != E; ++MBBI) {
332 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesenbd97f5d2011-12-08 01:10:05 +0000333 unsigned MBBId = MBB->getNumber();
Jakob Stoklund Olesenbd97f5d2011-12-08 01:10:05 +0000334 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000335 }
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000336 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000337 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
338 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000339 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000340 // Verify offset using the real max displacement without the safety
341 // adjustment.
342 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000343 /* DoDump = */ true)) {
344 DEBUG(dbgs() << "OK\n");
345 continue;
346 }
347 DEBUG(dbgs() << "Out of range.\n");
348 dumpBBs();
349 DEBUG(MF->dump());
350 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000351 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000352#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000353}
354
355/// print block size and offset information - debugging
356void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000357 DEBUG({
358 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
359 const BasicBlockInfo &BBI = BBInfo[J];
360 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
361 << " kb=" << unsigned(BBI.KnownBits)
362 << " ua=" << unsigned(BBI.Unalign)
363 << " pa=" << unsigned(BBI.PostAlign)
364 << format(" size=%#x\n", BBInfo[J].Size);
365 }
366 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000367}
368
Evan Cheng22c7cf52007-01-25 03:12:46 +0000369/// createARMConstantIslandPass - returns an instance of the constpool
370/// island pass.
Evan Cheng10043e22007-01-19 07:51:42 +0000371FunctionPass *llvm::createARMConstantIslandPass() {
372 return new ARMConstantIslands();
373}
374
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000375bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
376 MF = &mf;
377 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000378
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000379 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000380 << MCP->getConstants().size() << " CP entries, aligned to "
381 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000382
Eric Christopher1b21f002015-01-29 00:19:33 +0000383 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
384 TII = STI->getInstrInfo();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000385 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000386
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000387 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000388 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000389 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000390
391 HasFarJump = false;
392
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000393 // This pass invalidates liveness information when it splits basic blocks.
394 MF->getRegInfo().invalidateLiveness();
395
Evan Cheng10043e22007-01-19 07:51:42 +0000396 // Renumber all of the machine basic blocks in the function, guaranteeing that
397 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000398 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000399
Jim Grosbach5d577142009-11-12 17:25:07 +0000400 // Try to reorder and otherwise adjust the block layout to make good use
401 // of the TB[BH] instructions.
402 bool MadeChange = false;
403 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000404 scanFunctionJumpTables();
405 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000406 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000407 T2JumpTables.clear();
408 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000409 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000410 }
411
Evan Cheng10043e22007-01-19 07:51:42 +0000412 // Perform the initial placement of the constant pool entries. To start with,
413 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000414 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000415 if (!MCP->isEmpty())
Peter Collingbourne7e814d12015-05-21 23:20:55 +0000416 doInitialPlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000417
Evan Cheng10043e22007-01-19 07:51:42 +0000418 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000419 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000420
Evan Cheng10043e22007-01-19 07:51:42 +0000421 // Do the initial scan of the function, building up information about the
422 // sizes of each block, the location of all the water, and finding all of the
423 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000424 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000425 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000426 DEBUG(dumpBBs());
427
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000428 // Functions with jump tables need an alignment of 4 because they use the ADR
429 // instruction, which aligns the PC to 4 bytes before adding an offset.
430 if (!T2JumpTables.empty())
431 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000432
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000433 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000434 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000435
Evan Cheng7fa69642007-01-30 01:18:38 +0000436 // Iteratively place constant pool entries and fix up branches until there
437 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000438 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000439 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000440 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000441 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000442 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000443 CPChange |= handleConstantPoolUser(i);
Evan Cheng82ff0222009-08-07 07:35:21 +0000444 if (CPChange && ++NoCPIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000445 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000446 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000447
Bob Wilson2f9be502009-10-15 20:49:47 +0000448 // Clear NewWaterList now. If we split a block for branches, it should
449 // appear as "new water" for the next iteration of constant pool placement.
450 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000451
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000452 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000453 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000454 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000455 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000456 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000457 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000458 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000459
460 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000461 break;
462 MadeChange = true;
463 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000464
Evan Chengdb73d682009-08-14 00:32:16 +0000465 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000466 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000467 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000468
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000469 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000470 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000471
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000472 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
473 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000474 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000475 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000476
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000477 // Save the mapping between original and cloned constpool entries.
478 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
479 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
480 const CPEntry & CPE = CPEntries[i][j];
Peter Collingbourne7e814d12015-05-21 23:20:55 +0000481 AFI->recordCPEClone(i, CPE.CPI);
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000482 }
483 }
484
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000485 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000486
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000487 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000488 WaterList.clear();
489 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000490 CPEntries.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000491 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000492 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000493 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000494
495 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000496}
497
Peter Collingbourne7e814d12015-05-21 23:20:55 +0000498/// doInitialPlacement - Perform the initial placement of the constant pool
499/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000500void
Peter Collingbourne7e814d12015-05-21 23:20:55 +0000501ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000502 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000503 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
504 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000505
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000506 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000507 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000508
509 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000510 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000511
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000512 // The function needs to be as aligned as the basic blocks. The linker may
513 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000514 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000515
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000516 // Order the entries in BB by descending alignment. That ensures correct
517 // alignment of all entries as long as BB is sufficiently aligned. Keep
518 // track of the insertion point for each alignment. We are going to bucket
519 // sort the entries as they are created.
520 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000521
Evan Cheng10043e22007-01-19 07:51:42 +0000522 // Add all of the constants from the constant pool to the end block, use an
523 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000524 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000525
Eric Christopher8b770652015-01-26 19:03:15 +0000526 const DataLayout &TD = *MF->getTarget().getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000527 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000528 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000529 assert(Size >= 4 && "Too small constant pool entry");
530 unsigned Align = CPs[i].getAlignment();
531 assert(isPowerOf2_32(Align) && "Invalid alignment");
532 // Verify that all constant pool entries are a multiple of their alignment.
533 // If not, we would have to pad them out so that instructions stay aligned.
534 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
535
536 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
537 unsigned LogAlign = Log2_32(Align);
538 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000539 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000540 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000541 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000542 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000543
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000544 // Ensure that future entries with higher alignment get inserted before
545 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000546 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000547 if (InsPoint[a] == InsAt)
548 InsPoint[a] = CPEMI;
549
Evan Cheng8b7700f2007-02-09 20:54:44 +0000550 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000551 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000552 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000553 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
554 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000555 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000556 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000557}
558
Dale Johannesene18b13b2007-02-23 05:02:36 +0000559/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000560/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000561bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000562 // Get the next machine basic block in the function.
563 MachineFunction::iterator MBBI = MBB;
Jim Grosbach84511e12010-06-02 21:53:11 +0000564 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000565 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000566 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000567
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000568 MachineBasicBlock *NextBB = std::next(MBBI);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000569 if (std::find(MBB->succ_begin(), MBB->succ_end(), NextBB) == MBB->succ_end())
570 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000571
Tim Northoverab85dcc2014-11-13 17:58:51 +0000572 // Try to analyze the end of the block. A potential fallthrough may already
573 // have an unconditional branch for whatever reason.
574 MachineBasicBlock *TBB, *FBB;
575 SmallVector<MachineOperand, 4> Cond;
576 bool TooDifficult = TII->AnalyzeBranch(*MBB, TBB, FBB, Cond);
577 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000578}
579
Evan Cheng8b7700f2007-02-09 20:54:44 +0000580/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
581/// look up the corresponding CPEntry.
582ARMConstantIslands::CPEntry
583*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
584 const MachineInstr *CPEMI) {
585 std::vector<CPEntry> &CPEs = CPEntries[CPI];
586 // Number of entries per constpool index should be small, just do a
587 // linear search.
588 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
589 if (CPEs[i].CPEMI == CPEMI)
590 return &CPEs[i];
591 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000592 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000593}
594
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000595/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000596/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000597unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
Peter Collingbourne7e814d12015-05-21 23:20:55 +0000598 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000599
Peter Collingbourne7e814d12015-05-21 23:20:55 +0000600 unsigned CPI = CPEMI->getOperand(1).getIndex();
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000601 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
602 unsigned Align = MCP->getConstants()[CPI].getAlignment();
603 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
604 return Log2_32(Align);
605}
606
Jim Grosbach190e7b62012-03-23 23:07:03 +0000607/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000608/// information about the sizes of each block and the locations of all
609/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000610void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000611 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach5d577142009-11-12 17:25:07 +0000612 MBBI != E; ++MBBI) {
613 MachineBasicBlock &MBB = *MBBI;
614
Jim Grosbach5d577142009-11-12 17:25:07 +0000615 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach9785e592009-11-16 18:58:52 +0000616 I != E; ++I)
Evan Cheng7f8e5632011-12-07 07:15:52 +0000617 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach9785e592009-11-16 18:58:52 +0000618 T2JumpTables.push_back(I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000619 }
620}
621
Jim Grosbach190e7b62012-03-23 23:07:03 +0000622/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000623/// information about the sizes of each block, the location of all the water,
624/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000625void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000626initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000627 BBInfo.clear();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000628 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000629
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000630 // First thing, compute the size of all basic blocks, and see if the function
631 // has any inline assembly in it. If so, we have to be conservative about
632 // alignment assumptions, as we don't know for sure the size of any
633 // instructions in the inline assembly.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000634 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000635 computeBlockSize(I);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000636
637 // The known bits of the entry block offset are determined by the function
638 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000639 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000640
641 // Compute block offsets and known bits.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000642 adjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000643
Bill Wendling18581a42010-12-21 01:54:40 +0000644 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000645 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Cheng10043e22007-01-19 07:51:42 +0000646 MBBI != E; ++MBBI) {
647 MachineBasicBlock &MBB = *MBBI;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000648
Evan Cheng10043e22007-01-19 07:51:42 +0000649 // If this block doesn't fall through into the next MBB, then this is
650 // 'water' that a constant pool island could be placed.
651 if (!BBHasFallthrough(&MBB))
652 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000653
Evan Cheng10043e22007-01-19 07:51:42 +0000654 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
655 I != E; ++I) {
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000656 if (I->isDebugValue())
657 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000658
Matthias Braunfa3872e2015-05-18 20:27:55 +0000659 unsigned Opc = I->getOpcode();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000660 if (I->isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000661 bool isCond = false;
662 unsigned Bits = 0;
663 unsigned Scale = 1;
664 int UOpc = Opc;
665 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000666 default:
667 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000668 case ARM::t2BR_JT:
669 T2JumpTables.push_back(I);
670 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000671 case ARM::Bcc:
672 isCond = true;
673 UOpc = ARM::B;
674 // Fallthrough
675 case ARM::B:
676 Bits = 24;
677 Scale = 4;
678 break;
679 case ARM::tBcc:
680 isCond = true;
681 UOpc = ARM::tB;
682 Bits = 8;
683 Scale = 2;
684 break;
685 case ARM::tB:
686 Bits = 11;
687 Scale = 2;
688 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000689 case ARM::t2Bcc:
690 isCond = true;
691 UOpc = ARM::t2B;
692 Bits = 20;
693 Scale = 2;
694 break;
695 case ARM::t2B:
696 Bits = 24;
697 Scale = 2;
698 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000699 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000700
701 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000702 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengf9a4c692007-02-01 10:16:15 +0000703 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000704 }
705
Evan Cheng7fa69642007-01-30 01:18:38 +0000706 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
707 PushPopMIs.push_back(I);
708
Peter Collingbourne7e814d12015-05-21 23:20:55 +0000709 if (Opc == ARM::CONSTPOOL_ENTRY)
Evan Chengd2919a12009-07-23 18:27:47 +0000710 continue;
711
Evan Cheng10043e22007-01-19 07:51:42 +0000712 // Scan the instructions for constant pool operands.
713 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Peter Collingbourne7e814d12015-05-21 23:20:55 +0000714 if (I->getOperand(op).isCPI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000715 // We found one. The addressing mode tells us the max displacement
716 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000717
Evan Cheng10043e22007-01-19 07:51:42 +0000718 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000719 unsigned Bits = 0;
720 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000721 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000722 bool IsSoImm = false;
723
724 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000725 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000726 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000727
728 // Taking the address of a CP entry.
729 case ARM::LEApcrel:
730 // This takes a SoImm, which is 8 bit immediate rotated. We'll
731 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000732 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000733 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000734 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000735 Scale = 4;
736 NegOk = true;
737 IsSoImm = true;
738 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000739 case ARM::t2LEApcrel:
Evan Chengd2919a12009-07-23 18:27:47 +0000740 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000741 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000742 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000743 case ARM::tLEApcrel:
744 Bits = 8;
745 Scale = 4;
746 break;
747
David Majnemer452f1f92013-06-04 17:46:15 +0000748 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000749 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000750 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000751 case ARM::t2LDRpci:
Evan Chengfd522992007-02-01 20:44:52 +0000752 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000753 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000754 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000755
756 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000757 Bits = 8;
758 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000759 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000760
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000761 case ARM::VLDRD:
762 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000763 Bits = 8;
764 Scale = 4; // +-(offset_8*4)
765 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000766 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000767 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000768
Evan Cheng10043e22007-01-19 07:51:42 +0000769 // Remember that this is a user of a CP entry.
Chris Lattnera5bb3702007-12-30 23:10:15 +0000770 unsigned CPI = I->getOperand(op).getIndex();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000771 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000772 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd2919a12009-07-23 18:27:47 +0000773 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000774
775 // Increment corresponding CPEntry reference count.
776 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
777 assert(CPE && "Cannot find a corresponding CPEntry!");
778 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000779
Evan Cheng10043e22007-01-19 07:51:42 +0000780 // Instructions can only use one CP entry, don't bother scanning the
781 // rest of the operands.
782 break;
783 }
784 }
Evan Cheng10043e22007-01-19 07:51:42 +0000785 }
786}
787
Jim Grosbach190e7b62012-03-23 23:07:03 +0000788/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000789/// This function updates BBInfo directly.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000790void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000791 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
792 BBI.Size = 0;
793 BBI.Unalign = 0;
794 BBI.PostAlign = 0;
795
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000796 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
797 ++I) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000798 BBI.Size += TII->GetInstSizeInBytes(I);
799 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
800 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesen14e024d2011-12-08 01:22:39 +0000801 if (I->isInlineAsm())
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000802 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000803 // Also consider instructions that may be shrunk later.
804 else if (isThumb && mayOptimizeThumb2Instruction(I))
805 BBI.Unalign = 1;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000806 }
807
808 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000809 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000810 BBI.PostAlign = 2;
Chad Rosier73b02822012-07-06 23:13:38 +0000811 MBB->getParent()->ensureAlignment(2);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000812 }
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000813}
814
Jim Grosbach190e7b62012-03-23 23:07:03 +0000815/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000816/// from the start of the function. This offset changes as stuff is moved
817/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000818unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000819 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000820
Evan Cheng10043e22007-01-19 07:51:42 +0000821 // The offset is composed of two things: the sum of the sizes of all MBB's
822 // before this instruction's block, and the offset from the start of the block
823 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000824 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000825
826 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000827 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000828 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +0000829 Offset += TII->GetInstSizeInBytes(I);
Evan Cheng10043e22007-01-19 07:51:42 +0000830 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000831 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000832}
833
834/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
835/// ID.
836static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
837 const MachineBasicBlock *RHS) {
838 return LHS->getNumber() < RHS->getNumber();
839}
840
Jim Grosbach190e7b62012-03-23 23:07:03 +0000841/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000842/// machine function, it upsets all of the block numbers. Renumber the blocks
843/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000844void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000845 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000846 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000847
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000848 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000849 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000850 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000851
852 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000853 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000854 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000855 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
856 CompareMBBNumbers);
857 WaterList.insert(IP, NewBB);
858}
859
860
861/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000862/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000863/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000864MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000865 MachineBasicBlock *OrigBB = MI->getParent();
866
867 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000868 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000869 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Cheng10043e22007-01-19 07:51:42 +0000870 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000871 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000872
Evan Cheng10043e22007-01-19 07:51:42 +0000873 // Splice the instructions starting with MI over to NewBB.
874 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000875
Evan Cheng10043e22007-01-19 07:51:42 +0000876 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000877 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000878 // There doesn't seem to be meaningful DebugInfo available; this doesn't
879 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000880 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000881 if (!isThumb)
882 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
883 else
884 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
885 .addImm(ARMCC::AL).addReg(0);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000886 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000887
Evan Cheng10043e22007-01-19 07:51:42 +0000888 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000889 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000890
Evan Cheng10043e22007-01-19 07:51:42 +0000891 // OrigBB branches to NewBB.
892 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000893
Evan Cheng10043e22007-01-19 07:51:42 +0000894 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000895 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000896 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000897 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000898
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000899 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000900 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000901 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000902
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000903 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000904 // available water after it (but not if it's already there, which happens
905 // when splitting before a conditional branch that is followed by an
906 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000907 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +0000908 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
909 CompareMBBNumbers);
910 MachineBasicBlock* WaterBB = *IP;
911 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000912 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000913 else
914 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000915 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000916
Dale Johannesenc17dd572010-07-23 22:50:23 +0000917 // Figure out how large the OrigBB is. As the first half of the original
918 // block, it cannot contain a tablejump. The size includes
919 // the new jump we added. (It should be possible to do this without
920 // recounting everything, but it's very confusing, and this is rarely
921 // executed.)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000922 computeBlockSize(OrigBB);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000923
Dale Johannesenc17dd572010-07-23 22:50:23 +0000924 // Figure out how large the NewMBB is. As the second half of the original
925 // block, it may contain a tablejump.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000926 computeBlockSize(NewBB);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000927
Dale Johannesen01ee5752007-02-25 00:47:03 +0000928 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000929 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000930
931 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000932}
933
Jim Grosbach190e7b62012-03-23 23:07:03 +0000934/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000935/// displacement computation. Update U.KnownAlignment to match its current
936/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000937unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
938 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000939 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
940 unsigned KnownBits = BBI.internalKnownBits();
941
942 // The value read from PC is offset from the actual instruction address.
943 UserOffset += (isThumb ? 4 : 8);
944
945 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
946 // Make sure U.getMaxDisp() returns a constrained range.
947 U.KnownAlignment = (KnownBits >= 2);
948
949 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
950 // purposes of the displacement computation; compensate for that here.
951 // For unknown alignments, getMaxDisp() constrains the range instead.
952 if (isThumb && U.KnownAlignment)
953 UserOffset &= ~3u;
954
955 return UserOffset;
956}
957
Jim Grosbach190e7b62012-03-23 23:07:03 +0000958/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000959/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000960/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +0000961/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000962/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
963/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000964bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +0000965 unsigned TrialOffset, unsigned MaxDisp,
966 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +0000967 if (UserOffset <= TrialOffset) {
968 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +0000969 if (TrialOffset - UserOffset <= MaxDisp)
970 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000971 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000972 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +0000973 if (UserOffset - TrialOffset <= MaxDisp)
974 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000975 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000976 }
977 return false;
978}
979
Jim Grosbach190e7b62012-03-23 23:07:03 +0000980/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +0000981/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000982///
983/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000984bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000985 MachineBasicBlock* Water, CPUser &U,
986 unsigned &Growth) {
987 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
988 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
989 unsigned NextBlockOffset, NextBlockAlignment;
990 MachineFunction::const_iterator NextBlock = Water;
991 if (++NextBlock == MF->end()) {
992 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
993 NextBlockAlignment = 0;
994 } else {
995 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
996 NextBlockAlignment = NextBlock->getAlignment();
997 }
998 unsigned Size = U.CPEMI->getOperand(2).getImm();
999 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001000
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001001 // The CPE may be able to hide in the alignment padding before the next
1002 // block. It may also cause more padding to be required if it is more aligned
1003 // that the next block.
1004 if (CPEEnd > NextBlockOffset) {
1005 Growth = CPEEnd - NextBlockOffset;
1006 // Compute the padding that would go at the end of the CPE to align the next
1007 // block.
1008 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1009
1010 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001011 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001012 // in blocks between CPE and the user.
1013 if (CPEOffset < UserOffset)
1014 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1015 } else
1016 // CPE fits in existing padding.
1017 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001018
Jim Grosbach190e7b62012-03-23 23:07:03 +00001019 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001020}
1021
Jim Grosbach190e7b62012-03-23 23:07:03 +00001022/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001023/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001024bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001025 MachineInstr *CPEMI, unsigned MaxDisp,
1026 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001027 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001028
Dale Johannesene18b13b2007-02-23 05:02:36 +00001029 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001030 DEBUG({
1031 unsigned Block = MI->getParent()->getNumber();
1032 const BasicBlockInfo &BBI = BBInfo[Block];
1033 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1034 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001035 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001036 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001037 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1038 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1039 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001040 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001041 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001042
Jim Grosbach190e7b62012-03-23 23:07:03 +00001043 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001044}
1045
Evan Chenge4510972009-01-28 00:53:34 +00001046#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001047/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1048/// unconditionally branches to its only successor.
1049static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1050 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1051 return false;
1052
1053 MachineBasicBlock *Succ = *MBB->succ_begin();
1054 MachineBasicBlock *Pred = *MBB->pred_begin();
1055 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001056 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1057 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001058 return PredMI->getOperand(0).getMBB() == Succ;
1059 return false;
1060}
Evan Chenge4510972009-01-28 00:53:34 +00001061#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001062
Jim Grosbach190e7b62012-03-23 23:07:03 +00001063void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001064 unsigned BBNum = BB->getNumber();
1065 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001066 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001067 // Include the alignment of the current block.
1068 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1069 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1070 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001071
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001072 // This is where block i begins. Stop if the offset is already correct,
1073 // and we have updated 2 blocks. This is the maximum number of blocks
1074 // changed before calling this function.
1075 if (i > BBNum + 2 &&
1076 BBInfo[i].Offset == Offset &&
1077 BBInfo[i].KnownBits == KnownBits)
1078 break;
1079
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001080 BBInfo[i].Offset = Offset;
1081 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001082 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001083}
1084
Jim Grosbach190e7b62012-03-23 23:07:03 +00001085/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001086/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001087/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001088/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001089
Jim Grosbach190e7b62012-03-23 23:07:03 +00001090bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1091 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001092 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001093 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1094 assert(CPE && "Unexpected!");
1095 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001096 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001097 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001098 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001099 return true;
1100 }
1101 return false;
1102}
1103
Dale Johannesene18b13b2007-02-23 05:02:36 +00001104/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1105/// if not, see if an in-range clone of the CPE is in range, and if so,
1106/// change the data structures so the user references the clone. Returns:
1107/// 0 = no existing entry found
1108/// 1 = entry found, and there were no code insertions or deletions
1109/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001110int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001111{
1112 MachineInstr *UserMI = U.MI;
1113 MachineInstr *CPEMI = U.CPEMI;
1114
1115 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001116 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1117 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001118 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001119 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001120 }
1121
Dale Johannesene18b13b2007-02-23 05:02:36 +00001122 // No. Look for previously created clones of the CPE that are in range.
Peter Collingbourne7e814d12015-05-21 23:20:55 +00001123 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001124 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1125 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1126 // We already tried this one
1127 if (CPEs[i].CPEMI == CPEMI)
1128 continue;
1129 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001130 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001131 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001132 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001133 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001134 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001135 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001136 // Point the CPUser node to the replacement
1137 U.CPEMI = CPEs[i].CPEMI;
1138 // Change the CPI in the instruction operand to refer to the clone.
1139 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001140 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001141 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001142 break;
1143 }
1144 // Adjust the refcount of the clone...
1145 CPEs[i].RefCount++;
1146 // ...and the original. If we didn't remove the old entry, none of the
1147 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001148 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001149 }
1150 }
1151 return 0;
1152}
1153
Dale Johannesen440995b2007-02-28 18:41:23 +00001154/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1155/// the specific unconditional branch instruction.
1156static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001157 switch (Opc) {
1158 case ARM::tB:
1159 return ((1<<10)-1)*2;
1160 case ARM::t2B:
1161 return ((1<<23)-1)*2;
1162 default:
1163 break;
1164 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001165
David Goodwin27303cd2009-06-30 18:04:13 +00001166 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001167}
1168
Jim Grosbach190e7b62012-03-23 23:07:03 +00001169/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001170/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001171/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001172/// is set to the WaterList entry. For Thumb, prefer water that will not
1173/// introduce padding to water that will. To ensure that this pass
1174/// terminates, the CPE location for a particular CPUser is only allowed to
1175/// move to a lower address, so search backward from the end of the list and
1176/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001177bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Bob Wilson2f9be502009-10-15 20:49:47 +00001178 water_iterator &WaterIter) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001179 if (WaterList.empty())
1180 return false;
1181
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001182 unsigned BestGrowth = ~0u;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001183 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001184 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001185 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001186 // Check if water is in range and is either at a lower address than the
1187 // current "high water mark" or a new water block that was created since
1188 // the previous iteration by inserting an unconditional branch. In the
1189 // latter case, we want to allow resetting the high water mark back to
1190 // this new water since we haven't seen it before. Inserting branches
1191 // should be relatively uncommon and when it does happen, we want to be
1192 // sure to take advantage of it for all the CPEs near that block, so that
1193 // we don't insert more branches than necessary.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001194 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001195 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001196 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001197 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1198 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001199 // This is the least amount of required padding seen so far.
1200 BestGrowth = Growth;
1201 WaterIter = IP;
1202 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1203 << " Growth=" << Growth << '\n');
1204
1205 // Keep looking unless it is perfect.
1206 if (BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001207 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001208 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001209 if (IP == B)
1210 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001211 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001212 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001213}
1214
Jim Grosbach190e7b62012-03-23 23:07:03 +00001215/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001216/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1217/// block is used if in range, and the conditional branch munged so control
1218/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001219/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001220/// block following which the new island can be inserted (the WaterList
1221/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001222void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001223 unsigned UserOffset,
1224 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001225 CPUser &U = CPUsers[CPUserIndex];
1226 MachineInstr *UserMI = U.MI;
1227 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001228 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001229 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001230 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001231
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001232 // If the block does not end in an unconditional branch already, and if the
1233 // end of the block is within range, make new water there. (The addition
1234 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001235 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001236 if (BBHasFallthrough(UserMBB)) {
1237 // Size of branch to insert.
1238 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001239 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001240 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001241
Jim Grosbach190e7b62012-03-23 23:07:03 +00001242 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001243 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1244 << format(", expected CPE offset %#x\n", CPEOffset));
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001245 NewMBB = std::next(MachineFunction::iterator(UserMBB));
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001246 // Add an unconditional branch from UserMBB to fallthrough block. Record
1247 // it for branch lengthening; this new branch will not get out of range,
1248 // but if the preceding conditional branch is out of range, the targets
1249 // will be exchanged, and the altered branch may be out of range, so the
1250 // machinery has to know about it.
1251 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1252 if (!isThumb)
1253 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1254 else
1255 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1256 .addImm(ARMCC::AL).addReg(0);
1257 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1258 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1259 MaxDisp, false, UncondBr));
Akira Hatanaka442b40c2015-01-08 20:44:50 +00001260 computeBlockSize(UserMBB);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001261 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001262 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001263 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001264 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001265
1266 // What a big block. Find a place within the block to split it. This is a
1267 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1268 // entries are 4 bytes: if instruction I references island CPE, and
1269 // instruction I+1 references CPE', it will not work well to put CPE as far
1270 // forward as possible, since then CPE' cannot immediately follow it (that
1271 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1272 // need to create a new island. So, we make a first guess, then walk through
1273 // the instructions between the one currently being looked at and the
1274 // possible insertion point, and make sure any other instructions that
1275 // reference CPEs will be able to use the same island area; if not, we back
1276 // up the insertion point.
1277
1278 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001279 // point where we can add a 4-byte branch instruction, and then align to
1280 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001281 unsigned LogAlign = MF->getAlignment();
1282 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1283 unsigned KnownBits = UserBBI.internalKnownBits();
1284 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001285 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001286 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1287 BaseInsertOffset));
1288
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001289 // The 4 in the following is for the unconditional branch we'll be inserting
1290 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001291 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001292 BaseInsertOffset -= 4;
1293
1294 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1295 << " la=" << LogAlign
1296 << " kb=" << KnownBits
1297 << " up=" << UPad << '\n');
1298
1299 // This could point off the end of the block if we've already got constant
1300 // pool entries following this block; only the last one is in the water list.
1301 // Back past any possible branches (allow for a conditional and a maximally
1302 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001303 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001304 // Ensure BaseInsertOffset is larger than the offset of the instruction
1305 // following UserMI so that the loop which searches for the split point
1306 // iterates at least once.
1307 BaseInsertOffset =
1308 std::max(UserBBI.postOffset() - UPad - 8,
1309 UserOffset + TII->GetInstSizeInBytes(UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001310 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1311 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001312 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001313 CPEMI->getOperand(2).getImm();
1314 MachineBasicBlock::iterator MI = UserMI;
1315 ++MI;
1316 unsigned CPUIndex = CPUserIndex+1;
1317 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001318 MachineInstr *LastIT = nullptr;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001319 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1320 Offset < BaseInsertOffset;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001321 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001322 assert(MI != UserMBB->end() && "Fell off end of block");
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001323 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1324 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001325 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001326 // Shift intertion point by one unit of alignment so it is within reach.
1327 BaseInsertOffset -= 1u << LogAlign;
1328 EndInsertOffset -= 1u << LogAlign;
1329 }
1330 // This is overly conservative, as we don't account for CPEMIs being
1331 // reused within the block, but it doesn't matter much. Also assume CPEs
1332 // are added in order with alignment padding. We may eventually be able
1333 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001334 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001335 CPUIndex++;
1336 }
1337
1338 // Remember the last IT instruction.
1339 if (MI->getOpcode() == ARM::t2IT)
1340 LastIT = MI;
1341 }
1342
1343 --MI;
1344
1345 // Avoid splitting an IT block.
1346 if (LastIT) {
1347 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001348 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001349 if (CC != ARMCC::AL)
1350 MI = LastIT;
1351 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001352
1353 // We really must not split an IT block.
1354 DEBUG(unsigned PredReg;
1355 assert(!isThumb || getITInstrPredicate(MI, PredReg) == ARMCC::AL));
1356
Jim Grosbach190e7b62012-03-23 23:07:03 +00001357 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001358}
1359
Jim Grosbach190e7b62012-03-23 23:07:03 +00001360/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001361/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001362/// place in-range. Return true if we changed any addresses (thus must run
1363/// another pass of branch lengthening), false otherwise.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001364bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001365 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001366 MachineInstr *UserMI = U.MI;
1367 MachineInstr *CPEMI = U.CPEMI;
Peter Collingbourne7e814d12015-05-21 23:20:55 +00001368 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001369 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001370 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001371 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001372
Dale Johannesene18b13b2007-02-23 05:02:36 +00001373 // See if the current entry is within range, or there is a clone of it
1374 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001375 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001376 if (result==1) return false;
1377 else if (result==2) return true;
1378
1379 // No existing clone of this CPE is within range.
1380 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001381 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001382
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001383 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001384 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001385 MachineBasicBlock *NewMBB;
1386 water_iterator IP;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001387 if (findAvailableWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001388 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001389 MachineBasicBlock *WaterBB = *IP;
1390
1391 // If the original WaterList entry was "new water" on this iteration,
1392 // propagate that to the new island. This is just keeping NewWaterList
1393 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001394 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001395 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001396
Bob Wilson2f9be502009-10-15 20:49:47 +00001397 // The new CPE goes before the following block (NewMBB).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001398 NewMBB = std::next(MachineFunction::iterator(WaterBB));
Bob Wilson2f9be502009-10-15 20:49:47 +00001399
1400 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001401 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001402 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001403 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001404
Jim Grosbach190e7b62012-03-23 23:07:03 +00001405 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001406 // called while handling branches so that the water will be seen on the
1407 // next iteration for constant pools, but in this context, we don't want
1408 // it. Check for this so it will be removed from the WaterList.
1409 // Also remove any entry from NewWaterList.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001410 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
Bob Wilson2f9be502009-10-15 20:49:47 +00001411 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1412 if (IP != WaterList.end())
1413 NewWaterList.erase(WaterBB);
1414
1415 // We are adding new water. Update NewWaterList.
1416 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001417 }
1418
Bob Wilson2f9be502009-10-15 20:49:47 +00001419 // Remove the original WaterList entry; we want subsequent insertions in
1420 // this vicinity to go after the one we're about to insert. This
1421 // considerably reduces the number of times we have to move the same CPE
1422 // more than once and is also important to ensure the algorithm terminates.
1423 if (IP != WaterList.end())
1424 WaterList.erase(IP);
1425
Dale Johannesene18b13b2007-02-23 05:02:36 +00001426 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001427 MF->insert(NewMBB, NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001428
1429 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001430 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001431
Peter Collingbourne7e814d12015-05-21 23:20:55 +00001432 // Decrement the old entry, and remove it if refcount becomes 0.
1433 decrementCPEReferenceCount(CPI, CPEMI);
1434
Dale Johannesene18b13b2007-02-23 05:02:36 +00001435 // Now that we have an island to add the CPE to, clone the original CPE and
1436 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001437 U.HighWaterMark = NewIsland;
Peter Collingbourne7e814d12015-05-21 23:20:55 +00001438 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1439 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001440 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001441 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001442
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001443 // Mark the basic block as aligned as required by the const-pool entry.
1444 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001445
Evan Cheng10043e22007-01-19 07:51:42 +00001446 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001447 BBInfo[NewIsland->getNumber()].Size += Size;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001448 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001449
Evan Cheng10043e22007-01-19 07:51:42 +00001450 // Finally, change the CPI in the instruction operand to be ID.
1451 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001452 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001453 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001454 break;
1455 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001456
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001457 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001458 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001459
Evan Cheng10043e22007-01-19 07:51:42 +00001460 return true;
1461}
1462
Jim Grosbach190e7b62012-03-23 23:07:03 +00001463/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001464/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001465void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001466 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001467 unsigned Size = CPEMI->getOperand(2).getImm();
1468 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001469 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001470 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001471 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001472 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001473
Evan Chengab28b9a2013-02-21 18:37:54 +00001474 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001475 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001476 } else
1477 // Entries are sorted by descending alignment, so realign from the front.
1478 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1479
Jim Grosbach190e7b62012-03-23 23:07:03 +00001480 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001481 // An island has only one predecessor BB and one successor BB. Check if
1482 // this BB's predecessor jumps directly to this BB's successor. This
1483 // shouldn't happen currently.
1484 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1485 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001486}
1487
Jim Grosbach190e7b62012-03-23 23:07:03 +00001488/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001489/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001490bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001491 unsigned MadeChange = false;
1492 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1493 std::vector<CPEntry> &CPEs = CPEntries[i];
1494 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1495 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001496 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001497 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001498 MadeChange = true;
1499 }
1500 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001501 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001502 return MadeChange;
1503}
1504
Jim Grosbach190e7b62012-03-23 23:07:03 +00001505/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001506/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001507bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001508 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001509 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001510 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001511 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001512
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001513 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001514 << " from BB#" << MI->getParent()->getNumber()
1515 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001516 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001517 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001518
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001519 if (BrOffset <= DestOffset) {
1520 // Branch before the Dest.
1521 if (DestOffset-BrOffset <= MaxDisp)
1522 return true;
1523 } else {
1524 if (BrOffset-DestOffset <= MaxDisp)
1525 return true;
1526 }
1527 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001528}
1529
Jim Grosbach190e7b62012-03-23 23:07:03 +00001530/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001531/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001532bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001533 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001534 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001535
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001536 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001537 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001538 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001539
Evan Cheng7fa69642007-01-30 01:18:38 +00001540 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001541 return fixupUnconditionalBr(Br);
1542 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001543}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001544
Jim Grosbach190e7b62012-03-23 23:07:03 +00001545/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001546/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001547/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001548/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001549bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001550ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001551 MachineInstr *MI = Br.MI;
1552 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001553 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001554 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001555
1556 // Use BL to implement far jump.
1557 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001558 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001559 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001560 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001561 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001562 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001563
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001564 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001565
Evan Cheng7fa69642007-01-30 01:18:38 +00001566 return true;
1567}
1568
Jim Grosbach190e7b62012-03-23 23:07:03 +00001569/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001570/// far away to fit in its displacement field. It is converted to an inverse
1571/// conditional branch + an unconditional branch to the destination.
1572bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001573ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001574 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001575 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001576
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001577 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001578 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001579 // blt L1
1580 // =>
1581 // bge L2
1582 // b L1
1583 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001584 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001585 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001586 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001587
1588 // If the branch is at the end of its MBB and that has a fall-through block,
1589 // direct the updated conditional branch to the fall-through block. Otherwise,
1590 // split the MBB before the next instruction.
1591 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001592 MachineInstr *BMI = &MBB->back();
1593 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001594
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001595 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001596 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001597 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001598 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001599 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001600 // condition and swap destinations:
1601 // beq L1
1602 // b L2
1603 // =>
1604 // bne L2
1605 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001606 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001607 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001608 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001609 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001610 BMI->getOperand(0).setMBB(DestBB);
1611 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001612 MI->getOperand(1).setImm(CC);
1613 return true;
1614 }
1615 }
1616 }
1617
1618 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001619 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001620 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001621 // branch to the destination.
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +00001622 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001623 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001624 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001625 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001626 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001627 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001628
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001629 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001630 << " also invert condition and change dest. to BB#"
1631 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001632
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001633 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001634 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001635 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001636 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001637 Br.MI = &MBB->back();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001638 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001639 if (isThumb)
1640 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1641 .addImm(ARMCC::AL).addReg(0);
1642 else
1643 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001644 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001645 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001646 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001647
1648 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001649 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001650 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001651 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001652 return true;
1653}
Evan Cheng7fa69642007-01-30 01:18:38 +00001654
Jim Grosbach190e7b62012-03-23 23:07:03 +00001655/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001656/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1657/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001658bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001659 bool MadeChange = false;
1660 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1661 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001662 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001663 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001664 MI->getOperand(2).getReg() == ARM::PC &&
1665 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001666 // Create the new insn and copy the predicate from the old.
1667 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1668 .addOperand(MI->getOperand(0))
1669 .addOperand(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001670 MI->eraseFromParent();
1671 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001672 }
1673 }
1674 return MadeChange;
1675}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001676
Jim Grosbach190e7b62012-03-23 23:07:03 +00001677// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001678// below may shrink MI.
1679bool
1680ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1681 switch(MI->getOpcode()) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001682 // optimizeThumb2Instructions.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001683 case ARM::t2LEApcrel:
1684 case ARM::t2LDRpci:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001685 // optimizeThumb2Branches.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001686 case ARM::t2B:
1687 case ARM::t2Bcc:
1688 case ARM::tBcc:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001689 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001690 case ARM::t2BR_JT:
1691 return true;
1692 }
1693 return false;
1694}
1695
Jim Grosbach190e7b62012-03-23 23:07:03 +00001696bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001697 bool MadeChange = false;
1698
1699 // Shrink ADR and LDR from constantpool.
1700 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1701 CPUser &U = CPUsers[i];
1702 unsigned Opcode = U.MI->getOpcode();
1703 unsigned NewOpc = 0;
1704 unsigned Scale = 1;
1705 unsigned Bits = 0;
1706 switch (Opcode) {
1707 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001708 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001709 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1710 NewOpc = ARM::tLEApcrel;
1711 Bits = 8;
1712 Scale = 4;
1713 }
1714 break;
1715 case ARM::t2LDRpci:
1716 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1717 NewOpc = ARM::tLDRpci;
1718 Bits = 8;
1719 Scale = 4;
1720 }
1721 break;
1722 }
1723
1724 if (!NewOpc)
1725 continue;
1726
Jim Grosbach190e7b62012-03-23 23:07:03 +00001727 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001728 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001729
1730 // Be conservative with inline asm.
1731 if (!U.KnownAlignment)
1732 MaxOffs -= 2;
1733
Evan Chengdb73d682009-08-14 00:32:16 +00001734 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001735 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001736 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001737 U.MI->setDesc(TII->get(NewOpc));
1738 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001739 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001740 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001741 ++NumT2CPShrunk;
1742 MadeChange = true;
1743 }
1744 }
1745
Jim Grosbach190e7b62012-03-23 23:07:03 +00001746 MadeChange |= optimizeThumb2Branches();
1747 MadeChange |= optimizeThumb2JumpTables();
Evan Chengdb73d682009-08-14 00:32:16 +00001748 return MadeChange;
1749}
1750
Jim Grosbach190e7b62012-03-23 23:07:03 +00001751bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001752 bool MadeChange = false;
1753
Peter Collingbourne167668f2015-04-23 20:31:35 +00001754 // The order in which branches appear in ImmBranches is approximately their
1755 // order within the function body. By visiting later branches first, we reduce
1756 // the distance between earlier forward branches and their targets, making it
1757 // more likely that the cbn?z optimization, which can only apply to forward
1758 // branches, will succeed.
1759 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1760 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001761 unsigned Opcode = Br.MI->getOpcode();
1762 unsigned NewOpc = 0;
1763 unsigned Scale = 1;
1764 unsigned Bits = 0;
1765 switch (Opcode) {
1766 default: break;
1767 case ARM::t2B:
1768 NewOpc = ARM::tB;
1769 Bits = 11;
1770 Scale = 2;
1771 break;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001772 case ARM::t2Bcc: {
Evan Chenge41903b2009-08-14 18:31:44 +00001773 NewOpc = ARM::tBcc;
1774 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001775 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001776 break;
1777 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001778 }
1779 if (NewOpc) {
1780 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1781 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001782 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001783 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001784 Br.MI->setDesc(TII->get(NewOpc));
1785 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001786 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001787 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001788 ++NumT2BrShrunk;
1789 MadeChange = true;
1790 }
1791 }
1792
1793 Opcode = Br.MI->getOpcode();
1794 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001795 continue;
1796
Evan Cheng6bb95252012-01-14 01:53:46 +00001797 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1798 // so this transformation is not safe.
1799 if (!Br.MI->killsRegister(ARM::CPSR))
1800 continue;
1801
Evan Cheng6f29ad92009-10-31 23:46:45 +00001802 NewOpc = 0;
1803 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001804 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001805 if (Pred == ARMCC::EQ)
1806 NewOpc = ARM::tCBZ;
1807 else if (Pred == ARMCC::NE)
1808 NewOpc = ARM::tCBNZ;
1809 if (!NewOpc)
1810 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001811 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001812 // Check if the distance is within 126. Subtract starting offset by 2
1813 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001814 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001815 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001816 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001817 MachineBasicBlock::iterator CmpMI = Br.MI;
1818 if (CmpMI != Br.MI->getParent()->begin()) {
1819 --CmpMI;
1820 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1821 unsigned Reg = CmpMI->getOperand(0).getReg();
Craig Topperf6e7e122012-03-27 07:21:54 +00001822 Pred = getInstrPredicate(CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001823 if (Pred == ARMCC::AL &&
1824 CmpMI->getOperand(1).getImm() == 0 &&
1825 isARMLowRegister(Reg)) {
1826 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001827 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001828 MachineInstr *NewBR =
1829 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1830 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1831 CmpMI->eraseFromParent();
1832 Br.MI->eraseFromParent();
1833 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001834 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001835 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001836 ++NumCBZ;
1837 MadeChange = true;
1838 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001839 }
1840 }
Evan Chenge41903b2009-08-14 18:31:44 +00001841 }
1842 }
1843
1844 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001845}
1846
Tim Northover688f7bb2015-05-13 20:28:32 +00001847/// If we've formed a TBB or TBH instruction, the base register is now
1848/// redundant. In most cases, the instructions defining it will now be dead and
1849/// can be tidied up. This function removes them if so, and returns the number
1850/// of bytes saved.
1851unsigned ARMConstantIslands::removeDeadDefinitions(MachineInstr *MI,
1852 unsigned BaseReg,
1853 unsigned IdxReg) {
1854 unsigned BytesRemoved = 0;
1855 MachineBasicBlock *MBB = MI->getParent();
1856
1857 // Scan backwards to find the instruction that defines the base
1858 // register. Due to post-RA scheduling, we can't count on it
1859 // immediately preceding the branch instruction.
1860 MachineBasicBlock::iterator PrevI = MI;
1861 MachineBasicBlock::iterator B = MBB->begin();
1862 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1863 --PrevI;
1864
1865 // If for some reason we didn't find it, we can't do anything, so
1866 // just skip this one.
1867 if (!PrevI->definesRegister(BaseReg) || PrevI->hasUnmodeledSideEffects() ||
1868 PrevI->mayStore())
1869 return BytesRemoved;
1870
1871 MachineInstr *AddrMI = PrevI;
1872 unsigned NewBaseReg = BytesRemoved;
1873
1874 // Examine the instruction that calculates the jumptable entry address. Make
1875 // sure it only defines the base register and kills any uses other than the
1876 // index register. We also need precisely one use to trace backwards to
1877 // (hopefully) the LEA.
1878 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1879 const MachineOperand &MO = AddrMI->getOperand(k);
1880 if (!MO.isReg() || !MO.getReg())
1881 continue;
1882 if (MO.isDef() && MO.getReg() != BaseReg)
1883 return BytesRemoved;
1884
1885 if (MO.isUse() && MO.getReg() != IdxReg) {
1886 if (!MO.isKill() || (NewBaseReg != 0 && NewBaseReg != MO.getReg()))
1887 return BytesRemoved;
1888 NewBaseReg = MO.getReg();
1889 }
1890 }
1891
1892 // Want to continue searching for AddrMI, but there are 2 problems: AddrMI is
1893 // going away soon, and even decrementing once may be invalid.
1894 if (PrevI != B)
1895 PrevI = std::prev(PrevI);
1896
1897 DEBUG(dbgs() << "remove addr: " << *AddrMI);
1898 BytesRemoved += TII->GetInstSizeInBytes(AddrMI);
1899 AddrMI->eraseFromParent();
1900
1901 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1902 // that gave us the initial base register definition.
1903 for (; PrevI != B && !PrevI->definesRegister(NewBaseReg); --PrevI)
1904 ;
1905
1906 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1907 // to delete it as well.
1908 MachineInstr *LeaMI = PrevI;
1909 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1910 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1911 LeaMI->getOperand(0).getReg() != NewBaseReg)
1912 return BytesRemoved;
1913
1914 DEBUG(dbgs() << "remove lea: " << *LeaMI);
1915 BytesRemoved += TII->GetInstSizeInBytes(LeaMI);
1916 LeaMI->eraseFromParent();
1917 return BytesRemoved;
1918}
1919
Jim Grosbach190e7b62012-03-23 23:07:03 +00001920/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00001921/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001922bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00001923 bool MadeChange = false;
1924
1925 // FIXME: After the tables are shrunk, can we get rid some of the
1926 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001927 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00001928 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00001929
Evan Chengc6d70ae2009-07-29 02:18:14 +00001930 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1931 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1932 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00001933 const MCInstrDesc &MCID = MI->getDesc();
1934 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00001935 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Evan Chengc6d70ae2009-07-29 02:18:14 +00001936 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1937 unsigned JTI = JTOP.getIndex();
1938 assert(JTI < JT.size());
1939
Jim Grosbach8d92ec42009-11-11 02:47:19 +00001940 bool ByteOk = true;
1941 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001942 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00001943 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001944 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1945 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001946 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00001947 // Negative offset is not ok. FIXME: We should change BB layout to make
1948 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00001949 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00001950 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00001951 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00001952 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00001953 HalfWordOk = false;
1954 if (!ByteOk && !HalfWordOk)
1955 break;
1956 }
1957
Peter Collingbourne7e814d12015-05-21 23:20:55 +00001958 if (ByteOk || HalfWordOk) {
1959 MachineBasicBlock *MBB = MI->getParent();
1960 unsigned BaseReg = MI->getOperand(0).getReg();
1961 bool BaseRegKill = MI->getOperand(0).isKill();
1962 if (!BaseRegKill)
1963 continue;
1964 unsigned IdxReg = MI->getOperand(1).getReg();
1965 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbach40eda102010-07-07 22:51:22 +00001966
Peter Collingbourne7e814d12015-05-21 23:20:55 +00001967 DEBUG(dbgs() << "Shrink JT: " << *MI);
1968 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1969 MachineBasicBlock::iterator MI_JT = MI;
1970 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00001971 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Peter Collingbourne7e814d12015-05-21 23:20:55 +00001972 .addReg(IdxReg, getKillRegState(IdxRegKill))
1973 .addJumpTableIndex(JTI, JTOP.getTargetFlags());
1974 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
1975 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1976 // is 2-byte aligned. For now, asm printer will fix it up.
1977 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1978 unsigned OrigSize = TII->GetInstSizeInBytes(MI);
1979 unsigned DeadSize = removeDeadDefinitions(MI, BaseReg, IdxReg);
1980 MI->eraseFromParent();
Evan Chenge64f48b2009-08-01 06:13:52 +00001981
Peter Collingbourne7e814d12015-05-21 23:20:55 +00001982 int delta = OrigSize - NewSize + DeadSize;
1983 BBInfo[MBB->getNumber()].Size -= delta;
1984 adjustBBOffsetsAfter(MBB);
Evan Chenge64f48b2009-08-01 06:13:52 +00001985
Peter Collingbourne7e814d12015-05-21 23:20:55 +00001986 ++NumTBs;
1987 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00001988 }
1989 }
1990
1991 return MadeChange;
1992}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00001993
Jim Grosbach190e7b62012-03-23 23:07:03 +00001994/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00001995/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001996bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00001997 bool MadeChange = false;
1998
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001999 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002000 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002001
Jim Grosbach5d577142009-11-12 17:25:07 +00002002 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2003 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2004 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002005 const MCInstrDesc &MCID = MI->getDesc();
2006 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002007 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002008 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2009 unsigned JTI = JTOP.getIndex();
2010 assert(JTI < JT.size());
2011
2012 // We prefer if target blocks for the jump table come after the jump
2013 // instruction so we can use TB[BH]. Loop through the target blocks
2014 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002015 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002016 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2017 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2018 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002019 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002020
Jim Grosbach9785e592009-11-16 18:58:52 +00002021 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002022 // The destination precedes the switch. Try to move the block forward
2023 // so we have a positive offset.
2024 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002025 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002026 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002027 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002028 MadeChange = true;
2029 }
2030 }
2031 }
2032
2033 return MadeChange;
2034}
2035
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002036MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002037adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002038 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002039 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002040 // table that branches back to the actual target. This is a very simple
2041 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002042 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002043 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002044 SmallVector<MachineOperand, 4> CondPrior;
2045 MachineFunction::iterator BBi = BB;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002046 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002047
Jim Grosbach47d5e332009-11-16 17:10:56 +00002048 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002049 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002050
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002051 // If the block ends in an unconditional branch, move it. The prior block
2052 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002053 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002054 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002055 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002056 BB->moveAfter(JTBB);
2057 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002058 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002059 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002060 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002061 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002062 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002063 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002064
2065 // Create a new MBB for the code after the jump BB.
2066 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002067 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002068 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002069 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002070
2071 // Add an unconditional branch from NewBB to BB.
2072 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2073 // correspond directly to anything in the source.
2074 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson29cfe6c2011-09-09 21:48:23 +00002075 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2076 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002077
Jim Grosbach43d21082009-11-14 20:10:18 +00002078 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002079 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002080
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002081 // Update the CFG.
2082 NewBB->addSuccessor(BB);
2083 JTBB->removeSuccessor(BB);
2084 JTBB->addSuccessor(NewBB);
2085
Jim Grosbach5d577142009-11-12 17:25:07 +00002086 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002087 return NewBB;
2088}