blob: a9539850247f90c49ef94453335b9f4ee6579a68 [file] [log] [blame]
Bill Wendling9a4d2e42010-12-21 01:54:40 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
Evan Chenga8e29892007-01-19 07:51:42 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Chenga8e29892007-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
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000018#include "ARMMachineFunctionInfo.h"
Evan Cheng719510a2010-08-12 20:30:05 +000019#include "Thumb2InstrInfo.h"
Evan Chengee04a6d2011-07-20 23:34:39 +000020#include "MCTargetDesc/ARMAddressingModes.h"
Evan Chenga8e29892007-01-19 07:51:42 +000021#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Cheng5657c012009-07-29 02:18:14 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
Jakob Stoklund Olesen7a4c0712012-03-29 23:14:26 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +000029#include "llvm/Support/Format.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000030#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000031#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000032#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000033#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000035#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000036#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000037using namespace llvm;
38
Evan Chenga1efbbd2009-08-14 00:32:16 +000039STATISTIC(NumCPEs, "Number of constpool entries");
40STATISTIC(NumSplit, "Number of uncond branches inserted");
41STATISTIC(NumCBrFixed, "Number of cond branches fixed");
42STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
43STATISTIC(NumTBs, "Number of table branches generated");
44STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000045STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000046STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000047STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000048STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000049
50
51static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000052AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000053 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000054
Jakob Stoklund Olesenf5bb45f2011-12-16 16:07:41 +000055// FIXME: This option should be removed once it has received sufficient testing.
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +000056static cl::opt<bool>
Jakob Stoklund Olesenb6ff6ec2011-12-15 22:14:45 +000057AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(true),
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +000058 cl::desc("Align constant islands in code"));
59
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000060/// UnknownPadding - Return the worst case padding that could result from
61/// unknown offset bits. This does not include alignment padding caused by
62/// known offset bits.
63///
64/// @param LogAlign log2(alignment)
65/// @param KnownBits Number of known low offset bits.
66static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
67 if (KnownBits < LogAlign)
68 return (1u << LogAlign) - (1u << KnownBits);
69 return 0;
70}
71
Evan Chenga8e29892007-01-19 07:51:42 +000072namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000073 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000074 /// requires constant pool entries to be scattered among the instructions
75 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000076 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000077 /// special instructions.
78 ///
79 /// The terminology used in this pass includes:
80 /// Islands - Clumps of constants placed in the function.
81 /// Water - Potential places where an island could be formed.
82 /// CPE - A constant pool entry that has been placed somewhere, which
83 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000084 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000085 /// BasicBlockInfo - Information about the offset and size of a single
86 /// basic block.
87 struct BasicBlockInfo {
88 /// Offset - Distance from the beginning of the function to the beginning
89 /// of this basic block.
90 ///
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +000091 /// Offsets are computed assuming worst case padding before an aligned
92 /// block. This means that subtracting basic block offsets always gives a
93 /// conservative estimate of the real distance which may be smaller.
94 ///
95 /// Because worst case padding is used, the computed offset of an aligned
96 /// block may not actually be aligned.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000097 unsigned Offset;
Bob Wilson84945262009-05-12 17:09:30 +000098
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000099 /// Size - Size of the basic block in bytes. If the block contains
100 /// inline assembly, this is a worst case estimate.
101 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000102 /// The size does not include any alignment padding whether from the
103 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000104 unsigned Size;
105
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000106 /// KnownBits - The number of low bits in Offset that are known to be
107 /// exact. The remaining bits of Offset are an upper bound.
108 uint8_t KnownBits;
109
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000110 /// Unalign - When non-zero, the block contains instructions (inline asm)
111 /// of unknown size. The real size may be smaller than Size bytes by a
112 /// multiple of 1 << Unalign.
113 uint8_t Unalign;
114
115 /// PostAlign - When non-zero, the block terminator contains a .align
116 /// directive, so the end of the block is aligned to 1 << PostAlign
117 /// bytes.
118 uint8_t PostAlign;
119
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000120 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
121 PostAlign(0) {}
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000122
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000123 /// Compute the number of known offset bits internally to this block.
124 /// This number should be used to predict worst case padding when
125 /// splitting the block.
126 unsigned internalKnownBits() const {
Jakob Stoklund Olesen887d0952012-04-30 20:19:00 +0000127 unsigned Bits = Unalign ? Unalign : KnownBits;
128 // If the block size isn't a multiple of the known bits, assume the
129 // worst case padding.
130 if (Size & ((1u << Bits) - 1))
131 Bits = CountTrailingZeros_32(Size);
132 return Bits;
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000133 }
134
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000135 /// Compute the offset immediately following this block. If LogAlign is
136 /// specified, return the offset the successor block will get if it has
137 /// this alignment.
138 unsigned postOffset(unsigned LogAlign = 0) const {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000139 unsigned PO = Offset + Size;
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000140 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
141 if (!LA)
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000142 return PO;
143 // Add alignment padding from the terminator.
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +0000144 return PO + UnknownPadding(LA, internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000145 }
146
147 /// Compute the number of known low bits of postOffset. If this block
148 /// contains inline asm, the number of known bits drops to the
149 /// instruction alignment. An aligned terminator may increase the number
150 /// of know bits.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000151 /// If LogAlign is given, also consider the alignment of the next block.
152 unsigned postKnownBits(unsigned LogAlign = 0) const {
153 return std::max(std::max(unsigned(PostAlign), LogAlign),
154 internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000155 }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000156 };
157
158 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000159
Evan Chenga8e29892007-01-19 07:51:42 +0000160 /// WaterList - A sorted list of basic blocks where islands could be placed
161 /// (i.e. blocks that don't fall through to the following block, due
162 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +0000163 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +0000164
Bob Wilsonb9239532009-10-15 20:49:47 +0000165 /// NewWaterList - The subset of WaterList that was created since the
166 /// previous iteration by inserting unconditional branches.
167 SmallSet<MachineBasicBlock*, 4> NewWaterList;
168
Bob Wilson034de5f2009-10-12 18:52:13 +0000169 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
170
Evan Chenga8e29892007-01-19 07:51:42 +0000171 /// CPUser - One user of a constant pool, keeping the machine instruction
172 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000173 /// allowed from the instruction to the CP. The HighWaterMark records the
174 /// highest basic block where a new CPEntry can be placed. To ensure this
175 /// pass terminates, the CP entries are initially placed at the end of the
176 /// function and then move monotonically to lower addresses. The
177 /// exception to this rule is when the current CP entry for a particular
178 /// CPUser is out of range, but there is another CP entry for the same
179 /// constant value in range. We want to use the existing in-range CP
180 /// entry, but if it later moves out of range, the search for new water
181 /// should resume where it left off. The HighWaterMark is used to record
182 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000183 struct CPUser {
184 MachineInstr *MI;
185 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000186 MachineBasicBlock *HighWaterMark;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000187 private:
Evan Chenga8e29892007-01-19 07:51:42 +0000188 unsigned MaxDisp;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000189 public:
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000190 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000191 bool IsSoImm;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000192 bool KnownAlignment;
Evan Chengd3d9d662009-07-23 18:27:47 +0000193 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
194 bool neg, bool soimm)
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000195 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
196 KnownAlignment(false) {
Bob Wilson549dda92009-10-15 05:52:29 +0000197 HighWaterMark = CPEMI->getParent();
198 }
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000199 /// getMaxDisp - Returns the maximum displacement supported by MI.
200 /// Correct for unknown alignment.
Jakob Stoklund Olesen3ee36612012-03-31 00:06:44 +0000201 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000202 unsigned getMaxDisp() const {
Jakob Stoklund Olesen3ee36612012-03-31 00:06:44 +0000203 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000204 }
Evan Chenga8e29892007-01-19 07:51:42 +0000205 };
Bob Wilson84945262009-05-12 17:09:30 +0000206
Evan Chenga8e29892007-01-19 07:51:42 +0000207 /// CPUsers - Keep track of all of the machine instructions that use various
208 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000209 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000210
Evan Chengc99ef082007-02-09 20:54:44 +0000211 /// CPEntry - One per constant pool entry, keeping the machine instruction
212 /// pointer, the constpool index, and the number of CPUser's which
213 /// reference this entry.
214 struct CPEntry {
215 MachineInstr *CPEMI;
216 unsigned CPI;
217 unsigned RefCount;
218 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
219 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
220 };
221
222 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000223 /// instructions. For each original constpool index (i.e. those that
224 /// existed upon entry to this pass), it keeps a vector of entries.
225 /// Original elements are cloned as we go along; the clones are
226 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000227 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000228
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000229 /// ImmBranch - One per immediate branch, keeping the machine instruction
230 /// pointer, conditional or unconditional, the max displacement,
231 /// and (if isCond is true) the corresponding unconditional branch
232 /// opcode.
233 struct ImmBranch {
234 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000235 unsigned MaxDisp : 31;
236 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000237 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000238 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
239 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000240 };
241
Evan Cheng2706f972007-05-16 05:14:06 +0000242 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000243 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000244 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000245
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000246 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
247 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000248 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000249
Evan Cheng5657c012009-07-29 02:18:14 +0000250 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
251 SmallVector<MachineInstr*, 4> T2JumpTables;
252
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000253 /// HasFarJump - True if any far jump instruction has been emitted during
254 /// the branch fix up pass.
255 bool HasFarJump;
256
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000257 MachineFunction *MF;
258 MachineConstantPool *MCP;
Craig Topperacf20772012-03-25 23:49:58 +0000259 const ARMBaseInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000260 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000261 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000262 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000263 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000264 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000265 public:
Devang Patel19974732007-05-03 01:11:54 +0000266 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000267 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000268
Evan Cheng5657c012009-07-29 02:18:14 +0000269 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000270
271 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000272 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000273 }
Bob Wilson84945262009-05-12 17:09:30 +0000274
Evan Chenga8e29892007-01-19 07:51:42 +0000275 private:
Jim Grosbach7a465252012-03-23 23:07:03 +0000276 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000277 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000278 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach7a465252012-03-23 23:07:03 +0000279 void scanFunctionJumpTables();
280 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
281 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
282 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
283 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
284 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
285 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
286 bool findAvailableWater(CPUser&U, unsigned UserOffset,
287 water_iterator &WaterIter);
288 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000289 MachineBasicBlock *&NewMBB);
Jim Grosbach7a465252012-03-23 23:07:03 +0000290 bool handleConstantPoolUser(unsigned CPUserIndex);
291 void removeDeadCPEMI(MachineInstr *CPEMI);
292 bool removeUnusedCPEntries();
293 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
294 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
295 bool DoDump = false);
296 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000297 CPUser &U, unsigned &Growth);
Jim Grosbach7a465252012-03-23 23:07:03 +0000298 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
299 bool fixupImmediateBr(ImmBranch &Br);
300 bool fixupConditionalBr(ImmBranch &Br);
301 bool fixupUnconditionalBr(ImmBranch &Br);
302 bool undoLRSpillRestore();
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +0000303 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
Jim Grosbach7a465252012-03-23 23:07:03 +0000304 bool optimizeThumb2Instructions();
305 bool optimizeThumb2Branches();
306 bool reorderThumb2JumpTables();
307 bool optimizeThumb2JumpTables();
308 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000309 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000310
Jim Grosbach7a465252012-03-23 23:07:03 +0000311 void computeBlockSize(MachineBasicBlock *MBB);
312 unsigned getOffsetOf(MachineInstr *MI) const;
313 unsigned getUserOffset(CPUser&) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000314 void dumpBBs();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000315 void verify();
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000316
Jim Grosbach7a465252012-03-23 23:07:03 +0000317 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000318 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach7a465252012-03-23 23:07:03 +0000319 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000320 const CPUser &U) {
Jim Grosbach7a465252012-03-23 23:07:03 +0000321 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000322 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000323 }
Evan Chenga8e29892007-01-19 07:51:42 +0000324 };
Devang Patel19974732007-05-03 01:11:54 +0000325 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000326}
327
Dale Johannesen8593e412007-04-29 19:19:30 +0000328/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000329void ARMConstantIslands::verify() {
Evan Chengd3d9d662009-07-23 18:27:47 +0000330#ifndef NDEBUG
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000331 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000332 MBBI != E; ++MBBI) {
333 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000334 unsigned MBBId = MBB->getNumber();
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000335 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000336 }
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +0000337 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000338 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
339 CPUser &U = CPUsers[i];
Jim Grosbach7a465252012-03-23 23:07:03 +0000340 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesen3ee36612012-03-31 00:06:44 +0000341 // Verify offset using the real max displacement without the safety
342 // adjustment.
343 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +0000344 /* DoDump = */ true)) {
345 DEBUG(dbgs() << "OK\n");
346 continue;
347 }
348 DEBUG(dbgs() << "Out of range.\n");
349 dumpBBs();
350 DEBUG(MF->dump());
351 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000352 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000353#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000354}
355
356/// print block size and offset information - debugging
357void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000358 DEBUG({
359 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
360 const BasicBlockInfo &BBI = BBInfo[J];
361 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
362 << " kb=" << unsigned(BBI.KnownBits)
363 << " ua=" << unsigned(BBI.Unalign)
364 << " pa=" << unsigned(BBI.PostAlign)
365 << format(" size=%#x\n", BBInfo[J].Size);
366 }
367 });
Dale Johannesen8593e412007-04-29 19:19:30 +0000368}
369
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000370/// createARMConstantIslandPass - returns an instance of the constpool
371/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000372FunctionPass *llvm::createARMConstantIslandPass() {
373 return new ARMConstantIslands();
374}
375
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000376bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
377 MF = &mf;
378 MCP = mf.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000379
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000380 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000381 << MCP->getConstants().size() << " CP entries, aligned to "
382 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000383
Craig Topperacf20772012-03-25 23:49:58 +0000384 TII = (const ARMBaseInstrInfo*)MF->getTarget().getInstrInfo();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000385 AFI = MF->getInfo<ARMFunctionInfo>();
386 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000387
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000388 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000389 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000390 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000391
392 HasFarJump = false;
393
Jakob Stoklund Olesen7a4c0712012-03-29 23:14:26 +0000394 // This pass invalidates liveness information when it splits basic blocks.
395 MF->getRegInfo().invalidateLiveness();
396
Evan Chenga8e29892007-01-19 07:51:42 +0000397 // Renumber all of the machine basic blocks in the function, guaranteeing that
398 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000399 MF->RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000400
Jim Grosbach80697d12009-11-12 17:25:07 +0000401 // Try to reorder and otherwise adjust the block layout to make good use
402 // of the TB[BH] instructions.
403 bool MadeChange = false;
404 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach7a465252012-03-23 23:07:03 +0000405 scanFunctionJumpTables();
406 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach80697d12009-11-12 17:25:07 +0000407 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000408 T2JumpTables.clear();
409 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000410 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +0000411 }
412
Evan Chengd26b14c2009-07-31 18:28:05 +0000413 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000414 // This is so we can keep exact track of where the alignment padding goes.
415
Chris Lattner7d7dab02010-01-27 23:37:36 +0000416 // ARM and Thumb2 functions need to be 4-byte aligned.
417 if (!isThumb1)
Chad Rosier70cfaa32012-07-06 23:13:38 +0000418 MF->ensureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000419
Evan Chenga8e29892007-01-19 07:51:42 +0000420 // Perform the initial placement of the constant pool entries. To start with,
421 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000422 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000423 if (!MCP->isEmpty())
Jim Grosbach7a465252012-03-23 23:07:03 +0000424 doInitialPlacement(CPEMIs);
Bob Wilson84945262009-05-12 17:09:30 +0000425
Evan Chenga8e29892007-01-19 07:51:42 +0000426 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000427 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000428
Evan Chenga8e29892007-01-19 07:51:42 +0000429 // Do the initial scan of the function, building up information about the
430 // sizes of each block, the location of all the water, and finding all of the
431 // constant pool users.
Jim Grosbach7a465252012-03-23 23:07:03 +0000432 initializeFunctionInfo(CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000433 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000434 DEBUG(dumpBBs());
435
Bob Wilson84945262009-05-12 17:09:30 +0000436
Evan Chenged884f32007-04-03 23:39:48 +0000437 /// Remove dead constant pool entries.
Jim Grosbach7a465252012-03-23 23:07:03 +0000438 MadeChange |= removeUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000439
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000440 // Iteratively place constant pool entries and fix up branches until there
441 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000442 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000443 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000444 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000445 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000446 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jim Grosbach7a465252012-03-23 23:07:03 +0000447 CPChange |= handleConstantPoolUser(i);
Evan Chengb6879b22009-08-07 07:35:21 +0000448 if (CPChange && ++NoCPIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000449 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000450 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000451
Bob Wilsonb9239532009-10-15 20:49:47 +0000452 // Clear NewWaterList now. If we split a block for branches, it should
453 // appear as "new water" for the next iteration of constant pool placement.
454 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000455
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000456 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000457 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000458 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach7a465252012-03-23 23:07:03 +0000459 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Chengb6879b22009-08-07 07:35:21 +0000460 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000461 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000462 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000463
464 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000465 break;
466 MadeChange = true;
467 }
Evan Chenged884f32007-04-03 23:39:48 +0000468
Evan Chenga1efbbd2009-08-14 00:32:16 +0000469 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000470 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach7a465252012-03-23 23:07:03 +0000471 MadeChange |= optimizeThumb2Instructions();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000472
Dale Johannesen8593e412007-04-29 19:19:30 +0000473 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000474 verify();
Dale Johannesen8593e412007-04-29 19:19:30 +0000475
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000476 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
477 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000478 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach7a465252012-03-23 23:07:03 +0000479 MadeChange |= undoLRSpillRestore();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000480
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000481 // Save the mapping between original and cloned constpool entries.
482 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
483 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
484 const CPEntry & CPE = CPEntries[i][j];
485 AFI->recordCPEClone(i, CPE.CPI);
486 }
487 }
488
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000489 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000490
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000491 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000492 WaterList.clear();
493 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000494 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000495 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000496 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000497 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000498
499 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000500}
501
Jim Grosbach7a465252012-03-23 23:07:03 +0000502/// doInitialPlacement - Perform the initial placement of the constant pool
Evan Chenga8e29892007-01-19 07:51:42 +0000503/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000504void
Jim Grosbach7a465252012-03-23 23:07:03 +0000505ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000506 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000507 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
508 MF->push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000509
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000510 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000511 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000512
513 // Mark the basic block as required by the const-pool.
514 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
515 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
516
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000517 // The function needs to be as aligned as the basic blocks. The linker may
518 // move functions around based on their alignment.
Chad Rosier70cfaa32012-07-06 23:13:38 +0000519 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000520
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000521 // Order the entries in BB by descending alignment. That ensures correct
522 // alignment of all entries as long as BB is sufficiently aligned. Keep
523 // track of the insertion point for each alignment. We are going to bucket
524 // sort the entries as they are created.
525 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000526
Evan Chenga8e29892007-01-19 07:51:42 +0000527 // Add all of the constants from the constant pool to the end block, use an
528 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000529 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000530
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000531 const TargetData &TD = *MF->getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000532 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000533 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000534 assert(Size >= 4 && "Too small constant pool entry");
535 unsigned Align = CPs[i].getAlignment();
536 assert(isPowerOf2_32(Align) && "Invalid alignment");
537 // Verify that all constant pool entries are a multiple of their alignment.
538 // If not, we would have to pad them out so that instructions stay aligned.
539 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
540
541 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
542 unsigned LogAlign = Log2_32(Align);
543 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Chenga8e29892007-01-19 07:51:42 +0000544 MachineInstr *CPEMI =
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000545 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000546 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000547 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000548
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000549 // Ensure that future entries with higher alignment get inserted before
550 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesenb076fb72011-12-16 23:00:05 +0000551 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000552 if (InsPoint[a] == InsAt)
553 InsPoint[a] = CPEMI;
554
Evan Chengc99ef082007-02-09 20:54:44 +0000555 // Add a new CPEntry, but no corresponding CPUser yet.
556 std::vector<CPEntry> CPEs;
557 CPEs.push_back(CPEntry(CPEMI, i));
558 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000559 ++NumCPEs;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000560 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
561 << Size << ", align = " << Align <<'\n');
Evan Chenga8e29892007-01-19 07:51:42 +0000562 }
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000563 DEBUG(BB->dump());
Evan Chenga8e29892007-01-19 07:51:42 +0000564}
565
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000566/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000567/// into the block immediately after it.
568static bool BBHasFallthrough(MachineBasicBlock *MBB) {
569 // Get the next machine basic block in the function.
570 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000571 // Can't fall off end of function.
572 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000573 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000574
Chris Lattner7896c9f2009-12-03 00:50:42 +0000575 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000576 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
577 E = MBB->succ_end(); I != E; ++I)
578 if (*I == NextBB)
579 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000580
Evan Chenga8e29892007-01-19 07:51:42 +0000581 return false;
582}
583
Evan Chengc99ef082007-02-09 20:54:44 +0000584/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
585/// look up the corresponding CPEntry.
586ARMConstantIslands::CPEntry
587*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
588 const MachineInstr *CPEMI) {
589 std::vector<CPEntry> &CPEs = CPEntries[CPI];
590 // Number of entries per constpool index should be small, just do a
591 // linear search.
592 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
593 if (CPEs[i].CPEMI == CPEMI)
594 return &CPEs[i];
595 }
596 return NULL;
597}
598
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000599/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesenbd1ec172011-12-12 19:25:51 +0000600/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000601unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
602 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
603
604 // Everything is 4-byte aligned unless AlignConstantIslands is set.
605 if (!AlignConstantIslands)
606 return 2;
607
608 unsigned CPI = CPEMI->getOperand(1).getIndex();
609 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
610 unsigned Align = MCP->getConstants()[CPI].getAlignment();
611 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
612 return Log2_32(Align);
613}
614
Jim Grosbach7a465252012-03-23 23:07:03 +0000615/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach80697d12009-11-12 17:25:07 +0000616/// information about the sizes of each block and the locations of all
617/// the jump tables.
Jim Grosbach7a465252012-03-23 23:07:03 +0000618void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000619 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach80697d12009-11-12 17:25:07 +0000620 MBBI != E; ++MBBI) {
621 MachineBasicBlock &MBB = *MBBI;
622
Jim Grosbach80697d12009-11-12 17:25:07 +0000623 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000624 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000625 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000626 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000627 }
628}
629
Jim Grosbach7a465252012-03-23 23:07:03 +0000630/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Chenga8e29892007-01-19 07:51:42 +0000631/// information about the sizes of each block, the location of all the water,
632/// and finding all of the constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000633void ARMConstantIslands::
Jim Grosbach7a465252012-03-23 23:07:03 +0000634initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000635 BBInfo.clear();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000636 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000637
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000638 // First thing, compute the size of all basic blocks, and see if the function
639 // has any inline assembly in it. If so, we have to be conservative about
640 // alignment assumptions, as we don't know for sure the size of any
641 // instructions in the inline assembly.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000642 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jim Grosbach7a465252012-03-23 23:07:03 +0000643 computeBlockSize(I);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000644
645 // The known bits of the entry block offset are determined by the function
646 // alignment.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000647 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000648
649 // Compute block offsets and known bits.
Jim Grosbach7a465252012-03-23 23:07:03 +0000650 adjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000651
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000652 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000653 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chenga8e29892007-01-19 07:51:42 +0000654 MBBI != E; ++MBBI) {
655 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000656
Evan Chenga8e29892007-01-19 07:51:42 +0000657 // If this block doesn't fall through into the next MBB, then this is
658 // 'water' that a constant pool island could be placed.
659 if (!BBHasFallthrough(&MBB))
660 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000661
Evan Chenga8e29892007-01-19 07:51:42 +0000662 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
663 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000664 if (I->isDebugValue())
665 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000666
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000667 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000668 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000669 bool isCond = false;
670 unsigned Bits = 0;
671 unsigned Scale = 1;
672 int UOpc = Opc;
673 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000674 default:
675 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000676 case ARM::t2BR_JT:
677 T2JumpTables.push_back(I);
678 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000679 case ARM::Bcc:
680 isCond = true;
681 UOpc = ARM::B;
682 // Fallthrough
683 case ARM::B:
684 Bits = 24;
685 Scale = 4;
686 break;
687 case ARM::tBcc:
688 isCond = true;
689 UOpc = ARM::tB;
690 Bits = 8;
691 Scale = 2;
692 break;
693 case ARM::tB:
694 Bits = 11;
695 Scale = 2;
696 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000697 case ARM::t2Bcc:
698 isCond = true;
699 UOpc = ARM::t2B;
700 Bits = 20;
701 Scale = 2;
702 break;
703 case ARM::t2B:
704 Bits = 24;
705 Scale = 2;
706 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000707 }
Evan Chengb43216e2007-02-01 10:16:15 +0000708
709 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000710 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000711 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000712 }
713
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000714 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
715 PushPopMIs.push_back(I);
716
Evan Chengd3d9d662009-07-23 18:27:47 +0000717 if (Opc == ARM::CONSTPOOL_ENTRY)
718 continue;
719
Evan Chenga8e29892007-01-19 07:51:42 +0000720 // Scan the instructions for constant pool operands.
721 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000722 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000723 // We found one. The addressing mode tells us the max displacement
724 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000725
Evan Chenga8e29892007-01-19 07:51:42 +0000726 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000727 unsigned Bits = 0;
728 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000729 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000730 bool IsSoImm = false;
731
732 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000733 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000734 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000735
736 // Taking the address of a CP entry.
737 case ARM::LEApcrel:
738 // This takes a SoImm, which is 8 bit immediate rotated. We'll
739 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000740 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000741 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000742 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000743 Scale = 4;
744 NegOk = true;
745 IsSoImm = true;
746 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000747 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000748 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000749 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000750 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000751 case ARM::tLEApcrel:
752 Bits = 8;
753 Scale = 4;
754 break;
755
Jim Grosbach3e556122010-10-26 22:37:02 +0000756 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000757 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000758 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000759 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000760 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000761 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000762
763 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000764 Bits = 8;
765 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000766 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000767
Jim Grosbache5165492009-11-09 00:11:35 +0000768 case ARM::VLDRD:
769 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000770 Bits = 8;
771 Scale = 4; // +-(offset_8*4)
772 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000773 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000774 }
Evan Chengb43216e2007-02-01 10:16:15 +0000775
Evan Chenga8e29892007-01-19 07:51:42 +0000776 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000777 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000778 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000779 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000780 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000781
782 // Increment corresponding CPEntry reference count.
783 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
784 assert(CPE && "Cannot find a corresponding CPEntry!");
785 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000786
Evan Chenga8e29892007-01-19 07:51:42 +0000787 // Instructions can only use one CP entry, don't bother scanning the
788 // rest of the operands.
789 break;
790 }
791 }
Evan Chenga8e29892007-01-19 07:51:42 +0000792 }
793}
794
Jim Grosbach7a465252012-03-23 23:07:03 +0000795/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000796/// This function updates BBInfo directly.
Jim Grosbach7a465252012-03-23 23:07:03 +0000797void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000798 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
799 BBI.Size = 0;
800 BBI.Unalign = 0;
801 BBI.PostAlign = 0;
802
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000803 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
804 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000805 BBI.Size += TII->GetInstSizeInBytes(I);
806 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
807 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000808 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000809 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +0000810 // Also consider instructions that may be shrunk later.
811 else if (isThumb && mayOptimizeThumb2Instruction(I))
812 BBI.Unalign = 1;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000813 }
814
815 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000816 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000817 BBI.PostAlign = 2;
Chad Rosier70cfaa32012-07-06 23:13:38 +0000818 MBB->getParent()->ensureAlignment(2);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000819 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000820}
821
Jim Grosbach7a465252012-03-23 23:07:03 +0000822/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Chenga8e29892007-01-19 07:51:42 +0000823/// from the start of the function. This offset changes as stuff is moved
824/// around inside the function.
Jim Grosbach7a465252012-03-23 23:07:03 +0000825unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Chenga8e29892007-01-19 07:51:42 +0000826 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000827
Evan Chenga8e29892007-01-19 07:51:42 +0000828 // The offset is composed of two things: the sum of the sizes of all MBB's
829 // before this instruction's block, and the offset from the start of the block
830 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000831 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000832
833 // Sum instructions before MI in MBB.
Jim Grosbach0c3cfef2012-01-31 20:56:55 +0000834 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Chenga8e29892007-01-19 07:51:42 +0000835 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000836 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000837 }
Jim Grosbach0c3cfef2012-01-31 20:56:55 +0000838 return Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000839}
840
841/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
842/// ID.
843static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
844 const MachineBasicBlock *RHS) {
845 return LHS->getNumber() < RHS->getNumber();
846}
847
Jim Grosbach7a465252012-03-23 23:07:03 +0000848/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Chenga8e29892007-01-19 07:51:42 +0000849/// machine function, it upsets all of the block numbers. Renumber the blocks
850/// and update the arrays that parallel this numbering.
Jim Grosbach7a465252012-03-23 23:07:03 +0000851void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000852 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000853 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000854
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000855 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000856 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000857 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000858
859 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000860 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000861 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000862 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
863 CompareMBBNumbers);
864 WaterList.insert(IP, NewBB);
865}
866
867
868/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000869/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000870/// account for this change and returns the newly created block.
Jim Grosbach7a465252012-03-23 23:07:03 +0000871MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000872 MachineBasicBlock *OrigBB = MI->getParent();
873
874 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000875 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000876 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000877 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000878 MF->insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000879
Evan Chenga8e29892007-01-19 07:51:42 +0000880 // Splice the instructions starting with MI over to NewBB.
881 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000882
Evan Chenga8e29892007-01-19 07:51:42 +0000883 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000884 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000885 // There doesn't seem to be meaningful DebugInfo available; this doesn't
886 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000887 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000888 if (!isThumb)
889 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
890 else
891 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
892 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000893 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000894
Evan Chenga8e29892007-01-19 07:51:42 +0000895 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000896 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000897
Evan Chenga8e29892007-01-19 07:51:42 +0000898 // OrigBB branches to NewBB.
899 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000900
Evan Chenga8e29892007-01-19 07:51:42 +0000901 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach7a465252012-03-23 23:07:03 +0000902 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000903 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000904 MF->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000905
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000906 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000907 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000908 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000909
Bob Wilson84945262009-05-12 17:09:30 +0000910 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000911 // available water after it (but not if it's already there, which happens
912 // when splitting before a conditional branch that is followed by an
913 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000914 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000915 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
916 CompareMBBNumbers);
917 MachineBasicBlock* WaterBB = *IP;
918 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000919 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000920 else
921 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000922 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000923
Dale Johannesen8086d582010-07-23 22:50:23 +0000924 // Figure out how large the OrigBB is. As the first half of the original
925 // block, it cannot contain a tablejump. The size includes
926 // the new jump we added. (It should be possible to do this without
927 // recounting everything, but it's very confusing, and this is rarely
928 // executed.)
Jim Grosbach7a465252012-03-23 23:07:03 +0000929 computeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000930
Dale Johannesen8086d582010-07-23 22:50:23 +0000931 // Figure out how large the NewMBB is. As the second half of the original
932 // block, it may contain a tablejump.
Jim Grosbach7a465252012-03-23 23:07:03 +0000933 computeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000934
Dale Johannesen99c49a42007-02-25 00:47:03 +0000935 // All BBOffsets following these blocks must be modified.
Jim Grosbach7a465252012-03-23 23:07:03 +0000936 adjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000937
938 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000939}
940
Jim Grosbach7a465252012-03-23 23:07:03 +0000941/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000942/// displacement computation. Update U.KnownAlignment to match its current
943/// basic block location.
Jim Grosbach7a465252012-03-23 23:07:03 +0000944unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
945 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000946 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
947 unsigned KnownBits = BBI.internalKnownBits();
948
949 // The value read from PC is offset from the actual instruction address.
950 UserOffset += (isThumb ? 4 : 8);
951
952 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
953 // Make sure U.getMaxDisp() returns a constrained range.
954 U.KnownAlignment = (KnownBits >= 2);
955
956 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
957 // purposes of the displacement computation; compensate for that here.
958 // For unknown alignments, getMaxDisp() constrains the range instead.
959 if (isThumb && U.KnownAlignment)
960 UserOffset &= ~3u;
961
962 return UserOffset;
963}
964
Jim Grosbach7a465252012-03-23 23:07:03 +0000965/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000966/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000967/// constant pool entry).
Jim Grosbach7a465252012-03-23 23:07:03 +0000968/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000969/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
970/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach7a465252012-03-23 23:07:03 +0000971bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000972 unsigned TrialOffset, unsigned MaxDisp,
973 bool NegativeOK, bool IsSoImm) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000974 if (UserOffset <= TrialOffset) {
975 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000976 if (TrialOffset - UserOffset <= MaxDisp)
977 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000978 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000979 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000980 if (UserOffset - TrialOffset <= MaxDisp)
981 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000982 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000983 }
984 return false;
985}
986
Jim Grosbach7a465252012-03-23 23:07:03 +0000987/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000988/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000989///
990/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach7a465252012-03-23 23:07:03 +0000991bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000992 MachineBasicBlock* Water, CPUser &U,
993 unsigned &Growth) {
994 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
995 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
996 unsigned NextBlockOffset, NextBlockAlignment;
997 MachineFunction::const_iterator NextBlock = Water;
998 if (++NextBlock == MF->end()) {
999 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1000 NextBlockAlignment = 0;
1001 } else {
1002 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1003 NextBlockAlignment = NextBlock->getAlignment();
1004 }
1005 unsigned Size = U.CPEMI->getOperand(2).getImm();
1006 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001007
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001008 // The CPE may be able to hide in the alignment padding before the next
1009 // block. It may also cause more padding to be required if it is more aligned
1010 // that the next block.
1011 if (CPEEnd > NextBlockOffset) {
1012 Growth = CPEEnd - NextBlockOffset;
1013 // Compute the padding that would go at the end of the CPE to align the next
1014 // block.
1015 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1016
1017 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach7a465252012-03-23 23:07:03 +00001018 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001019 // in blocks between CPE and the user.
1020 if (CPEOffset < UserOffset)
1021 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1022 } else
1023 // CPE fits in existing padding.
1024 Growth = 0;
Dale Johannesend959aa42007-04-02 20:31:06 +00001025
Jim Grosbach7a465252012-03-23 23:07:03 +00001026 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001027}
1028
Jim Grosbach7a465252012-03-23 23:07:03 +00001029/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +00001030/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001031bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001032 MachineInstr *CPEMI, unsigned MaxDisp,
1033 bool NegOk, bool DoDump) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001034 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng2021abe2007-02-01 01:09:47 +00001035
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001036 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001037 DEBUG({
1038 unsigned Block = MI->getParent()->getNumber();
1039 const BasicBlockInfo &BBI = BBInfo[Block];
1040 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1041 << " max delta=" << MaxDisp
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001042 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001043 << " in BB#" << Block << ": "
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001044 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1045 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1046 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001047 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001048 }
Evan Chengc0dbec72007-01-31 19:57:44 +00001049
Jim Grosbach7a465252012-03-23 23:07:03 +00001050 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +00001051}
1052
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001053#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001054/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1055/// unconditionally branches to its only successor.
1056static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1057 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1058 return false;
1059
1060 MachineBasicBlock *Succ = *MBB->succ_begin();
1061 MachineBasicBlock *Pred = *MBB->pred_begin();
1062 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001063 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1064 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +00001065 return PredMI->getOperand(0).getMBB() == Succ;
1066 return false;
1067}
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001068#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001069
Jim Grosbach7a465252012-03-23 23:07:03 +00001070void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001071 unsigned BBNum = BB->getNumber();
1072 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001073 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +00001074 // Include the alignment of the current block.
1075 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1076 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1077 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001078
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001079 // This is where block i begins. Stop if the offset is already correct,
1080 // and we have updated 2 blocks. This is the maximum number of blocks
1081 // changed before calling this function.
1082 if (i > BBNum + 2 &&
1083 BBInfo[i].Offset == Offset &&
1084 BBInfo[i].KnownBits == KnownBits)
1085 break;
1086
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001087 BBInfo[i].Offset = Offset;
1088 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +00001089 }
Dale Johannesen99c49a42007-02-25 00:47:03 +00001090}
1091
Jim Grosbach7a465252012-03-23 23:07:03 +00001092/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001093/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +00001094/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001095/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +00001096
Jim Grosbach7a465252012-03-23 23:07:03 +00001097bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1098 MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +00001099 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +00001100 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1101 assert(CPE && "Unexpected!");
1102 if (--CPE->RefCount == 0) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001103 removeDeadCPEMI(CPEMI);
Evan Chenged884f32007-04-03 23:39:48 +00001104 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +00001105 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001106 return true;
1107 }
1108 return false;
1109}
1110
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001111/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1112/// if not, see if an in-range clone of the CPE is in range, and if so,
1113/// change the data structures so the user references the clone. Returns:
1114/// 0 = no existing entry found
1115/// 1 = entry found, and there were no code insertions or deletions
1116/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach7a465252012-03-23 23:07:03 +00001117int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001118{
1119 MachineInstr *UserMI = U.MI;
1120 MachineInstr *CPEMI = U.CPEMI;
1121
1122 // Check to see if the CPE is already in-range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001123 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1124 true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001125 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001126 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001127 }
1128
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001129 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001130 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001131 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1132 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1133 // We already tried this one
1134 if (CPEs[i].CPEMI == CPEMI)
1135 continue;
1136 // Removing CPEs can leave empty entries, skip
1137 if (CPEs[i].CPEMI == NULL)
1138 continue;
Jim Grosbach7a465252012-03-23 23:07:03 +00001139 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001140 U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001141 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001142 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001143 // Point the CPUser node to the replacement
1144 U.CPEMI = CPEs[i].CPEMI;
1145 // Change the CPI in the instruction operand to refer to the clone.
1146 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001147 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001148 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001149 break;
1150 }
1151 // Adjust the refcount of the clone...
1152 CPEs[i].RefCount++;
1153 // ...and the original. If we didn't remove the old entry, none of the
1154 // addresses changed, so we don't need another pass.
Jim Grosbach7a465252012-03-23 23:07:03 +00001155 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001156 }
1157 }
1158 return 0;
1159}
1160
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001161/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1162/// the specific unconditional branch instruction.
1163static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001164 switch (Opc) {
1165 case ARM::tB:
1166 return ((1<<10)-1)*2;
1167 case ARM::t2B:
1168 return ((1<<23)-1)*2;
1169 default:
1170 break;
1171 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001172
David Goodwin5e47a9a2009-06-30 18:04:13 +00001173 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001174}
1175
Jim Grosbach7a465252012-03-23 23:07:03 +00001176/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001177/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001178/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001179/// is set to the WaterList entry. For Thumb, prefer water that will not
1180/// introduce padding to water that will. To ensure that this pass
1181/// terminates, the CPE location for a particular CPUser is only allowed to
1182/// move to a lower address, so search backward from the end of the list and
1183/// prefer the first water that is in range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001184bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001185 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001186 if (WaterList.empty())
1187 return false;
1188
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001189 unsigned BestGrowth = ~0u;
1190 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1191 --IP) {
Bob Wilson3b757352009-10-12 19:04:03 +00001192 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001193 // Check if water is in range and is either at a lower address than the
1194 // current "high water mark" or a new water block that was created since
1195 // the previous iteration by inserting an unconditional branch. In the
1196 // latter case, we want to allow resetting the high water mark back to
1197 // this new water since we haven't seen it before. Inserting branches
1198 // should be relatively uncommon and when it does happen, we want to be
1199 // sure to take advantage of it for all the CPEs near that block, so that
1200 // we don't insert more branches than necessary.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001201 unsigned Growth;
Jim Grosbach7a465252012-03-23 23:07:03 +00001202 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilsonb9239532009-10-15 20:49:47 +00001203 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001204 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1205 // This is the least amount of required padding seen so far.
1206 BestGrowth = Growth;
1207 WaterIter = IP;
1208 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1209 << " Growth=" << Growth << '\n');
1210
1211 // Keep looking unless it is perfect.
1212 if (BestGrowth == 0)
Bob Wilson3b757352009-10-12 19:04:03 +00001213 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001214 }
Bob Wilson3b757352009-10-12 19:04:03 +00001215 if (IP == B)
1216 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001217 }
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001218 return BestGrowth != ~0u;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001219}
1220
Jim Grosbach7a465252012-03-23 23:07:03 +00001221/// createNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001222/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1223/// block is used if in range, and the conditional branch munged so control
1224/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001225/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001226/// block following which the new island can be inserted (the WaterList
1227/// is not adjusted).
Jim Grosbach7a465252012-03-23 23:07:03 +00001228void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001229 unsigned UserOffset,
1230 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001231 CPUser &U = CPUsers[CPUserIndex];
1232 MachineInstr *UserMI = U.MI;
1233 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001234 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001235 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001236 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001237
Bob Wilson36fa5322009-10-15 05:10:36 +00001238 // If the block does not end in an unconditional branch already, and if the
1239 // end of the block is within range, make new water there. (The addition
1240 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001241 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001242 if (BBHasFallthrough(UserMBB)) {
1243 // Size of branch to insert.
1244 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001245 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +00001246 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001247
Jim Grosbach7a465252012-03-23 23:07:03 +00001248 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001249 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1250 << format(", expected CPE offset %#x\n", CPEOffset));
1251 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1252 // Add an unconditional branch from UserMBB to fallthrough block. Record
1253 // it for branch lengthening; this new branch will not get out of range,
1254 // but if the preceding conditional branch is out of range, the targets
1255 // will be exchanged, and the altered branch may be out of range, so the
1256 // machinery has to know about it.
1257 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1258 if (!isThumb)
1259 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1260 else
1261 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1262 .addImm(ARMCC::AL).addReg(0);
1263 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1264 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1265 MaxDisp, false, UncondBr));
1266 BBInfo[UserMBB->getNumber()].Size += Delta;
Jim Grosbach7a465252012-03-23 23:07:03 +00001267 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001268 return;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001269 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001270 }
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001271
1272 // What a big block. Find a place within the block to split it. This is a
1273 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1274 // entries are 4 bytes: if instruction I references island CPE, and
1275 // instruction I+1 references CPE', it will not work well to put CPE as far
1276 // forward as possible, since then CPE' cannot immediately follow it (that
1277 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1278 // need to create a new island. So, we make a first guess, then walk through
1279 // the instructions between the one currently being looked at and the
1280 // possible insertion point, and make sure any other instructions that
1281 // reference CPEs will be able to use the same island area; if not, we back
1282 // up the insertion point.
1283
1284 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +00001285 // point where we can add a 4-byte branch instruction, and then align to
1286 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001287 unsigned LogAlign = MF->getAlignment();
1288 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1289 unsigned KnownBits = UserBBI.internalKnownBits();
1290 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +00001291 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001292 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1293 BaseInsertOffset));
1294
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001295 // The 4 in the following is for the unconditional branch we'll be inserting
1296 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach7a465252012-03-23 23:07:03 +00001297 // inside isOffsetInRange.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001298 BaseInsertOffset -= 4;
1299
1300 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1301 << " la=" << LogAlign
1302 << " kb=" << KnownBits
1303 << " up=" << UPad << '\n');
1304
1305 // This could point off the end of the block if we've already got constant
1306 // pool entries following this block; only the last one is in the water list.
1307 // Back past any possible branches (allow for a conditional and a maximally
1308 // long unconditional).
Jakob Stoklund Olesen9b10dae2012-04-28 06:21:38 +00001309 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1310 BaseInsertOffset = UserBBI.postOffset() - UPad - 8;
1311 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1312 }
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +00001313 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001314 CPEMI->getOperand(2).getImm();
1315 MachineBasicBlock::iterator MI = UserMI;
1316 ++MI;
1317 unsigned CPUIndex = CPUserIndex+1;
1318 unsigned NumCPUsers = CPUsers.size();
1319 MachineInstr *LastIT = 0;
1320 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1321 Offset < BaseInsertOffset;
1322 Offset += TII->GetInstSizeInBytes(MI),
1323 MI = llvm::next(MI)) {
Jakob Stoklund Olesen9b10dae2012-04-28 06:21:38 +00001324 assert(MI != UserMBB->end() && "Fell off end of block");
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001325 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1326 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach7a465252012-03-23 23:07:03 +00001327 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001328 // Shift intertion point by one unit of alignment so it is within reach.
1329 BaseInsertOffset -= 1u << LogAlign;
1330 EndInsertOffset -= 1u << LogAlign;
1331 }
1332 // This is overly conservative, as we don't account for CPEMIs being
1333 // reused within the block, but it doesn't matter much. Also assume CPEs
1334 // are added in order with alignment padding. We may eventually be able
1335 // to pack the aligned CPEs better.
Jakob Stoklund Olesen456ff462012-04-27 22:58:38 +00001336 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001337 CPUIndex++;
1338 }
1339
1340 // Remember the last IT instruction.
1341 if (MI->getOpcode() == ARM::t2IT)
1342 LastIT = MI;
1343 }
1344
1345 --MI;
1346
1347 // Avoid splitting an IT block.
1348 if (LastIT) {
1349 unsigned PredReg = 0;
Craig Topperc89c7442012-03-27 07:21:54 +00001350 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001351 if (CC != ARMCC::AL)
1352 MI = LastIT;
1353 }
Jim Grosbach7a465252012-03-23 23:07:03 +00001354 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001355}
1356
Jim Grosbach7a465252012-03-23 23:07:03 +00001357/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001358/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001359/// place in-range. Return true if we changed any addresses (thus must run
1360/// another pass of branch lengthening), false otherwise.
Jim Grosbach7a465252012-03-23 23:07:03 +00001361bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001362 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001363 MachineInstr *UserMI = U.MI;
1364 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001365 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001366 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001367 // Compute this only once, it's expensive.
Jim Grosbach7a465252012-03-23 23:07:03 +00001368 unsigned UserOffset = getUserOffset(U);
Evan Cheng768c9f72007-04-27 08:14:15 +00001369
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001370 // See if the current entry is within range, or there is a clone of it
1371 // in range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001372 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001373 if (result==1) return false;
1374 else if (result==2) return true;
1375
1376 // No existing clone of this CPE is within range.
1377 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001378 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001379
Bob Wilsonf98032e2009-10-12 21:23:15 +00001380 // Look for water where we can place this CPE.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001381 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilsonb9239532009-10-15 20:49:47 +00001382 MachineBasicBlock *NewMBB;
1383 water_iterator IP;
Jim Grosbach7a465252012-03-23 23:07:03 +00001384 if (findAvailableWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001385 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001386 MachineBasicBlock *WaterBB = *IP;
1387
1388 // If the original WaterList entry was "new water" on this iteration,
1389 // propagate that to the new island. This is just keeping NewWaterList
1390 // updated to match the WaterList, which will be updated below.
1391 if (NewWaterList.count(WaterBB)) {
1392 NewWaterList.erase(WaterBB);
1393 NewWaterList.insert(NewIsland);
1394 }
1395 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001396 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001397
1398 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001399 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001400 DEBUG(dbgs() << "No water found\n");
Jim Grosbach7a465252012-03-23 23:07:03 +00001401 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001402
Jim Grosbach7a465252012-03-23 23:07:03 +00001403 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilsonb9239532009-10-15 20:49:47 +00001404 // called while handling branches so that the water will be seen on the
1405 // next iteration for constant pools, but in this context, we don't want
1406 // it. Check for this so it will be removed from the WaterList.
1407 // Also remove any entry from NewWaterList.
1408 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1409 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1410 if (IP != WaterList.end())
1411 NewWaterList.erase(WaterBB);
1412
1413 // We are adding new water. Update NewWaterList.
1414 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001415 }
1416
Bob Wilsonb9239532009-10-15 20:49:47 +00001417 // Remove the original WaterList entry; we want subsequent insertions in
1418 // this vicinity to go after the one we're about to insert. This
1419 // considerably reduces the number of times we have to move the same CPE
1420 // more than once and is also important to ensure the algorithm terminates.
1421 if (IP != WaterList.end())
1422 WaterList.erase(IP);
1423
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001424 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001425 MF->insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001426
1427 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach7a465252012-03-23 23:07:03 +00001428 updateForInsertedWaterBlock(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001429
1430 // Decrement the old entry, and remove it if refcount becomes 0.
Jim Grosbach7a465252012-03-23 23:07:03 +00001431 decrementCPEReferenceCount(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001432
1433 // Now that we have an island to add the CPE to, clone the original CPE and
1434 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001435 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001436 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001437 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001438 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001439 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001440
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001441 // Mark the basic block as aligned as required by the const-pool entry.
1442 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001443
Evan Chenga8e29892007-01-19 07:51:42 +00001444 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001445 BBInfo[NewIsland->getNumber()].Size += Size;
Jim Grosbach7a465252012-03-23 23:07:03 +00001446 adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001447
Evan Chenga8e29892007-01-19 07:51:42 +00001448 // Finally, change the CPI in the instruction operand to be ID.
1449 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001450 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001451 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001452 break;
1453 }
Bob Wilson84945262009-05-12 17:09:30 +00001454
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001455 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001456 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson84945262009-05-12 17:09:30 +00001457
Evan Chenga8e29892007-01-19 07:51:42 +00001458 return true;
1459}
1460
Jim Grosbach7a465252012-03-23 23:07:03 +00001461/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Chenged884f32007-04-03 23:39:48 +00001462/// sizes and offsets of impacted basic blocks.
Jim Grosbach7a465252012-03-23 23:07:03 +00001463void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Chenged884f32007-04-03 23:39:48 +00001464 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001465 unsigned Size = CPEMI->getOperand(2).getImm();
1466 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001467 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001468 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001469 if (CPEBB->empty()) {
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001470 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001471
1472 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1473 CPEBB->setAlignment(0);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001474 } else
1475 // Entries are sorted by descending alignment, so realign from the front.
1476 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1477
Jim Grosbach7a465252012-03-23 23:07:03 +00001478 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001479 // An island has only one predecessor BB and one successor BB. Check if
1480 // this BB's predecessor jumps directly to this BB's successor. This
1481 // shouldn't happen currently.
1482 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1483 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001484}
1485
Jim Grosbach7a465252012-03-23 23:07:03 +00001486/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Chenged884f32007-04-03 23:39:48 +00001487/// are zero.
Jim Grosbach7a465252012-03-23 23:07:03 +00001488bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Chenged884f32007-04-03 23:39:48 +00001489 unsigned MadeChange = false;
1490 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1491 std::vector<CPEntry> &CPEs = CPEntries[i];
1492 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1493 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001494 removeDeadCPEMI(CPEs[j].CPEMI);
Evan Chenged884f32007-04-03 23:39:48 +00001495 CPEs[j].CPEMI = NULL;
1496 MadeChange = true;
1497 }
1498 }
Bob Wilson84945262009-05-12 17:09:30 +00001499 }
Evan Chenged884f32007-04-03 23:39:48 +00001500 return MadeChange;
1501}
1502
Jim Grosbach7a465252012-03-23 23:07:03 +00001503/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001504/// specific BB can fit in MI's displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001505bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Chengc0dbec72007-01-31 19:57:44 +00001506 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001507 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach7a465252012-03-23 23:07:03 +00001508 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001509 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001510
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001511 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001512 << " from BB#" << MI->getParent()->getNumber()
1513 << " max delta=" << MaxDisp
Jim Grosbach7a465252012-03-23 23:07:03 +00001514 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattner705e07f2009-08-23 03:41:05 +00001515 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001516
Dale Johannesen8593e412007-04-29 19:19:30 +00001517 if (BrOffset <= DestOffset) {
1518 // Branch before the Dest.
1519 if (DestOffset-BrOffset <= MaxDisp)
1520 return true;
1521 } else {
1522 if (BrOffset-DestOffset <= MaxDisp)
1523 return true;
1524 }
1525 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001526}
1527
Jim Grosbach7a465252012-03-23 23:07:03 +00001528/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001529/// away to fit in its displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001530bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001531 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001532 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001533
Evan Chengc0dbec72007-01-31 19:57:44 +00001534 // Check to see if the DestBB is already in-range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001535 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001536 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001537
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001538 if (!Br.isCond)
Jim Grosbach7a465252012-03-23 23:07:03 +00001539 return fixupUnconditionalBr(Br);
1540 return fixupConditionalBr(Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001541}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001542
Jim Grosbach7a465252012-03-23 23:07:03 +00001543/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001544/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001545/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001546/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001547bool
Jim Grosbach7a465252012-03-23 23:07:03 +00001548ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001549 MachineInstr *MI = Br.MI;
1550 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001551 if (!isThumb1)
Jim Grosbach7a465252012-03-23 23:07:03 +00001552 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001553
1554 // Use BL to implement far jump.
1555 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001556 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001557 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001558 adjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001559 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001560 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001561
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001562 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001563
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001564 return true;
1565}
1566
Jim Grosbach7a465252012-03-23 23:07:03 +00001567/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001568/// far away to fit in its displacement field. It is converted to an inverse
1569/// conditional branch + an unconditional branch to the destination.
1570bool
Jim Grosbach7a465252012-03-23 23:07:03 +00001571ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001572 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001573 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001574
Bob Wilson39bf0512009-05-12 17:35:29 +00001575 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001576 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001577 // blt L1
1578 // =>
1579 // bge L2
1580 // b L1
1581 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001582 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001583 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001584 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001585
1586 // If the branch is at the end of its MBB and that has a fall-through block,
1587 // direct the updated conditional branch to the fall-through block. Otherwise,
1588 // split the MBB before the next instruction.
1589 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001590 MachineInstr *BMI = &MBB->back();
1591 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001592
Dan Gohmanfe601042010-06-22 15:08:57 +00001593 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001594 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001595 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001596 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001597 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001598 // condition and swap destinations:
1599 // beq L1
1600 // b L2
1601 // =>
1602 // bne L2
1603 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001604 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach7a465252012-03-23 23:07:03 +00001605 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001606 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001607 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001608 BMI->getOperand(0).setMBB(DestBB);
1609 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001610 MI->getOperand(1).setImm(CC);
1611 return true;
1612 }
1613 }
1614 }
1615
1616 if (NeedSplit) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001617 splitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001618 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001619 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001620 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001621 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001622 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001623 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001624 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001625 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001626
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001627 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001628 << " also invert condition and change dest. to BB#"
1629 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001630
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001631 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001632 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001633 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001634 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001635 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001636 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001637 if (isThumb)
1638 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1639 .addImm(ARMCC::AL).addReg(0);
1640 else
1641 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001642 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001643 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001644 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001645
1646 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001647 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001648 MI->eraseFromParent();
Jim Grosbach7a465252012-03-23 23:07:03 +00001649 adjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001650 return true;
1651}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001652
Jim Grosbach7a465252012-03-23 23:07:03 +00001653/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001654/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1655/// to do this if tBfar is not used.
Jim Grosbach7a465252012-03-23 23:07:03 +00001656bool ARMConstantIslands::undoLRSpillRestore() {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001657 bool MadeChange = false;
1658 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1659 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001660 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001661 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001662 MI->getOperand(2).getReg() == ARM::PC &&
1663 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001664 // Create the new insn and copy the predicate from the old.
1665 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1666 .addOperand(MI->getOperand(0))
1667 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001668 MI->eraseFromParent();
1669 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001670 }
1671 }
1672 return MadeChange;
1673}
Evan Cheng5657c012009-07-29 02:18:14 +00001674
Jim Grosbach7a465252012-03-23 23:07:03 +00001675// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001676// below may shrink MI.
1677bool
1678ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1679 switch(MI->getOpcode()) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001680 // optimizeThumb2Instructions.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001681 case ARM::t2LEApcrel:
1682 case ARM::t2LDRpci:
Jim Grosbach7a465252012-03-23 23:07:03 +00001683 // optimizeThumb2Branches.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001684 case ARM::t2B:
1685 case ARM::t2Bcc:
1686 case ARM::tBcc:
Jim Grosbach7a465252012-03-23 23:07:03 +00001687 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001688 case ARM::t2BR_JT:
1689 return true;
1690 }
1691 return false;
1692}
1693
Jim Grosbach7a465252012-03-23 23:07:03 +00001694bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chenga1efbbd2009-08-14 00:32:16 +00001695 bool MadeChange = false;
1696
1697 // Shrink ADR and LDR from constantpool.
1698 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1699 CPUser &U = CPUsers[i];
1700 unsigned Opcode = U.MI->getOpcode();
1701 unsigned NewOpc = 0;
1702 unsigned Scale = 1;
1703 unsigned Bits = 0;
1704 switch (Opcode) {
1705 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001706 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001707 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1708 NewOpc = ARM::tLEApcrel;
1709 Bits = 8;
1710 Scale = 4;
1711 }
1712 break;
1713 case ARM::t2LDRpci:
1714 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1715 NewOpc = ARM::tLDRpci;
1716 Bits = 8;
1717 Scale = 4;
1718 }
1719 break;
1720 }
1721
1722 if (!NewOpc)
1723 continue;
1724
Jim Grosbach7a465252012-03-23 23:07:03 +00001725 unsigned UserOffset = getUserOffset(U);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001726 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001727
1728 // Be conservative with inline asm.
1729 if (!U.KnownAlignment)
1730 MaxOffs -= 2;
1731
Evan Chenga1efbbd2009-08-14 00:32:16 +00001732 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach7a465252012-03-23 23:07:03 +00001733 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001734 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001735 U.MI->setDesc(TII->get(NewOpc));
1736 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001737 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001738 adjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001739 ++NumT2CPShrunk;
1740 MadeChange = true;
1741 }
1742 }
1743
Jim Grosbach7a465252012-03-23 23:07:03 +00001744 MadeChange |= optimizeThumb2Branches();
1745 MadeChange |= optimizeThumb2JumpTables();
Evan Chenga1efbbd2009-08-14 00:32:16 +00001746 return MadeChange;
1747}
1748
Jim Grosbach7a465252012-03-23 23:07:03 +00001749bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001750 bool MadeChange = false;
1751
1752 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1753 ImmBranch &Br = ImmBranches[i];
1754 unsigned Opcode = Br.MI->getOpcode();
1755 unsigned NewOpc = 0;
1756 unsigned Scale = 1;
1757 unsigned Bits = 0;
1758 switch (Opcode) {
1759 default: break;
1760 case ARM::t2B:
1761 NewOpc = ARM::tB;
1762 Bits = 11;
1763 Scale = 2;
1764 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001765 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001766 NewOpc = ARM::tBcc;
1767 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001768 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001769 break;
1770 }
Evan Chengde17fb62009-10-31 23:46:45 +00001771 }
1772 if (NewOpc) {
1773 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1774 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach7a465252012-03-23 23:07:03 +00001775 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001776 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Chengde17fb62009-10-31 23:46:45 +00001777 Br.MI->setDesc(TII->get(NewOpc));
1778 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001779 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001780 adjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001781 ++NumT2BrShrunk;
1782 MadeChange = true;
1783 }
1784 }
1785
1786 Opcode = Br.MI->getOpcode();
1787 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001788 continue;
1789
Evan Chengbfe8afa2012-01-14 01:53:46 +00001790 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1791 // so this transformation is not safe.
1792 if (!Br.MI->killsRegister(ARM::CPSR))
1793 continue;
1794
Evan Chengde17fb62009-10-31 23:46:45 +00001795 NewOpc = 0;
1796 unsigned PredReg = 0;
Craig Topperc89c7442012-03-27 07:21:54 +00001797 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
Evan Chengde17fb62009-10-31 23:46:45 +00001798 if (Pred == ARMCC::EQ)
1799 NewOpc = ARM::tCBZ;
1800 else if (Pred == ARMCC::NE)
1801 NewOpc = ARM::tCBNZ;
1802 if (!NewOpc)
1803 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001804 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001805 // Check if the distance is within 126. Subtract starting offset by 2
1806 // because the cmp will be eliminated.
Jim Grosbach7a465252012-03-23 23:07:03 +00001807 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001808 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001809 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001810 MachineBasicBlock::iterator CmpMI = Br.MI;
1811 if (CmpMI != Br.MI->getParent()->begin()) {
1812 --CmpMI;
1813 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1814 unsigned Reg = CmpMI->getOperand(0).getReg();
Craig Topperc89c7442012-03-27 07:21:54 +00001815 Pred = getInstrPredicate(CmpMI, PredReg);
Evan Cheng0539c152011-04-01 22:09:28 +00001816 if (Pred == ARMCC::AL &&
1817 CmpMI->getOperand(1).getImm() == 0 &&
1818 isARMLowRegister(Reg)) {
1819 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001820 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng0539c152011-04-01 22:09:28 +00001821 MachineInstr *NewBR =
1822 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1823 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1824 CmpMI->eraseFromParent();
1825 Br.MI->eraseFromParent();
1826 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001827 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001828 adjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001829 ++NumCBZ;
1830 MadeChange = true;
1831 }
Evan Chengde17fb62009-10-31 23:46:45 +00001832 }
1833 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001834 }
1835 }
1836
1837 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001838}
1839
Jim Grosbach7a465252012-03-23 23:07:03 +00001840/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chenga1efbbd2009-08-14 00:32:16 +00001841/// jumptables when it's possible.
Jim Grosbach7a465252012-03-23 23:07:03 +00001842bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Cheng5657c012009-07-29 02:18:14 +00001843 bool MadeChange = false;
1844
1845 // FIXME: After the tables are shrunk, can we get rid some of the
1846 // constantpool tables?
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001847 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001848 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001849
Evan Cheng5657c012009-07-29 02:18:14 +00001850 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1851 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1852 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001853 const MCInstrDesc &MCID = MI->getDesc();
1854 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001855 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001856 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1857 unsigned JTI = JTOP.getIndex();
1858 assert(JTI < JT.size());
1859
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001860 bool ByteOk = true;
1861 bool HalfWordOk = true;
Jim Grosbach7a465252012-03-23 23:07:03 +00001862 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach80697d12009-11-12 17:25:07 +00001863 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001864 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1865 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001866 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001867 // Negative offset is not ok. FIXME: We should change BB layout to make
1868 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001869 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001870 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001871 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001872 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001873 HalfWordOk = false;
1874 if (!ByteOk && !HalfWordOk)
1875 break;
1876 }
1877
1878 if (ByteOk || HalfWordOk) {
1879 MachineBasicBlock *MBB = MI->getParent();
1880 unsigned BaseReg = MI->getOperand(0).getReg();
1881 bool BaseRegKill = MI->getOperand(0).isKill();
1882 if (!BaseRegKill)
1883 continue;
1884 unsigned IdxReg = MI->getOperand(1).getReg();
1885 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001886
1887 // Scan backwards to find the instruction that defines the base
1888 // register. Due to post-RA scheduling, we can't count on it
1889 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001890 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001891 MachineBasicBlock::iterator B = MBB->begin();
1892 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1893 --PrevI;
1894
1895 // If for some reason we didn't find it, we can't do anything, so
1896 // just skip this one.
1897 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001898 continue;
1899
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001900 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001901 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001902 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001903 // Make sure it only defines the base register and kills any uses
1904 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001905 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1906 const MachineOperand &MO = AddrMI->getOperand(k);
1907 if (!MO.isReg() || !MO.getReg())
1908 continue;
1909 if (MO.isDef() && MO.getReg() != BaseReg) {
1910 OptOk = false;
1911 break;
1912 }
1913 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1914 OptOk = false;
1915 break;
1916 }
1917 }
1918 if (!OptOk)
1919 continue;
1920
Owen Anderson6b8719f2010-12-13 22:51:08 +00001921 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001922 // that gave us the initial base register definition.
1923 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1924 ;
1925
Owen Anderson6b8719f2010-12-13 22:51:08 +00001926 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001927 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001928 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001929 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001930 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001931 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001932 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001933
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001934 if (!OptOk)
1935 continue;
1936
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001937 DEBUG(dbgs() << "Shrink JT: " << *MI << " addr: " << *AddrMI
1938 << " lea: " << *LeaMI);
Jim Grosbachd092a872010-11-29 21:28:32 +00001939 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001940 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1941 .addReg(IdxReg, getKillRegState(IdxRegKill))
1942 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1943 .addImm(MI->getOperand(JTOpIdx+1).getImm());
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001944 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001945 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1946 // is 2-byte aligned. For now, asm printer will fix it up.
1947 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1948 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1949 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1950 OrigSize += TII->GetInstSizeInBytes(MI);
1951
1952 AddrMI->eraseFromParent();
1953 LeaMI->eraseFromParent();
1954 MI->eraseFromParent();
1955
1956 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001957 BBInfo[MBB->getNumber()].Size -= delta;
Jim Grosbach7a465252012-03-23 23:07:03 +00001958 adjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001959
1960 ++NumTBs;
1961 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001962 }
1963 }
1964
1965 return MadeChange;
1966}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001967
Jim Grosbach7a465252012-03-23 23:07:03 +00001968/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach9249efe2009-11-16 18:55:47 +00001969/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach7a465252012-03-23 23:07:03 +00001970bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach80697d12009-11-12 17:25:07 +00001971 bool MadeChange = false;
1972
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001973 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001974 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001975
Jim Grosbach80697d12009-11-12 17:25:07 +00001976 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1977 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1978 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001979 const MCInstrDesc &MCID = MI->getDesc();
1980 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001981 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001982 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1983 unsigned JTI = JTOP.getIndex();
1984 assert(JTI < JT.size());
1985
1986 // We prefer if target blocks for the jump table come after the jump
1987 // instruction so we can use TB[BH]. Loop through the target blocks
1988 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001989 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001990 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1991 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1992 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001993 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001994
Jim Grosbach08cbda52009-11-16 18:58:52 +00001995 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001996 // The destination precedes the switch. Try to move the block forward
1997 // so we have a positive offset.
1998 MachineBasicBlock *NewBB =
Jim Grosbach7a465252012-03-23 23:07:03 +00001999 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach80697d12009-11-12 17:25:07 +00002000 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002001 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00002002 MadeChange = true;
2003 }
2004 }
2005 }
2006
2007 return MadeChange;
2008}
2009
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002010MachineBasicBlock *ARMConstantIslands::
Jim Grosbach7a465252012-03-23 23:07:03 +00002011adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach03e2d442010-07-07 22:53:35 +00002012 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00002013 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00002014 // table that branches back to the actual target. This is a very simple
2015 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00002016 MachineBasicBlock *TBB = 0, *FBB = 0;
2017 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002018 SmallVector<MachineOperand, 4> CondPrior;
2019 MachineFunction::iterator BBi = BB;
2020 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002021
Jim Grosbachca215e72009-11-16 17:10:56 +00002022 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002023 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00002024
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002025 // If the block ends in an unconditional branch, move it. The prior block
2026 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00002027 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002028 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002029 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00002030 BB->moveAfter(JTBB);
2031 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002032 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00002033 // Update numbering to account for the block being moved.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002034 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00002035 ++NumJTMoved;
2036 return NULL;
2037 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002038
2039 // Create a new MBB for the code after the jump BB.
2040 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002041 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002042 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002043 MF->insert(MBBI, NewBB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002044
2045 // Add an unconditional branch from NewBB to BB.
2046 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2047 // correspond directly to anything in the source.
2048 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00002049 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2050 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002051
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002052 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002053 MF->RenumberBlocks(NewBB);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002054
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002055 // Update the CFG.
2056 NewBB->addSuccessor(BB);
2057 JTBB->removeSuccessor(BB);
2058 JTBB->addSuccessor(NewBB);
2059
Jim Grosbach80697d12009-11-12 17:25:07 +00002060 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002061 return NewBB;
2062}