blob: f5221f05e42f61800aed0bbbd7ebb3bd198cc6c6 [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
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000072/// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
73/// add padding such that:
74///
75/// 1. The result is aligned to 1 << LogAlign.
76///
77/// 2. No other value of the unknown bits would require more padding.
78///
79/// This may add more padding than is required to satisfy just one of the
80/// constraints. It is necessary to compute alignment this way to guarantee
81/// that we don't underestimate the padding before an aligned block. If the
82/// real padding before a block is larger than we think, constant pool entries
83/// may go out of range.
84static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
85 unsigned KnownBits) {
86 // Add the worst possible padding that the unknown bits could cause.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000087 Offset += UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000088
89 // Then align the result.
90 return RoundUpToAlignment(Offset, 1u << LogAlign);
91}
92
Evan Chenga8e29892007-01-19 07:51:42 +000093namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000094 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000095 /// requires constant pool entries to be scattered among the instructions
96 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000097 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000098 /// special instructions.
99 ///
100 /// The terminology used in this pass includes:
101 /// Islands - Clumps of constants placed in the function.
102 /// Water - Potential places where an island could be formed.
103 /// CPE - A constant pool entry that has been placed somewhere, which
104 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000105 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000106 /// BasicBlockInfo - Information about the offset and size of a single
107 /// basic block.
108 struct BasicBlockInfo {
109 /// Offset - Distance from the beginning of the function to the beginning
110 /// of this basic block.
111 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000112 /// The offset is always aligned as required by the basic block.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000113 unsigned Offset;
Bob Wilson84945262009-05-12 17:09:30 +0000114
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000115 /// Size - Size of the basic block in bytes. If the block contains
116 /// inline assembly, this is a worst case estimate.
117 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000118 /// The size does not include any alignment padding whether from the
119 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000120 unsigned Size;
121
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000122 /// KnownBits - The number of low bits in Offset that are known to be
123 /// exact. The remaining bits of Offset are an upper bound.
124 uint8_t KnownBits;
125
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000126 /// Unalign - When non-zero, the block contains instructions (inline asm)
127 /// of unknown size. The real size may be smaller than Size bytes by a
128 /// multiple of 1 << Unalign.
129 uint8_t Unalign;
130
131 /// PostAlign - When non-zero, the block terminator contains a .align
132 /// directive, so the end of the block is aligned to 1 << PostAlign
133 /// bytes.
134 uint8_t PostAlign;
135
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000136 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
137 PostAlign(0) {}
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000138
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000139 /// Compute the number of known offset bits internally to this block.
140 /// This number should be used to predict worst case padding when
141 /// splitting the block.
142 unsigned internalKnownBits() const {
143 return Unalign ? Unalign : KnownBits;
144 }
145
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000146 /// Compute the offset immediately following this block. If LogAlign is
147 /// specified, return the offset the successor block will get if it has
148 /// this alignment.
149 unsigned postOffset(unsigned LogAlign = 0) const {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000150 unsigned PO = Offset + Size;
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000151 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
152 if (!LA)
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000153 return PO;
154 // Add alignment padding from the terminator.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000155 return WorstCaseAlign(PO, LA, internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000156 }
157
158 /// Compute the number of known low bits of postOffset. If this block
159 /// contains inline asm, the number of known bits drops to the
160 /// instruction alignment. An aligned terminator may increase the number
161 /// of know bits.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000162 /// If LogAlign is given, also consider the alignment of the next block.
163 unsigned postKnownBits(unsigned LogAlign = 0) const {
164 return std::max(std::max(unsigned(PostAlign), LogAlign),
165 internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000166 }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000167 };
168
169 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000170
Evan Chenga8e29892007-01-19 07:51:42 +0000171 /// WaterList - A sorted list of basic blocks where islands could be placed
172 /// (i.e. blocks that don't fall through to the following block, due
173 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +0000174 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +0000175
Bob Wilsonb9239532009-10-15 20:49:47 +0000176 /// NewWaterList - The subset of WaterList that was created since the
177 /// previous iteration by inserting unconditional branches.
178 SmallSet<MachineBasicBlock*, 4> NewWaterList;
179
Bob Wilson034de5f2009-10-12 18:52:13 +0000180 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
181
Evan Chenga8e29892007-01-19 07:51:42 +0000182 /// CPUser - One user of a constant pool, keeping the machine instruction
183 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000184 /// allowed from the instruction to the CP. The HighWaterMark records the
185 /// highest basic block where a new CPEntry can be placed. To ensure this
186 /// pass terminates, the CP entries are initially placed at the end of the
187 /// function and then move monotonically to lower addresses. The
188 /// exception to this rule is when the current CP entry for a particular
189 /// CPUser is out of range, but there is another CP entry for the same
190 /// constant value in range. We want to use the existing in-range CP
191 /// entry, but if it later moves out of range, the search for new water
192 /// should resume where it left off. The HighWaterMark is used to record
193 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000194 struct CPUser {
195 MachineInstr *MI;
196 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000197 MachineBasicBlock *HighWaterMark;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000198 private:
Evan Chenga8e29892007-01-19 07:51:42 +0000199 unsigned MaxDisp;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000200 public:
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000201 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000202 bool IsSoImm;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000203 bool KnownAlignment;
Evan Chengd3d9d662009-07-23 18:27:47 +0000204 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
205 bool neg, bool soimm)
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000206 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
207 KnownAlignment(false) {
Bob Wilson549dda92009-10-15 05:52:29 +0000208 HighWaterMark = CPEMI->getParent();
209 }
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000210 /// getMaxDisp - Returns the maximum displacement supported by MI.
211 /// Correct for unknown alignment.
212 unsigned getMaxDisp() const {
213 return KnownAlignment ? MaxDisp : MaxDisp - 2;
214 }
Evan Chenga8e29892007-01-19 07:51:42 +0000215 };
Bob Wilson84945262009-05-12 17:09:30 +0000216
Evan Chenga8e29892007-01-19 07:51:42 +0000217 /// CPUsers - Keep track of all of the machine instructions that use various
218 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000219 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000220
Evan Chengc99ef082007-02-09 20:54:44 +0000221 /// CPEntry - One per constant pool entry, keeping the machine instruction
222 /// pointer, the constpool index, and the number of CPUser's which
223 /// reference this entry.
224 struct CPEntry {
225 MachineInstr *CPEMI;
226 unsigned CPI;
227 unsigned RefCount;
228 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
229 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
230 };
231
232 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000233 /// instructions. For each original constpool index (i.e. those that
234 /// existed upon entry to this pass), it keeps a vector of entries.
235 /// Original elements are cloned as we go along; the clones are
236 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000237 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000238
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000239 /// ImmBranch - One per immediate branch, keeping the machine instruction
240 /// pointer, conditional or unconditional, the max displacement,
241 /// and (if isCond is true) the corresponding unconditional branch
242 /// opcode.
243 struct ImmBranch {
244 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000245 unsigned MaxDisp : 31;
246 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000247 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000248 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
249 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000250 };
251
Evan Cheng2706f972007-05-16 05:14:06 +0000252 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000253 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000254 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000255
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000256 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
257 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000258 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000259
Evan Cheng5657c012009-07-29 02:18:14 +0000260 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
261 SmallVector<MachineInstr*, 4> T2JumpTables;
262
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000263 /// HasFarJump - True if any far jump instruction has been emitted during
264 /// the branch fix up pass.
265 bool HasFarJump;
266
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000267 MachineFunction *MF;
268 MachineConstantPool *MCP;
Craig Topperacf20772012-03-25 23:49:58 +0000269 const ARMBaseInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000270 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000271 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000272 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000273 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000274 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000275 public:
Devang Patel19974732007-05-03 01:11:54 +0000276 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000277 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000278
Evan Cheng5657c012009-07-29 02:18:14 +0000279 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000280
281 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000282 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000283 }
Bob Wilson84945262009-05-12 17:09:30 +0000284
Evan Chenga8e29892007-01-19 07:51:42 +0000285 private:
Jim Grosbach7a465252012-03-23 23:07:03 +0000286 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000287 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000288 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach7a465252012-03-23 23:07:03 +0000289 void scanFunctionJumpTables();
290 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
291 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
292 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
293 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
294 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
295 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
296 bool findAvailableWater(CPUser&U, unsigned UserOffset,
297 water_iterator &WaterIter);
298 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000299 MachineBasicBlock *&NewMBB);
Jim Grosbach7a465252012-03-23 23:07:03 +0000300 bool handleConstantPoolUser(unsigned CPUserIndex);
301 void removeDeadCPEMI(MachineInstr *CPEMI);
302 bool removeUnusedCPEntries();
303 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
304 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
305 bool DoDump = false);
306 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000307 CPUser &U, unsigned &Growth);
Jim Grosbach7a465252012-03-23 23:07:03 +0000308 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
309 bool fixupImmediateBr(ImmBranch &Br);
310 bool fixupConditionalBr(ImmBranch &Br);
311 bool fixupUnconditionalBr(ImmBranch &Br);
312 bool undoLRSpillRestore();
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +0000313 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
Jim Grosbach7a465252012-03-23 23:07:03 +0000314 bool optimizeThumb2Instructions();
315 bool optimizeThumb2Branches();
316 bool reorderThumb2JumpTables();
317 bool optimizeThumb2JumpTables();
318 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000319 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000320
Jim Grosbach7a465252012-03-23 23:07:03 +0000321 void computeBlockSize(MachineBasicBlock *MBB);
322 unsigned getOffsetOf(MachineInstr *MI) const;
323 unsigned getUserOffset(CPUser&) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000324 void dumpBBs();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000325 void verify();
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000326
Jim Grosbach7a465252012-03-23 23:07:03 +0000327 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000328 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach7a465252012-03-23 23:07:03 +0000329 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000330 const CPUser &U) {
Jim Grosbach7a465252012-03-23 23:07:03 +0000331 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000332 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000333 }
Evan Chenga8e29892007-01-19 07:51:42 +0000334 };
Devang Patel19974732007-05-03 01:11:54 +0000335 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000336}
337
Dale Johannesen8593e412007-04-29 19:19:30 +0000338/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000339void ARMConstantIslands::verify() {
Evan Chengd3d9d662009-07-23 18:27:47 +0000340#ifndef NDEBUG
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000341 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000342 MBBI != E; ++MBBI) {
343 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000344 unsigned Align = MBB->getAlignment();
345 unsigned MBBId = MBB->getNumber();
346 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
347 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000348 }
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +0000349 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000350 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
351 CPUser &U = CPUsers[i];
Jim Grosbach7a465252012-03-23 23:07:03 +0000352 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +0000353 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp(), U.NegOk,
354 /* DoDump = */ true)) {
355 DEBUG(dbgs() << "OK\n");
356 continue;
357 }
358 DEBUG(dbgs() << "Out of range.\n");
359 dumpBBs();
360 DEBUG(MF->dump());
361 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000362 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000363#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000364}
365
366/// print block size and offset information - debugging
367void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000368 DEBUG({
369 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
370 const BasicBlockInfo &BBI = BBInfo[J];
371 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
372 << " kb=" << unsigned(BBI.KnownBits)
373 << " ua=" << unsigned(BBI.Unalign)
374 << " pa=" << unsigned(BBI.PostAlign)
375 << format(" size=%#x\n", BBInfo[J].Size);
376 }
377 });
Dale Johannesen8593e412007-04-29 19:19:30 +0000378}
379
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000380/// createARMConstantIslandPass - returns an instance of the constpool
381/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000382FunctionPass *llvm::createARMConstantIslandPass() {
383 return new ARMConstantIslands();
384}
385
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000386bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
387 MF = &mf;
388 MCP = mf.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000389
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000390 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000391 << MCP->getConstants().size() << " CP entries, aligned to "
392 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000393
Craig Topperacf20772012-03-25 23:49:58 +0000394 TII = (const ARMBaseInstrInfo*)MF->getTarget().getInstrInfo();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000395 AFI = MF->getInfo<ARMFunctionInfo>();
396 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000397
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000398 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000399 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000400 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000401
402 HasFarJump = false;
403
Jakob Stoklund Olesen7a4c0712012-03-29 23:14:26 +0000404 // This pass invalidates liveness information when it splits basic blocks.
405 MF->getRegInfo().invalidateLiveness();
406
Evan Chenga8e29892007-01-19 07:51:42 +0000407 // Renumber all of the machine basic blocks in the function, guaranteeing that
408 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000409 MF->RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000410
Jim Grosbach80697d12009-11-12 17:25:07 +0000411 // Try to reorder and otherwise adjust the block layout to make good use
412 // of the TB[BH] instructions.
413 bool MadeChange = false;
414 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach7a465252012-03-23 23:07:03 +0000415 scanFunctionJumpTables();
416 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach80697d12009-11-12 17:25:07 +0000417 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000418 T2JumpTables.clear();
419 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000420 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +0000421 }
422
Evan Chengd26b14c2009-07-31 18:28:05 +0000423 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000424 // This is so we can keep exact track of where the alignment padding goes.
425
Chris Lattner7d7dab02010-01-27 23:37:36 +0000426 // ARM and Thumb2 functions need to be 4-byte aligned.
427 if (!isThumb1)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000428 MF->EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000429
Evan Chenga8e29892007-01-19 07:51:42 +0000430 // Perform the initial placement of the constant pool entries. To start with,
431 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000432 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000433 if (!MCP->isEmpty())
Jim Grosbach7a465252012-03-23 23:07:03 +0000434 doInitialPlacement(CPEMIs);
Bob Wilson84945262009-05-12 17:09:30 +0000435
Evan Chenga8e29892007-01-19 07:51:42 +0000436 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000437 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000438
Evan Chenga8e29892007-01-19 07:51:42 +0000439 // Do the initial scan of the function, building up information about the
440 // sizes of each block, the location of all the water, and finding all of the
441 // constant pool users.
Jim Grosbach7a465252012-03-23 23:07:03 +0000442 initializeFunctionInfo(CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000443 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000444 DEBUG(dumpBBs());
445
Bob Wilson84945262009-05-12 17:09:30 +0000446
Evan Chenged884f32007-04-03 23:39:48 +0000447 /// Remove dead constant pool entries.
Jim Grosbach7a465252012-03-23 23:07:03 +0000448 MadeChange |= removeUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000449
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000450 // Iteratively place constant pool entries and fix up branches until there
451 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000452 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000453 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000454 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000455 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000456 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jim Grosbach7a465252012-03-23 23:07:03 +0000457 CPChange |= handleConstantPoolUser(i);
Evan Chengb6879b22009-08-07 07:35:21 +0000458 if (CPChange && ++NoCPIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000459 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000460 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000461
Bob Wilsonb9239532009-10-15 20:49:47 +0000462 // Clear NewWaterList now. If we split a block for branches, it should
463 // appear as "new water" for the next iteration of constant pool placement.
464 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000465
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000466 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000467 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000468 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach7a465252012-03-23 23:07:03 +0000469 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Chengb6879b22009-08-07 07:35:21 +0000470 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000471 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000472 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000473
474 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000475 break;
476 MadeChange = true;
477 }
Evan Chenged884f32007-04-03 23:39:48 +0000478
Evan Chenga1efbbd2009-08-14 00:32:16 +0000479 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000480 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach7a465252012-03-23 23:07:03 +0000481 MadeChange |= optimizeThumb2Instructions();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000482
Dale Johannesen8593e412007-04-29 19:19:30 +0000483 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000484 verify();
Dale Johannesen8593e412007-04-29 19:19:30 +0000485
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000486 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
487 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000488 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach7a465252012-03-23 23:07:03 +0000489 MadeChange |= undoLRSpillRestore();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000490
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000491 // Save the mapping between original and cloned constpool entries.
492 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
493 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
494 const CPEntry & CPE = CPEntries[i][j];
495 AFI->recordCPEClone(i, CPE.CPI);
496 }
497 }
498
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000499 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000500
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000501 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000502 WaterList.clear();
503 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000504 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000505 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000506 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000507 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000508
509 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000510}
511
Jim Grosbach7a465252012-03-23 23:07:03 +0000512/// doInitialPlacement - Perform the initial placement of the constant pool
Evan Chenga8e29892007-01-19 07:51:42 +0000513/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000514void
Jim Grosbach7a465252012-03-23 23:07:03 +0000515ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000516 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000517 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
518 MF->push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000519
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000520 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000521 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000522
523 // Mark the basic block as required by the const-pool.
524 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
525 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
526
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000527 // The function needs to be as aligned as the basic blocks. The linker may
528 // move functions around based on their alignment.
529 MF->EnsureAlignment(BB->getAlignment());
530
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000531 // Order the entries in BB by descending alignment. That ensures correct
532 // alignment of all entries as long as BB is sufficiently aligned. Keep
533 // track of the insertion point for each alignment. We are going to bucket
534 // sort the entries as they are created.
535 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000536
Evan Chenga8e29892007-01-19 07:51:42 +0000537 // Add all of the constants from the constant pool to the end block, use an
538 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000539 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000540
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000541 const TargetData &TD = *MF->getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000542 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000543 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000544 assert(Size >= 4 && "Too small constant pool entry");
545 unsigned Align = CPs[i].getAlignment();
546 assert(isPowerOf2_32(Align) && "Invalid alignment");
547 // Verify that all constant pool entries are a multiple of their alignment.
548 // If not, we would have to pad them out so that instructions stay aligned.
549 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
550
551 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
552 unsigned LogAlign = Log2_32(Align);
553 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Chenga8e29892007-01-19 07:51:42 +0000554 MachineInstr *CPEMI =
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000555 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000556 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000557 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000558
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000559 // Ensure that future entries with higher alignment get inserted before
560 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesenb076fb72011-12-16 23:00:05 +0000561 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000562 if (InsPoint[a] == InsAt)
563 InsPoint[a] = CPEMI;
564
Evan Chengc99ef082007-02-09 20:54:44 +0000565 // Add a new CPEntry, but no corresponding CPUser yet.
566 std::vector<CPEntry> CPEs;
567 CPEs.push_back(CPEntry(CPEMI, i));
568 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000569 ++NumCPEs;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000570 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
571 << Size << ", align = " << Align <<'\n');
Evan Chenga8e29892007-01-19 07:51:42 +0000572 }
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000573 DEBUG(BB->dump());
Evan Chenga8e29892007-01-19 07:51:42 +0000574}
575
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000576/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000577/// into the block immediately after it.
578static bool BBHasFallthrough(MachineBasicBlock *MBB) {
579 // Get the next machine basic block in the function.
580 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000581 // Can't fall off end of function.
582 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000583 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000584
Chris Lattner7896c9f2009-12-03 00:50:42 +0000585 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000586 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
587 E = MBB->succ_end(); I != E; ++I)
588 if (*I == NextBB)
589 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000590
Evan Chenga8e29892007-01-19 07:51:42 +0000591 return false;
592}
593
Evan Chengc99ef082007-02-09 20:54:44 +0000594/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
595/// look up the corresponding CPEntry.
596ARMConstantIslands::CPEntry
597*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
598 const MachineInstr *CPEMI) {
599 std::vector<CPEntry> &CPEs = CPEntries[CPI];
600 // Number of entries per constpool index should be small, just do a
601 // linear search.
602 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
603 if (CPEs[i].CPEMI == CPEMI)
604 return &CPEs[i];
605 }
606 return NULL;
607}
608
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000609/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesenbd1ec172011-12-12 19:25:51 +0000610/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000611unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
612 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
613
614 // Everything is 4-byte aligned unless AlignConstantIslands is set.
615 if (!AlignConstantIslands)
616 return 2;
617
618 unsigned CPI = CPEMI->getOperand(1).getIndex();
619 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
620 unsigned Align = MCP->getConstants()[CPI].getAlignment();
621 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
622 return Log2_32(Align);
623}
624
Jim Grosbach7a465252012-03-23 23:07:03 +0000625/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach80697d12009-11-12 17:25:07 +0000626/// information about the sizes of each block and the locations of all
627/// the jump tables.
Jim Grosbach7a465252012-03-23 23:07:03 +0000628void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000629 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach80697d12009-11-12 17:25:07 +0000630 MBBI != E; ++MBBI) {
631 MachineBasicBlock &MBB = *MBBI;
632
Jim Grosbach80697d12009-11-12 17:25:07 +0000633 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000634 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000635 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000636 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000637 }
638}
639
Jim Grosbach7a465252012-03-23 23:07:03 +0000640/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Chenga8e29892007-01-19 07:51:42 +0000641/// information about the sizes of each block, the location of all the water,
642/// and finding all of the constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000643void ARMConstantIslands::
Jim Grosbach7a465252012-03-23 23:07:03 +0000644initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000645 BBInfo.clear();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000646 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000647
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000648 // First thing, compute the size of all basic blocks, and see if the function
649 // has any inline assembly in it. If so, we have to be conservative about
650 // alignment assumptions, as we don't know for sure the size of any
651 // instructions in the inline assembly.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000652 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jim Grosbach7a465252012-03-23 23:07:03 +0000653 computeBlockSize(I);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000654
655 // The known bits of the entry block offset are determined by the function
656 // alignment.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000657 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000658
659 // Compute block offsets and known bits.
Jim Grosbach7a465252012-03-23 23:07:03 +0000660 adjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000661
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000662 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000663 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chenga8e29892007-01-19 07:51:42 +0000664 MBBI != E; ++MBBI) {
665 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000666
Evan Chenga8e29892007-01-19 07:51:42 +0000667 // If this block doesn't fall through into the next MBB, then this is
668 // 'water' that a constant pool island could be placed.
669 if (!BBHasFallthrough(&MBB))
670 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000671
Evan Chenga8e29892007-01-19 07:51:42 +0000672 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
673 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000674 if (I->isDebugValue())
675 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000676
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000677 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000678 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000679 bool isCond = false;
680 unsigned Bits = 0;
681 unsigned Scale = 1;
682 int UOpc = Opc;
683 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000684 default:
685 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000686 case ARM::t2BR_JT:
687 T2JumpTables.push_back(I);
688 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000689 case ARM::Bcc:
690 isCond = true;
691 UOpc = ARM::B;
692 // Fallthrough
693 case ARM::B:
694 Bits = 24;
695 Scale = 4;
696 break;
697 case ARM::tBcc:
698 isCond = true;
699 UOpc = ARM::tB;
700 Bits = 8;
701 Scale = 2;
702 break;
703 case ARM::tB:
704 Bits = 11;
705 Scale = 2;
706 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000707 case ARM::t2Bcc:
708 isCond = true;
709 UOpc = ARM::t2B;
710 Bits = 20;
711 Scale = 2;
712 break;
713 case ARM::t2B:
714 Bits = 24;
715 Scale = 2;
716 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000717 }
Evan Chengb43216e2007-02-01 10:16:15 +0000718
719 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000720 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000721 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000722 }
723
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000724 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
725 PushPopMIs.push_back(I);
726
Evan Chengd3d9d662009-07-23 18:27:47 +0000727 if (Opc == ARM::CONSTPOOL_ENTRY)
728 continue;
729
Evan Chenga8e29892007-01-19 07:51:42 +0000730 // Scan the instructions for constant pool operands.
731 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000732 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000733 // We found one. The addressing mode tells us the max displacement
734 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000735
Evan Chenga8e29892007-01-19 07:51:42 +0000736 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000737 unsigned Bits = 0;
738 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000739 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000740 bool IsSoImm = false;
741
742 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000743 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000744 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000745
746 // Taking the address of a CP entry.
747 case ARM::LEApcrel:
748 // This takes a SoImm, which is 8 bit immediate rotated. We'll
749 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000750 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000751 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000752 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000753 Scale = 4;
754 NegOk = true;
755 IsSoImm = true;
756 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000757 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000758 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000759 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000760 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000761 case ARM::tLEApcrel:
762 Bits = 8;
763 Scale = 4;
764 break;
765
Jim Grosbach3e556122010-10-26 22:37:02 +0000766 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000767 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000768 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000769 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000770 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000771 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000772
773 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000774 Bits = 8;
775 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000776 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000777
Jim Grosbache5165492009-11-09 00:11:35 +0000778 case ARM::VLDRD:
779 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000780 Bits = 8;
781 Scale = 4; // +-(offset_8*4)
782 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000783 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000784 }
Evan Chengb43216e2007-02-01 10:16:15 +0000785
Evan Chenga8e29892007-01-19 07:51:42 +0000786 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000787 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000788 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000789 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000790 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000791
792 // Increment corresponding CPEntry reference count.
793 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
794 assert(CPE && "Cannot find a corresponding CPEntry!");
795 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000796
Evan Chenga8e29892007-01-19 07:51:42 +0000797 // Instructions can only use one CP entry, don't bother scanning the
798 // rest of the operands.
799 break;
800 }
801 }
Evan Chenga8e29892007-01-19 07:51:42 +0000802 }
803}
804
Jim Grosbach7a465252012-03-23 23:07:03 +0000805/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000806/// This function updates BBInfo directly.
Jim Grosbach7a465252012-03-23 23:07:03 +0000807void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000808 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
809 BBI.Size = 0;
810 BBI.Unalign = 0;
811 BBI.PostAlign = 0;
812
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000813 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
814 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000815 BBI.Size += TII->GetInstSizeInBytes(I);
816 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
817 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000818 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000819 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +0000820 // Also consider instructions that may be shrunk later.
821 else if (isThumb && mayOptimizeThumb2Instruction(I))
822 BBI.Unalign = 1;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000823 }
824
825 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000826 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000827 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000828 MBB->getParent()->EnsureAlignment(2);
829 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000830}
831
Jim Grosbach7a465252012-03-23 23:07:03 +0000832/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Chenga8e29892007-01-19 07:51:42 +0000833/// from the start of the function. This offset changes as stuff is moved
834/// around inside the function.
Jim Grosbach7a465252012-03-23 23:07:03 +0000835unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Chenga8e29892007-01-19 07:51:42 +0000836 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000837
Evan Chenga8e29892007-01-19 07:51:42 +0000838 // The offset is composed of two things: the sum of the sizes of all MBB's
839 // before this instruction's block, and the offset from the start of the block
840 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000841 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000842
843 // Sum instructions before MI in MBB.
Jim Grosbach0c3cfef2012-01-31 20:56:55 +0000844 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Chenga8e29892007-01-19 07:51:42 +0000845 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000846 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000847 }
Jim Grosbach0c3cfef2012-01-31 20:56:55 +0000848 return Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000849}
850
851/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
852/// ID.
853static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
854 const MachineBasicBlock *RHS) {
855 return LHS->getNumber() < RHS->getNumber();
856}
857
Jim Grosbach7a465252012-03-23 23:07:03 +0000858/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Chenga8e29892007-01-19 07:51:42 +0000859/// machine function, it upsets all of the block numbers. Renumber the blocks
860/// and update the arrays that parallel this numbering.
Jim Grosbach7a465252012-03-23 23:07:03 +0000861void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000862 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000863 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000864
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000865 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000866 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000867 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000868
869 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000870 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000871 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000872 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
873 CompareMBBNumbers);
874 WaterList.insert(IP, NewBB);
875}
876
877
878/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000879/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000880/// account for this change and returns the newly created block.
Jim Grosbach7a465252012-03-23 23:07:03 +0000881MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000882 MachineBasicBlock *OrigBB = MI->getParent();
883
884 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000885 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000886 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000887 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000888 MF->insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000889
Evan Chenga8e29892007-01-19 07:51:42 +0000890 // Splice the instructions starting with MI over to NewBB.
891 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000892
Evan Chenga8e29892007-01-19 07:51:42 +0000893 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000894 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000895 // There doesn't seem to be meaningful DebugInfo available; this doesn't
896 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000897 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000898 if (!isThumb)
899 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
900 else
901 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
902 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000903 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000904
Evan Chenga8e29892007-01-19 07:51:42 +0000905 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000906 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000907
Evan Chenga8e29892007-01-19 07:51:42 +0000908 // OrigBB branches to NewBB.
909 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000910
Evan Chenga8e29892007-01-19 07:51:42 +0000911 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach7a465252012-03-23 23:07:03 +0000912 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000913 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000914 MF->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000915
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000916 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000917 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000918 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000919
Bob Wilson84945262009-05-12 17:09:30 +0000920 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000921 // available water after it (but not if it's already there, which happens
922 // when splitting before a conditional branch that is followed by an
923 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000924 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000925 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
926 CompareMBBNumbers);
927 MachineBasicBlock* WaterBB = *IP;
928 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000929 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000930 else
931 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000932 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000933
Dale Johannesen8086d582010-07-23 22:50:23 +0000934 // Figure out how large the OrigBB is. As the first half of the original
935 // block, it cannot contain a tablejump. The size includes
936 // the new jump we added. (It should be possible to do this without
937 // recounting everything, but it's very confusing, and this is rarely
938 // executed.)
Jim Grosbach7a465252012-03-23 23:07:03 +0000939 computeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000940
Dale Johannesen8086d582010-07-23 22:50:23 +0000941 // Figure out how large the NewMBB is. As the second half of the original
942 // block, it may contain a tablejump.
Jim Grosbach7a465252012-03-23 23:07:03 +0000943 computeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000944
Dale Johannesen99c49a42007-02-25 00:47:03 +0000945 // All BBOffsets following these blocks must be modified.
Jim Grosbach7a465252012-03-23 23:07:03 +0000946 adjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000947
948 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000949}
950
Jim Grosbach7a465252012-03-23 23:07:03 +0000951/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000952/// displacement computation. Update U.KnownAlignment to match its current
953/// basic block location.
Jim Grosbach7a465252012-03-23 23:07:03 +0000954unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
955 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000956 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
957 unsigned KnownBits = BBI.internalKnownBits();
958
959 // The value read from PC is offset from the actual instruction address.
960 UserOffset += (isThumb ? 4 : 8);
961
962 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
963 // Make sure U.getMaxDisp() returns a constrained range.
964 U.KnownAlignment = (KnownBits >= 2);
965
966 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
967 // purposes of the displacement computation; compensate for that here.
968 // For unknown alignments, getMaxDisp() constrains the range instead.
969 if (isThumb && U.KnownAlignment)
970 UserOffset &= ~3u;
971
972 return UserOffset;
973}
974
Jim Grosbach7a465252012-03-23 23:07:03 +0000975/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000976/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000977/// constant pool entry).
Jim Grosbach7a465252012-03-23 23:07:03 +0000978/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +0000979/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
980/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach7a465252012-03-23 23:07:03 +0000981bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000982 unsigned TrialOffset, unsigned MaxDisp,
983 bool NegativeOK, bool IsSoImm) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000984 if (UserOffset <= TrialOffset) {
985 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000986 if (TrialOffset - UserOffset <= MaxDisp)
987 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000988 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000989 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000990 if (UserOffset - TrialOffset <= MaxDisp)
991 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000992 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000993 }
994 return false;
995}
996
Jim Grosbach7a465252012-03-23 23:07:03 +0000997/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000998/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000999///
1000/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach7a465252012-03-23 23:07:03 +00001001bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001002 MachineBasicBlock* Water, CPUser &U,
1003 unsigned &Growth) {
1004 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1005 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1006 unsigned NextBlockOffset, NextBlockAlignment;
1007 MachineFunction::const_iterator NextBlock = Water;
1008 if (++NextBlock == MF->end()) {
1009 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1010 NextBlockAlignment = 0;
1011 } else {
1012 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1013 NextBlockAlignment = NextBlock->getAlignment();
1014 }
1015 unsigned Size = U.CPEMI->getOperand(2).getImm();
1016 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001017
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001018 // The CPE may be able to hide in the alignment padding before the next
1019 // block. It may also cause more padding to be required if it is more aligned
1020 // that the next block.
1021 if (CPEEnd > NextBlockOffset) {
1022 Growth = CPEEnd - NextBlockOffset;
1023 // Compute the padding that would go at the end of the CPE to align the next
1024 // block.
1025 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1026
1027 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach7a465252012-03-23 23:07:03 +00001028 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001029 // in blocks between CPE and the user.
1030 if (CPEOffset < UserOffset)
1031 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1032 } else
1033 // CPE fits in existing padding.
1034 Growth = 0;
Dale Johannesend959aa42007-04-02 20:31:06 +00001035
Jim Grosbach7a465252012-03-23 23:07:03 +00001036 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001037}
1038
Jim Grosbach7a465252012-03-23 23:07:03 +00001039/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +00001040/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001041bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001042 MachineInstr *CPEMI, unsigned MaxDisp,
1043 bool NegOk, bool DoDump) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001044 unsigned CPEOffset = getOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +00001045 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +00001046
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001047 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001048 DEBUG({
1049 unsigned Block = MI->getParent()->getNumber();
1050 const BasicBlockInfo &BBI = BBInfo[Block];
1051 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1052 << " max delta=" << MaxDisp
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001053 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001054 << " in BB#" << Block << ": "
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001055 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1056 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1057 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001058 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001059 }
Evan Chengc0dbec72007-01-31 19:57:44 +00001060
Jim Grosbach7a465252012-03-23 23:07:03 +00001061 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +00001062}
1063
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001064#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001065/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1066/// unconditionally branches to its only successor.
1067static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1068 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1069 return false;
1070
1071 MachineBasicBlock *Succ = *MBB->succ_begin();
1072 MachineBasicBlock *Pred = *MBB->pred_begin();
1073 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001074 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1075 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +00001076 return PredMI->getOperand(0).getMBB() == Succ;
1077 return false;
1078}
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001079#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001080
Jim Grosbach7a465252012-03-23 23:07:03 +00001081void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001082 unsigned BBNum = BB->getNumber();
1083 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001084 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +00001085 // Include the alignment of the current block.
1086 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1087 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1088 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001089
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001090 // This is where block i begins. Stop if the offset is already correct,
1091 // and we have updated 2 blocks. This is the maximum number of blocks
1092 // changed before calling this function.
1093 if (i > BBNum + 2 &&
1094 BBInfo[i].Offset == Offset &&
1095 BBInfo[i].KnownBits == KnownBits)
1096 break;
1097
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001098 BBInfo[i].Offset = Offset;
1099 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +00001100 }
Dale Johannesen99c49a42007-02-25 00:47:03 +00001101}
1102
Jim Grosbach7a465252012-03-23 23:07:03 +00001103/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001104/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +00001105/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001106/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +00001107
Jim Grosbach7a465252012-03-23 23:07:03 +00001108bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1109 MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +00001110 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +00001111 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1112 assert(CPE && "Unexpected!");
1113 if (--CPE->RefCount == 0) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001114 removeDeadCPEMI(CPEMI);
Evan Chenged884f32007-04-03 23:39:48 +00001115 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +00001116 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001117 return true;
1118 }
1119 return false;
1120}
1121
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001122/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1123/// if not, see if an in-range clone of the CPE is in range, and if so,
1124/// change the data structures so the user references the clone. Returns:
1125/// 0 = no existing entry found
1126/// 1 = entry found, and there were no code insertions or deletions
1127/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach7a465252012-03-23 23:07:03 +00001128int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001129{
1130 MachineInstr *UserMI = U.MI;
1131 MachineInstr *CPEMI = U.CPEMI;
1132
1133 // Check to see if the CPE is already in-range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001134 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1135 true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001136 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001137 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001138 }
1139
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001140 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001141 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001142 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1143 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1144 // We already tried this one
1145 if (CPEs[i].CPEMI == CPEMI)
1146 continue;
1147 // Removing CPEs can leave empty entries, skip
1148 if (CPEs[i].CPEMI == NULL)
1149 continue;
Jim Grosbach7a465252012-03-23 23:07:03 +00001150 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001151 U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001152 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001153 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001154 // Point the CPUser node to the replacement
1155 U.CPEMI = CPEs[i].CPEMI;
1156 // Change the CPI in the instruction operand to refer to the clone.
1157 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001158 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001159 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001160 break;
1161 }
1162 // Adjust the refcount of the clone...
1163 CPEs[i].RefCount++;
1164 // ...and the original. If we didn't remove the old entry, none of the
1165 // addresses changed, so we don't need another pass.
Jim Grosbach7a465252012-03-23 23:07:03 +00001166 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001167 }
1168 }
1169 return 0;
1170}
1171
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001172/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1173/// the specific unconditional branch instruction.
1174static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001175 switch (Opc) {
1176 case ARM::tB:
1177 return ((1<<10)-1)*2;
1178 case ARM::t2B:
1179 return ((1<<23)-1)*2;
1180 default:
1181 break;
1182 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001183
David Goodwin5e47a9a2009-06-30 18:04:13 +00001184 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001185}
1186
Jim Grosbach7a465252012-03-23 23:07:03 +00001187/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001188/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001189/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001190/// is set to the WaterList entry. For Thumb, prefer water that will not
1191/// introduce padding to water that will. To ensure that this pass
1192/// terminates, the CPE location for a particular CPUser is only allowed to
1193/// move to a lower address, so search backward from the end of the list and
1194/// prefer the first water that is in range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001195bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001196 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001197 if (WaterList.empty())
1198 return false;
1199
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001200 unsigned BestGrowth = ~0u;
1201 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1202 --IP) {
Bob Wilson3b757352009-10-12 19:04:03 +00001203 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001204 // Check if water is in range and is either at a lower address than the
1205 // current "high water mark" or a new water block that was created since
1206 // the previous iteration by inserting an unconditional branch. In the
1207 // latter case, we want to allow resetting the high water mark back to
1208 // this new water since we haven't seen it before. Inserting branches
1209 // should be relatively uncommon and when it does happen, we want to be
1210 // sure to take advantage of it for all the CPEs near that block, so that
1211 // we don't insert more branches than necessary.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001212 unsigned Growth;
Jim Grosbach7a465252012-03-23 23:07:03 +00001213 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilsonb9239532009-10-15 20:49:47 +00001214 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001215 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1216 // This is the least amount of required padding seen so far.
1217 BestGrowth = Growth;
1218 WaterIter = IP;
1219 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1220 << " Growth=" << Growth << '\n');
1221
1222 // Keep looking unless it is perfect.
1223 if (BestGrowth == 0)
Bob Wilson3b757352009-10-12 19:04:03 +00001224 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001225 }
Bob Wilson3b757352009-10-12 19:04:03 +00001226 if (IP == B)
1227 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001228 }
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001229 return BestGrowth != ~0u;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001230}
1231
Jim Grosbach7a465252012-03-23 23:07:03 +00001232/// createNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001233/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1234/// block is used if in range, and the conditional branch munged so control
1235/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001236/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001237/// block following which the new island can be inserted (the WaterList
1238/// is not adjusted).
Jim Grosbach7a465252012-03-23 23:07:03 +00001239void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001240 unsigned UserOffset,
1241 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001242 CPUser &U = CPUsers[CPUserIndex];
1243 MachineInstr *UserMI = U.MI;
1244 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001245 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001246 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001247 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001248
Bob Wilson36fa5322009-10-15 05:10:36 +00001249 // If the block does not end in an unconditional branch already, and if the
1250 // end of the block is within range, make new water there. (The addition
1251 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001252 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001253 if (BBHasFallthrough(UserMBB)) {
1254 // Size of branch to insert.
1255 unsigned Delta = isThumb1 ? 2 : 4;
1256 // End of UserBlock after adding a branch.
1257 unsigned UserBlockEnd = UserBBI.postOffset() + Delta;
1258 // Compute the offset where the CPE will begin.
1259 unsigned CPEOffset = WorstCaseAlign(UserBlockEnd, CPELogAlign,
1260 UserBBI.postKnownBits());
Dale Johannesen8593e412007-04-29 19:19:30 +00001261
Jim Grosbach7a465252012-03-23 23:07:03 +00001262 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001263 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1264 << format(", expected CPE offset %#x\n", CPEOffset));
1265 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1266 // Add an unconditional branch from UserMBB to fallthrough block. Record
1267 // it for branch lengthening; this new branch will not get out of range,
1268 // but if the preceding conditional branch is out of range, the targets
1269 // will be exchanged, and the altered branch may be out of range, so the
1270 // machinery has to know about it.
1271 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1272 if (!isThumb)
1273 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1274 else
1275 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1276 .addImm(ARMCC::AL).addReg(0);
1277 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1278 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1279 MaxDisp, false, UncondBr));
1280 BBInfo[UserMBB->getNumber()].Size += Delta;
Jim Grosbach7a465252012-03-23 23:07:03 +00001281 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001282 return;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001283 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001284 }
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001285
1286 // What a big block. Find a place within the block to split it. This is a
1287 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1288 // entries are 4 bytes: if instruction I references island CPE, and
1289 // instruction I+1 references CPE', it will not work well to put CPE as far
1290 // forward as possible, since then CPE' cannot immediately follow it (that
1291 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1292 // need to create a new island. So, we make a first guess, then walk through
1293 // the instructions between the one currently being looked at and the
1294 // possible insertion point, and make sure any other instructions that
1295 // reference CPEs will be able to use the same island area; if not, we back
1296 // up the insertion point.
1297
1298 // Try to split the block so it's fully aligned. Compute the latest split
1299 // point where we can add a 4-byte branch instruction, and then
1300 // WorstCaseAlign to LogAlign.
1301 unsigned LogAlign = MF->getAlignment();
1302 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1303 unsigned KnownBits = UserBBI.internalKnownBits();
1304 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001305 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001306 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1307 BaseInsertOffset));
1308
1309 // Account for alignment and unknown padding.
1310 BaseInsertOffset &= ~((1u << LogAlign) - 1);
1311 BaseInsertOffset -= UPad;
1312
1313 // The 4 in the following is for the unconditional branch we'll be inserting
1314 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach7a465252012-03-23 23:07:03 +00001315 // inside isOffsetInRange.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001316 BaseInsertOffset -= 4;
1317
1318 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1319 << " la=" << LogAlign
1320 << " kb=" << KnownBits
1321 << " up=" << UPad << '\n');
1322
1323 // This could point off the end of the block if we've already got constant
1324 // pool entries following this block; only the last one is in the water list.
1325 // Back past any possible branches (allow for a conditional and a maximally
1326 // long unconditional).
1327 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1328 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1329 (isThumb1 ? 6 : 8);
1330 unsigned EndInsertOffset =
1331 WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1332 CPEMI->getOperand(2).getImm();
1333 MachineBasicBlock::iterator MI = UserMI;
1334 ++MI;
1335 unsigned CPUIndex = CPUserIndex+1;
1336 unsigned NumCPUsers = CPUsers.size();
1337 MachineInstr *LastIT = 0;
1338 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1339 Offset < BaseInsertOffset;
1340 Offset += TII->GetInstSizeInBytes(MI),
1341 MI = llvm::next(MI)) {
1342 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1343 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach7a465252012-03-23 23:07:03 +00001344 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001345 // Shift intertion point by one unit of alignment so it is within reach.
1346 BaseInsertOffset -= 1u << LogAlign;
1347 EndInsertOffset -= 1u << LogAlign;
1348 }
1349 // This is overly conservative, as we don't account for CPEMIs being
1350 // reused within the block, but it doesn't matter much. Also assume CPEs
1351 // are added in order with alignment padding. We may eventually be able
1352 // to pack the aligned CPEs better.
1353 EndInsertOffset = RoundUpToAlignment(EndInsertOffset,
1354 1u << getCPELogAlign(U.CPEMI)) +
1355 U.CPEMI->getOperand(2).getImm();
1356 CPUIndex++;
1357 }
1358
1359 // Remember the last IT instruction.
1360 if (MI->getOpcode() == ARM::t2IT)
1361 LastIT = MI;
1362 }
1363
1364 --MI;
1365
1366 // Avoid splitting an IT block.
1367 if (LastIT) {
1368 unsigned PredReg = 0;
Craig Topperc89c7442012-03-27 07:21:54 +00001369 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001370 if (CC != ARMCC::AL)
1371 MI = LastIT;
1372 }
Jim Grosbach7a465252012-03-23 23:07:03 +00001373 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001374}
1375
Jim Grosbach7a465252012-03-23 23:07:03 +00001376/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001377/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001378/// place in-range. Return true if we changed any addresses (thus must run
1379/// another pass of branch lengthening), false otherwise.
Jim Grosbach7a465252012-03-23 23:07:03 +00001380bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001381 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001382 MachineInstr *UserMI = U.MI;
1383 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001384 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001385 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001386 // Compute this only once, it's expensive.
Jim Grosbach7a465252012-03-23 23:07:03 +00001387 unsigned UserOffset = getUserOffset(U);
Evan Cheng768c9f72007-04-27 08:14:15 +00001388
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001389 // See if the current entry is within range, or there is a clone of it
1390 // in range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001391 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001392 if (result==1) return false;
1393 else if (result==2) return true;
1394
1395 // No existing clone of this CPE is within range.
1396 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001397 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001398
Bob Wilsonf98032e2009-10-12 21:23:15 +00001399 // Look for water where we can place this CPE.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001400 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilsonb9239532009-10-15 20:49:47 +00001401 MachineBasicBlock *NewMBB;
1402 water_iterator IP;
Jim Grosbach7a465252012-03-23 23:07:03 +00001403 if (findAvailableWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001404 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001405 MachineBasicBlock *WaterBB = *IP;
1406
1407 // If the original WaterList entry was "new water" on this iteration,
1408 // propagate that to the new island. This is just keeping NewWaterList
1409 // updated to match the WaterList, which will be updated below.
1410 if (NewWaterList.count(WaterBB)) {
1411 NewWaterList.erase(WaterBB);
1412 NewWaterList.insert(NewIsland);
1413 }
1414 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001415 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001416
1417 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001418 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001419 DEBUG(dbgs() << "No water found\n");
Jim Grosbach7a465252012-03-23 23:07:03 +00001420 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001421
Jim Grosbach7a465252012-03-23 23:07:03 +00001422 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilsonb9239532009-10-15 20:49:47 +00001423 // called while handling branches so that the water will be seen on the
1424 // next iteration for constant pools, but in this context, we don't want
1425 // it. Check for this so it will be removed from the WaterList.
1426 // Also remove any entry from NewWaterList.
1427 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1428 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1429 if (IP != WaterList.end())
1430 NewWaterList.erase(WaterBB);
1431
1432 // We are adding new water. Update NewWaterList.
1433 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001434 }
1435
Bob Wilsonb9239532009-10-15 20:49:47 +00001436 // Remove the original WaterList entry; we want subsequent insertions in
1437 // this vicinity to go after the one we're about to insert. This
1438 // considerably reduces the number of times we have to move the same CPE
1439 // more than once and is also important to ensure the algorithm terminates.
1440 if (IP != WaterList.end())
1441 WaterList.erase(IP);
1442
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001443 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001444 MF->insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001445
1446 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach7a465252012-03-23 23:07:03 +00001447 updateForInsertedWaterBlock(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001448
1449 // Decrement the old entry, and remove it if refcount becomes 0.
Jim Grosbach7a465252012-03-23 23:07:03 +00001450 decrementCPEReferenceCount(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001451
1452 // Now that we have an island to add the CPE to, clone the original CPE and
1453 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001454 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001455 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001456 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001457 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001458 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001459
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001460 // Mark the basic block as aligned as required by the const-pool entry.
1461 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001462
Evan Chenga8e29892007-01-19 07:51:42 +00001463 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001464 BBInfo[NewIsland->getNumber()].Size += Size;
Jim Grosbach7a465252012-03-23 23:07:03 +00001465 adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001466
Evan Chenga8e29892007-01-19 07:51:42 +00001467 // Finally, change the CPI in the instruction operand to be ID.
1468 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001469 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001470 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001471 break;
1472 }
Bob Wilson84945262009-05-12 17:09:30 +00001473
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001474 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001475 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson84945262009-05-12 17:09:30 +00001476
Evan Chenga8e29892007-01-19 07:51:42 +00001477 return true;
1478}
1479
Jim Grosbach7a465252012-03-23 23:07:03 +00001480/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Chenged884f32007-04-03 23:39:48 +00001481/// sizes and offsets of impacted basic blocks.
Jim Grosbach7a465252012-03-23 23:07:03 +00001482void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Chenged884f32007-04-03 23:39:48 +00001483 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001484 unsigned Size = CPEMI->getOperand(2).getImm();
1485 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001486 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001487 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001488 if (CPEBB->empty()) {
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001489 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001490
1491 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1492 CPEBB->setAlignment(0);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001493 } else
1494 // Entries are sorted by descending alignment, so realign from the front.
1495 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1496
Jim Grosbach7a465252012-03-23 23:07:03 +00001497 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001498 // An island has only one predecessor BB and one successor BB. Check if
1499 // this BB's predecessor jumps directly to this BB's successor. This
1500 // shouldn't happen currently.
1501 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1502 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001503}
1504
Jim Grosbach7a465252012-03-23 23:07:03 +00001505/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Chenged884f32007-04-03 23:39:48 +00001506/// are zero.
Jim Grosbach7a465252012-03-23 23:07:03 +00001507bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Chenged884f32007-04-03 23:39:48 +00001508 unsigned MadeChange = false;
1509 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1510 std::vector<CPEntry> &CPEs = CPEntries[i];
1511 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1512 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001513 removeDeadCPEMI(CPEs[j].CPEMI);
Evan Chenged884f32007-04-03 23:39:48 +00001514 CPEs[j].CPEMI = NULL;
1515 MadeChange = true;
1516 }
1517 }
Bob Wilson84945262009-05-12 17:09:30 +00001518 }
Evan Chenged884f32007-04-03 23:39:48 +00001519 return MadeChange;
1520}
1521
Jim Grosbach7a465252012-03-23 23:07:03 +00001522/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001523/// specific BB can fit in MI's displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001524bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Chengc0dbec72007-01-31 19:57:44 +00001525 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001526 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach7a465252012-03-23 23:07:03 +00001527 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001528 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001529
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001530 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001531 << " from BB#" << MI->getParent()->getNumber()
1532 << " max delta=" << MaxDisp
Jim Grosbach7a465252012-03-23 23:07:03 +00001533 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattner705e07f2009-08-23 03:41:05 +00001534 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001535
Dale Johannesen8593e412007-04-29 19:19:30 +00001536 if (BrOffset <= DestOffset) {
1537 // Branch before the Dest.
1538 if (DestOffset-BrOffset <= MaxDisp)
1539 return true;
1540 } else {
1541 if (BrOffset-DestOffset <= MaxDisp)
1542 return true;
1543 }
1544 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001545}
1546
Jim Grosbach7a465252012-03-23 23:07:03 +00001547/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001548/// away to fit in its displacement field.
Jim Grosbach7a465252012-03-23 23:07:03 +00001549bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001550 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001551 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001552
Evan Chengc0dbec72007-01-31 19:57:44 +00001553 // Check to see if the DestBB is already in-range.
Jim Grosbach7a465252012-03-23 23:07:03 +00001554 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001555 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001556
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001557 if (!Br.isCond)
Jim Grosbach7a465252012-03-23 23:07:03 +00001558 return fixupUnconditionalBr(Br);
1559 return fixupConditionalBr(Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001560}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001561
Jim Grosbach7a465252012-03-23 23:07:03 +00001562/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001563/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001564/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001565/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001566bool
Jim Grosbach7a465252012-03-23 23:07:03 +00001567ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001568 MachineInstr *MI = Br.MI;
1569 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001570 if (!isThumb1)
Jim Grosbach7a465252012-03-23 23:07:03 +00001571 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001572
1573 // Use BL to implement far jump.
1574 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001575 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001576 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001577 adjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001578 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001579 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001580
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001581 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001582
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001583 return true;
1584}
1585
Jim Grosbach7a465252012-03-23 23:07:03 +00001586/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001587/// far away to fit in its displacement field. It is converted to an inverse
1588/// conditional branch + an unconditional branch to the destination.
1589bool
Jim Grosbach7a465252012-03-23 23:07:03 +00001590ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001591 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001592 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001593
Bob Wilson39bf0512009-05-12 17:35:29 +00001594 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001595 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001596 // blt L1
1597 // =>
1598 // bge L2
1599 // b L1
1600 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001601 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001602 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001603 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001604
1605 // If the branch is at the end of its MBB and that has a fall-through block,
1606 // direct the updated conditional branch to the fall-through block. Otherwise,
1607 // split the MBB before the next instruction.
1608 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001609 MachineInstr *BMI = &MBB->back();
1610 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001611
Dan Gohmanfe601042010-06-22 15:08:57 +00001612 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001613 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001614 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001615 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001616 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001617 // condition and swap destinations:
1618 // beq L1
1619 // b L2
1620 // =>
1621 // bne L2
1622 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001623 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach7a465252012-03-23 23:07:03 +00001624 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001625 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001626 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001627 BMI->getOperand(0).setMBB(DestBB);
1628 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001629 MI->getOperand(1).setImm(CC);
1630 return true;
1631 }
1632 }
1633 }
1634
1635 if (NeedSplit) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001636 splitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001637 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001638 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001639 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001640 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001641 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001642 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001643 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001644 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001645
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001646 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001647 << " also invert condition and change dest. to BB#"
1648 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001649
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001650 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001651 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001652 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001653 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001654 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001655 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001656 if (isThumb)
1657 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1658 .addImm(ARMCC::AL).addReg(0);
1659 else
1660 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001661 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001662 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001663 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001664
1665 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001666 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001667 MI->eraseFromParent();
Jim Grosbach7a465252012-03-23 23:07:03 +00001668 adjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001669 return true;
1670}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001671
Jim Grosbach7a465252012-03-23 23:07:03 +00001672/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001673/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1674/// to do this if tBfar is not used.
Jim Grosbach7a465252012-03-23 23:07:03 +00001675bool ARMConstantIslands::undoLRSpillRestore() {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001676 bool MadeChange = false;
1677 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1678 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001679 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001680 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001681 MI->getOperand(2).getReg() == ARM::PC &&
1682 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001683 // Create the new insn and copy the predicate from the old.
1684 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1685 .addOperand(MI->getOperand(0))
1686 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001687 MI->eraseFromParent();
1688 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001689 }
1690 }
1691 return MadeChange;
1692}
Evan Cheng5657c012009-07-29 02:18:14 +00001693
Jim Grosbach7a465252012-03-23 23:07:03 +00001694// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001695// below may shrink MI.
1696bool
1697ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1698 switch(MI->getOpcode()) {
Jim Grosbach7a465252012-03-23 23:07:03 +00001699 // optimizeThumb2Instructions.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001700 case ARM::t2LEApcrel:
1701 case ARM::t2LDRpci:
Jim Grosbach7a465252012-03-23 23:07:03 +00001702 // optimizeThumb2Branches.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001703 case ARM::t2B:
1704 case ARM::t2Bcc:
1705 case ARM::tBcc:
Jim Grosbach7a465252012-03-23 23:07:03 +00001706 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen19d0bf32012-01-10 22:32:14 +00001707 case ARM::t2BR_JT:
1708 return true;
1709 }
1710 return false;
1711}
1712
Jim Grosbach7a465252012-03-23 23:07:03 +00001713bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chenga1efbbd2009-08-14 00:32:16 +00001714 bool MadeChange = false;
1715
1716 // Shrink ADR and LDR from constantpool.
1717 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1718 CPUser &U = CPUsers[i];
1719 unsigned Opcode = U.MI->getOpcode();
1720 unsigned NewOpc = 0;
1721 unsigned Scale = 1;
1722 unsigned Bits = 0;
1723 switch (Opcode) {
1724 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001725 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001726 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1727 NewOpc = ARM::tLEApcrel;
1728 Bits = 8;
1729 Scale = 4;
1730 }
1731 break;
1732 case ARM::t2LDRpci:
1733 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1734 NewOpc = ARM::tLDRpci;
1735 Bits = 8;
1736 Scale = 4;
1737 }
1738 break;
1739 }
1740
1741 if (!NewOpc)
1742 continue;
1743
Jim Grosbach7a465252012-03-23 23:07:03 +00001744 unsigned UserOffset = getUserOffset(U);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001745 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesendae412b2012-01-10 01:34:59 +00001746
1747 // Be conservative with inline asm.
1748 if (!U.KnownAlignment)
1749 MaxOffs -= 2;
1750
Evan Chenga1efbbd2009-08-14 00:32:16 +00001751 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach7a465252012-03-23 23:07:03 +00001752 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001753 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001754 U.MI->setDesc(TII->get(NewOpc));
1755 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001756 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001757 adjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001758 ++NumT2CPShrunk;
1759 MadeChange = true;
1760 }
1761 }
1762
Jim Grosbach7a465252012-03-23 23:07:03 +00001763 MadeChange |= optimizeThumb2Branches();
1764 MadeChange |= optimizeThumb2JumpTables();
Evan Chenga1efbbd2009-08-14 00:32:16 +00001765 return MadeChange;
1766}
1767
Jim Grosbach7a465252012-03-23 23:07:03 +00001768bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001769 bool MadeChange = false;
1770
1771 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1772 ImmBranch &Br = ImmBranches[i];
1773 unsigned Opcode = Br.MI->getOpcode();
1774 unsigned NewOpc = 0;
1775 unsigned Scale = 1;
1776 unsigned Bits = 0;
1777 switch (Opcode) {
1778 default: break;
1779 case ARM::t2B:
1780 NewOpc = ARM::tB;
1781 Bits = 11;
1782 Scale = 2;
1783 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001784 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001785 NewOpc = ARM::tBcc;
1786 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001787 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001788 break;
1789 }
Evan Chengde17fb62009-10-31 23:46:45 +00001790 }
1791 if (NewOpc) {
1792 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1793 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach7a465252012-03-23 23:07:03 +00001794 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001795 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Chengde17fb62009-10-31 23:46:45 +00001796 Br.MI->setDesc(TII->get(NewOpc));
1797 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001798 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001799 adjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001800 ++NumT2BrShrunk;
1801 MadeChange = true;
1802 }
1803 }
1804
1805 Opcode = Br.MI->getOpcode();
1806 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001807 continue;
1808
Evan Chengbfe8afa2012-01-14 01:53:46 +00001809 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1810 // so this transformation is not safe.
1811 if (!Br.MI->killsRegister(ARM::CPSR))
1812 continue;
1813
Evan Chengde17fb62009-10-31 23:46:45 +00001814 NewOpc = 0;
1815 unsigned PredReg = 0;
Craig Topperc89c7442012-03-27 07:21:54 +00001816 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
Evan Chengde17fb62009-10-31 23:46:45 +00001817 if (Pred == ARMCC::EQ)
1818 NewOpc = ARM::tCBZ;
1819 else if (Pred == ARMCC::NE)
1820 NewOpc = ARM::tCBNZ;
1821 if (!NewOpc)
1822 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001823 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001824 // Check if the distance is within 126. Subtract starting offset by 2
1825 // because the cmp will be eliminated.
Jim Grosbach7a465252012-03-23 23:07:03 +00001826 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001827 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001828 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001829 MachineBasicBlock::iterator CmpMI = Br.MI;
1830 if (CmpMI != Br.MI->getParent()->begin()) {
1831 --CmpMI;
1832 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1833 unsigned Reg = CmpMI->getOperand(0).getReg();
Craig Topperc89c7442012-03-27 07:21:54 +00001834 Pred = getInstrPredicate(CmpMI, PredReg);
Evan Cheng0539c152011-04-01 22:09:28 +00001835 if (Pred == ARMCC::AL &&
1836 CmpMI->getOperand(1).getImm() == 0 &&
1837 isARMLowRegister(Reg)) {
1838 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001839 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng0539c152011-04-01 22:09:28 +00001840 MachineInstr *NewBR =
1841 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1842 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1843 CmpMI->eraseFromParent();
1844 Br.MI->eraseFromParent();
1845 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001846 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach7a465252012-03-23 23:07:03 +00001847 adjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001848 ++NumCBZ;
1849 MadeChange = true;
1850 }
Evan Chengde17fb62009-10-31 23:46:45 +00001851 }
1852 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001853 }
1854 }
1855
1856 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001857}
1858
Jim Grosbach7a465252012-03-23 23:07:03 +00001859/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chenga1efbbd2009-08-14 00:32:16 +00001860/// jumptables when it's possible.
Jim Grosbach7a465252012-03-23 23:07:03 +00001861bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Cheng5657c012009-07-29 02:18:14 +00001862 bool MadeChange = false;
1863
1864 // FIXME: After the tables are shrunk, can we get rid some of the
1865 // constantpool tables?
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001866 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001867 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001868
Evan Cheng5657c012009-07-29 02:18:14 +00001869 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1870 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1871 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001872 const MCInstrDesc &MCID = MI->getDesc();
1873 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001874 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001875 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1876 unsigned JTI = JTOP.getIndex();
1877 assert(JTI < JT.size());
1878
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001879 bool ByteOk = true;
1880 bool HalfWordOk = true;
Jim Grosbach7a465252012-03-23 23:07:03 +00001881 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach80697d12009-11-12 17:25:07 +00001882 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001883 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1884 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001885 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001886 // Negative offset is not ok. FIXME: We should change BB layout to make
1887 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001888 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001889 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001890 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001891 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001892 HalfWordOk = false;
1893 if (!ByteOk && !HalfWordOk)
1894 break;
1895 }
1896
1897 if (ByteOk || HalfWordOk) {
1898 MachineBasicBlock *MBB = MI->getParent();
1899 unsigned BaseReg = MI->getOperand(0).getReg();
1900 bool BaseRegKill = MI->getOperand(0).isKill();
1901 if (!BaseRegKill)
1902 continue;
1903 unsigned IdxReg = MI->getOperand(1).getReg();
1904 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001905
1906 // Scan backwards to find the instruction that defines the base
1907 // register. Due to post-RA scheduling, we can't count on it
1908 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001909 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001910 MachineBasicBlock::iterator B = MBB->begin();
1911 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1912 --PrevI;
1913
1914 // If for some reason we didn't find it, we can't do anything, so
1915 // just skip this one.
1916 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001917 continue;
1918
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001919 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001920 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001921 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001922 // Make sure it only defines the base register and kills any uses
1923 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001924 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1925 const MachineOperand &MO = AddrMI->getOperand(k);
1926 if (!MO.isReg() || !MO.getReg())
1927 continue;
1928 if (MO.isDef() && MO.getReg() != BaseReg) {
1929 OptOk = false;
1930 break;
1931 }
1932 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1933 OptOk = false;
1934 break;
1935 }
1936 }
1937 if (!OptOk)
1938 continue;
1939
Owen Anderson6b8719f2010-12-13 22:51:08 +00001940 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001941 // that gave us the initial base register definition.
1942 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1943 ;
1944
Owen Anderson6b8719f2010-12-13 22:51:08 +00001945 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001946 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001947 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001948 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001949 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001950 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001951 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001952
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001953 if (!OptOk)
1954 continue;
1955
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001956 DEBUG(dbgs() << "Shrink JT: " << *MI << " addr: " << *AddrMI
1957 << " lea: " << *LeaMI);
Jim Grosbachd092a872010-11-29 21:28:32 +00001958 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001959 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1960 .addReg(IdxReg, getKillRegState(IdxRegKill))
1961 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1962 .addImm(MI->getOperand(JTOpIdx+1).getImm());
Jakob Stoklund Olesen101c03a2012-03-31 00:06:42 +00001963 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001964 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1965 // is 2-byte aligned. For now, asm printer will fix it up.
1966 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1967 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1968 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1969 OrigSize += TII->GetInstSizeInBytes(MI);
1970
1971 AddrMI->eraseFromParent();
1972 LeaMI->eraseFromParent();
1973 MI->eraseFromParent();
1974
1975 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001976 BBInfo[MBB->getNumber()].Size -= delta;
Jim Grosbach7a465252012-03-23 23:07:03 +00001977 adjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001978
1979 ++NumTBs;
1980 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001981 }
1982 }
1983
1984 return MadeChange;
1985}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001986
Jim Grosbach7a465252012-03-23 23:07:03 +00001987/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach9249efe2009-11-16 18:55:47 +00001988/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach7a465252012-03-23 23:07:03 +00001989bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach80697d12009-11-12 17:25:07 +00001990 bool MadeChange = false;
1991
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001992 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001993 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001994
Jim Grosbach80697d12009-11-12 17:25:07 +00001995 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1996 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1997 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001998 const MCInstrDesc &MCID = MI->getDesc();
1999 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00002000 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00002001 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2002 unsigned JTI = JTOP.getIndex();
2003 assert(JTI < JT.size());
2004
2005 // We prefer if target blocks for the jump table come after the jump
2006 // instruction so we can use TB[BH]. Loop through the target blocks
2007 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00002008 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00002009 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2010 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2011 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00002012 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00002013
Jim Grosbach08cbda52009-11-16 18:58:52 +00002014 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00002015 // The destination precedes the switch. Try to move the block forward
2016 // so we have a positive offset.
2017 MachineBasicBlock *NewBB =
Jim Grosbach7a465252012-03-23 23:07:03 +00002018 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach80697d12009-11-12 17:25:07 +00002019 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002020 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00002021 MadeChange = true;
2022 }
2023 }
2024 }
2025
2026 return MadeChange;
2027}
2028
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002029MachineBasicBlock *ARMConstantIslands::
Jim Grosbach7a465252012-03-23 23:07:03 +00002030adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach03e2d442010-07-07 22:53:35 +00002031 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00002032 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00002033 // table that branches back to the actual target. This is a very simple
2034 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00002035 MachineBasicBlock *TBB = 0, *FBB = 0;
2036 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002037 SmallVector<MachineOperand, 4> CondPrior;
2038 MachineFunction::iterator BBi = BB;
2039 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002040
Jim Grosbachca215e72009-11-16 17:10:56 +00002041 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002042 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00002043
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002044 // If the block ends in an unconditional branch, move it. The prior block
2045 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00002046 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002047 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbacha0a95a32009-11-17 01:21:04 +00002048 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00002049 BB->moveAfter(JTBB);
2050 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002051 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00002052 // Update numbering to account for the block being moved.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002053 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00002054 ++NumJTMoved;
2055 return NULL;
2056 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002057
2058 // Create a new MBB for the code after the jump BB.
2059 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002060 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002061 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002062 MF->insert(MBBI, NewBB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002063
2064 // Add an unconditional branch from NewBB to BB.
2065 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2066 // correspond directly to anything in the source.
2067 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00002068 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2069 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002070
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002071 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00002072 MF->RenumberBlocks(NewBB);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00002073
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002074 // Update the CFG.
2075 NewBB->addSuccessor(BB);
2076 JTBB->removeSuccessor(BB);
2077 JTBB->addSuccessor(NewBB);
2078
Jim Grosbach80697d12009-11-12 17:25:07 +00002079 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002080 return NewBB;
2081}