blob: 55a0cc0f44444da983e0d03c924667533b35cbe8 [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 Chenga8e29892007-01-19 07:51:42 +000019#include "ARMInstrInfo.h"
Evan Cheng719510a2010-08-12 20:30:05 +000020#include "Thumb2InstrInfo.h"
Evan Chengee04a6d2011-07-20 23:34:39 +000021#include "MCTargetDesc/ARMAddressingModes.h"
Evan Chenga8e29892007-01-19 07:51:42 +000022#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.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 Olesen77caaf02011-12-10 02:55:10 +000055/// UnknownPadding - Return the worst case padding that could result from
56/// unknown offset bits. This does not include alignment padding caused by
57/// known offset bits.
58///
59/// @param LogAlign log2(alignment)
60/// @param KnownBits Number of known low offset bits.
61static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
62 if (KnownBits < LogAlign)
63 return (1u << LogAlign) - (1u << KnownBits);
64 return 0;
65}
66
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000067/// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
68/// add padding such that:
69///
70/// 1. The result is aligned to 1 << LogAlign.
71///
72/// 2. No other value of the unknown bits would require more padding.
73///
74/// This may add more padding than is required to satisfy just one of the
75/// constraints. It is necessary to compute alignment this way to guarantee
76/// that we don't underestimate the padding before an aligned block. If the
77/// real padding before a block is larger than we think, constant pool entries
78/// may go out of range.
79static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
80 unsigned KnownBits) {
81 // Add the worst possible padding that the unknown bits could cause.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000082 Offset += UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000083
84 // Then align the result.
85 return RoundUpToAlignment(Offset, 1u << LogAlign);
86}
87
Evan Chenga8e29892007-01-19 07:51:42 +000088namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000089 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000090 /// requires constant pool entries to be scattered among the instructions
91 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000092 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000093 /// special instructions.
94 ///
95 /// The terminology used in this pass includes:
96 /// Islands - Clumps of constants placed in the function.
97 /// Water - Potential places where an island could be formed.
98 /// CPE - A constant pool entry that has been placed somewhere, which
99 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000100 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000101 /// BasicBlockInfo - Information about the offset and size of a single
102 /// basic block.
103 struct BasicBlockInfo {
104 /// Offset - Distance from the beginning of the function to the beginning
105 /// of this basic block.
106 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000107 /// The offset is always aligned as required by the basic block.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000108 unsigned Offset;
Bob Wilson84945262009-05-12 17:09:30 +0000109
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000110 /// Size - Size of the basic block in bytes. If the block contains
111 /// inline assembly, this is a worst case estimate.
112 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000113 /// The size does not include any alignment padding whether from the
114 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000115 unsigned Size;
116
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000117 /// KnownBits - The number of low bits in Offset that are known to be
118 /// exact. The remaining bits of Offset are an upper bound.
119 uint8_t KnownBits;
120
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000121 /// Unalign - When non-zero, the block contains instructions (inline asm)
122 /// of unknown size. The real size may be smaller than Size bytes by a
123 /// multiple of 1 << Unalign.
124 uint8_t Unalign;
125
126 /// PostAlign - When non-zero, the block terminator contains a .align
127 /// directive, so the end of the block is aligned to 1 << PostAlign
128 /// bytes.
129 uint8_t PostAlign;
130
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000131 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
132 PostAlign(0) {}
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000133
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000134 /// Compute the number of known offset bits internally to this block.
135 /// This number should be used to predict worst case padding when
136 /// splitting the block.
137 unsigned internalKnownBits() const {
138 return Unalign ? Unalign : KnownBits;
139 }
140
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000141 /// Compute the offset immediately following this block.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000142 unsigned postOffset() const {
143 unsigned PO = Offset + Size;
144 if (!PostAlign)
145 return PO;
146 // Add alignment padding from the terminator.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000147 return WorstCaseAlign(PO, PostAlign, internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000148 }
149
150 /// Compute the number of known low bits of postOffset. If this block
151 /// contains inline asm, the number of known bits drops to the
152 /// instruction alignment. An aligned terminator may increase the number
153 /// of know bits.
154 unsigned postKnownBits() const {
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000155 return std::max(unsigned(PostAlign), internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000156 }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000157 };
158
159 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000160
Evan Chenga8e29892007-01-19 07:51:42 +0000161 /// WaterList - A sorted list of basic blocks where islands could be placed
162 /// (i.e. blocks that don't fall through to the following block, due
163 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +0000164 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +0000165
Bob Wilsonb9239532009-10-15 20:49:47 +0000166 /// NewWaterList - The subset of WaterList that was created since the
167 /// previous iteration by inserting unconditional branches.
168 SmallSet<MachineBasicBlock*, 4> NewWaterList;
169
Bob Wilson034de5f2009-10-12 18:52:13 +0000170 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
171
Evan Chenga8e29892007-01-19 07:51:42 +0000172 /// CPUser - One user of a constant pool, keeping the machine instruction
173 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000174 /// allowed from the instruction to the CP. The HighWaterMark records the
175 /// highest basic block where a new CPEntry can be placed. To ensure this
176 /// pass terminates, the CP entries are initially placed at the end of the
177 /// function and then move monotonically to lower addresses. The
178 /// exception to this rule is when the current CP entry for a particular
179 /// CPUser is out of range, but there is another CP entry for the same
180 /// constant value in range. We want to use the existing in-range CP
181 /// entry, but if it later moves out of range, the search for new water
182 /// should resume where it left off. The HighWaterMark is used to record
183 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000184 struct CPUser {
185 MachineInstr *MI;
186 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000187 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000188 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000189 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000190 bool IsSoImm;
191 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
192 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000193 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
194 HighWaterMark = CPEMI->getParent();
195 }
Evan Chenga8e29892007-01-19 07:51:42 +0000196 };
Bob Wilson84945262009-05-12 17:09:30 +0000197
Evan Chenga8e29892007-01-19 07:51:42 +0000198 /// CPUsers - Keep track of all of the machine instructions that use various
199 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000200 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000201
Evan Chengc99ef082007-02-09 20:54:44 +0000202 /// CPEntry - One per constant pool entry, keeping the machine instruction
203 /// pointer, the constpool index, and the number of CPUser's which
204 /// reference this entry.
205 struct CPEntry {
206 MachineInstr *CPEMI;
207 unsigned CPI;
208 unsigned RefCount;
209 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
210 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
211 };
212
213 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000214 /// instructions. For each original constpool index (i.e. those that
215 /// existed upon entry to this pass), it keeps a vector of entries.
216 /// Original elements are cloned as we go along; the clones are
217 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000218 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000219
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000220 /// ImmBranch - One per immediate branch, keeping the machine instruction
221 /// pointer, conditional or unconditional, the max displacement,
222 /// and (if isCond is true) the corresponding unconditional branch
223 /// opcode.
224 struct ImmBranch {
225 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000226 unsigned MaxDisp : 31;
227 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000228 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000229 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
230 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000231 };
232
Evan Cheng2706f972007-05-16 05:14:06 +0000233 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000234 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000235 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000236
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000237 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
238 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000239 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000240
Evan Cheng5657c012009-07-29 02:18:14 +0000241 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
242 SmallVector<MachineInstr*, 4> T2JumpTables;
243
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000244 /// HasFarJump - True if any far jump instruction has been emitted during
245 /// the branch fix up pass.
246 bool HasFarJump;
247
Chris Lattner20628752010-07-22 21:27:00 +0000248 const ARMInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000249 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000250 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000251 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000252 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000253 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000254 public:
Devang Patel19974732007-05-03 01:11:54 +0000255 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000256 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000257
Evan Cheng5657c012009-07-29 02:18:14 +0000258 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000259
260 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000261 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000262 }
Bob Wilson84945262009-05-12 17:09:30 +0000263
Evan Chenga8e29892007-01-19 07:51:42 +0000264 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000265 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000266 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000267 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jim Grosbach80697d12009-11-12 17:25:07 +0000268 void JumpTableFunctionScan(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000269 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000270 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000271 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000272 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000273 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
Evan Chenged884f32007-04-03 23:39:48 +0000274 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000275 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000276 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000277 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000278 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000279 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000280 void RemoveDeadCPEMI(MachineInstr *CPEMI);
281 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000282 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000283 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
284 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000285 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000286 CPUser &U);
Evan Chengc0dbec72007-01-31 19:57:44 +0000287 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000288 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
289 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
290 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000291 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000292 bool OptimizeThumb2Instructions(MachineFunction &MF);
293 bool OptimizeThumb2Branches(MachineFunction &MF);
Jim Grosbach80697d12009-11-12 17:25:07 +0000294 bool ReorderThumb2JumpTables(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000295 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000296 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
297 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000298
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000299 void ComputeBlockSize(MachineBasicBlock *MBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000300 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000301 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000302 void verify(MachineFunction &MF);
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000303
304 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
305 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
306 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
307 const CPUser &U) {
308 return OffsetIsInRange(UserOffset, TrialOffset,
309 U.MaxDisp, U.NegOk, U.IsSoImm);
310 }
Evan Chenga8e29892007-01-19 07:51:42 +0000311 };
Devang Patel19974732007-05-03 01:11:54 +0000312 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000313}
314
Dale Johannesen8593e412007-04-29 19:19:30 +0000315/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000316void ARMConstantIslands::verify(MachineFunction &MF) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000317#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000318 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000319 MBBI != E; ++MBBI) {
320 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000321 unsigned Align = MBB->getAlignment();
322 unsigned MBBId = MBB->getNumber();
323 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
324 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000325 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000326 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
327 CPUser &U = CPUsers[i];
328 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000329 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
330 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
331 UserOffset - CPEOffset;
332 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000333 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000334#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000335}
336
337/// print block size and offset information - debugging
338void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000339 DEBUG({
340 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
341 const BasicBlockInfo &BBI = BBInfo[J];
342 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
343 << " kb=" << unsigned(BBI.KnownBits)
344 << " ua=" << unsigned(BBI.Unalign)
345 << " pa=" << unsigned(BBI.PostAlign)
346 << format(" size=%#x\n", BBInfo[J].Size);
347 }
348 });
Dale Johannesen8593e412007-04-29 19:19:30 +0000349}
350
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000351/// createARMConstantIslandPass - returns an instance of the constpool
352/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000353FunctionPass *llvm::createARMConstantIslandPass() {
354 return new ARMConstantIslands();
355}
356
Evan Cheng5657c012009-07-29 02:18:14 +0000357bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
358 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000359
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000360 DEBUG(dbgs() << "***** ARMConstantIslands: "
361 << MCP.getConstants().size() << " CP entries, aligned to "
362 << MCP.getConstantPoolAlignment() << " bytes *****\n");
363
Chris Lattner20628752010-07-22 21:27:00 +0000364 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
Evan Cheng5657c012009-07-29 02:18:14 +0000365 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000366 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
367
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000368 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000369 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000370 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000371
372 HasFarJump = false;
373
Evan Chenga8e29892007-01-19 07:51:42 +0000374 // Renumber all of the machine basic blocks in the function, guaranteeing that
375 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000376 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000377
Jim Grosbach80697d12009-11-12 17:25:07 +0000378 // Try to reorder and otherwise adjust the block layout to make good use
379 // of the TB[BH] instructions.
380 bool MadeChange = false;
381 if (isThumb2 && AdjustJumpTableBlocks) {
382 JumpTableFunctionScan(MF);
383 MadeChange |= ReorderThumb2JumpTables(MF);
384 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000385 T2JumpTables.clear();
386 // Blocks may have shifted around. Keep the numbering up to date.
387 MF.RenumberBlocks();
388 }
389
Evan Chengd26b14c2009-07-31 18:28:05 +0000390 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000391 // This is so we can keep exact track of where the alignment padding goes.
392
Chris Lattner7d7dab02010-01-27 23:37:36 +0000393 // ARM and Thumb2 functions need to be 4-byte aligned.
394 if (!isThumb1)
395 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000396
Evan Chenga8e29892007-01-19 07:51:42 +0000397 // Perform the initial placement of the constant pool entries. To start with,
398 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000399 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000400 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000401 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000402 if (isThumb1)
Chris Lattner7d7dab02010-01-27 23:37:36 +0000403 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000404 }
Bob Wilson84945262009-05-12 17:09:30 +0000405
Evan Chenga8e29892007-01-19 07:51:42 +0000406 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000407 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000408
Evan Chenga8e29892007-01-19 07:51:42 +0000409 // Do the initial scan of the function, building up information about the
410 // sizes of each block, the location of all the water, and finding all of the
411 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000412 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000413 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000414 DEBUG(dumpBBs());
415
Bob Wilson84945262009-05-12 17:09:30 +0000416
Evan Chenged884f32007-04-03 23:39:48 +0000417 /// Remove dead constant pool entries.
Bill Wendlingcd080242010-12-18 01:53:06 +0000418 MadeChange |= RemoveUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000419
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000420 // Iteratively place constant pool entries and fix up branches until there
421 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000422 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000423 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000424 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000425 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000426 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000427 CPChange |= HandleConstantPoolUser(MF, i);
428 if (CPChange && ++NoCPIters > 30)
429 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000430 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000431
Bob Wilsonb9239532009-10-15 20:49:47 +0000432 // Clear NewWaterList now. If we split a block for branches, it should
433 // appear as "new water" for the next iteration of constant pool placement.
434 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000435
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000436 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000437 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000438 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000439 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
440 if (BRChange && ++NoBRIters > 30)
441 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000442 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000443
444 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000445 break;
446 MadeChange = true;
447 }
Evan Chenged884f32007-04-03 23:39:48 +0000448
Evan Chenga1efbbd2009-08-14 00:32:16 +0000449 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000450 if (isThumb2 && !STI->prefers32BitThumb())
Evan Chenga1efbbd2009-08-14 00:32:16 +0000451 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000452
Dale Johannesen8593e412007-04-29 19:19:30 +0000453 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000454 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000455
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000456 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
457 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000458 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000459 MadeChange |= UndoLRSpillRestore();
460
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000461 // Save the mapping between original and cloned constpool entries.
462 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
463 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
464 const CPEntry & CPE = CPEntries[i][j];
465 AFI->recordCPEClone(i, CPE.CPI);
466 }
467 }
468
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000469 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000470
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000471 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000472 WaterList.clear();
473 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000474 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000475 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000476 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000477 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000478
479 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000480}
481
482/// DoInitialPlacement - Perform the initial placement of the constant pool
483/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000484void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000485 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000486 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000487 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
488 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000489
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000490 // Mark the basic block as 4-byte aligned as required by the const-pool.
491 BB->setAlignment(2);
492
Evan Chenga8e29892007-01-19 07:51:42 +0000493 // Add all of the constants from the constant pool to the end block, use an
494 // identity mapping of CPI's to CPE's.
495 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000496 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000497
Evan Cheng5657c012009-07-29 02:18:14 +0000498 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000499 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000500 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000501 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
502 // we would have to pad them out or something so that instructions stay
503 // aligned.
504 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
505 MachineInstr *CPEMI =
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000506 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
507 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000508 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000509
510 // Add a new CPEntry, but no corresponding CPUser yet.
511 std::vector<CPEntry> CPEs;
512 CPEs.push_back(CPEntry(CPEMI, i));
513 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000514 ++NumCPEs;
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000515 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function as #" << i
Chris Lattner893e1c92009-08-23 06:49:22 +0000516 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000517 }
518}
519
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000520/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000521/// into the block immediately after it.
522static bool BBHasFallthrough(MachineBasicBlock *MBB) {
523 // Get the next machine basic block in the function.
524 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000525 // Can't fall off end of function.
526 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000527 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000528
Chris Lattner7896c9f2009-12-03 00:50:42 +0000529 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000530 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
531 E = MBB->succ_end(); I != E; ++I)
532 if (*I == NextBB)
533 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000534
Evan Chenga8e29892007-01-19 07:51:42 +0000535 return false;
536}
537
Evan Chengc99ef082007-02-09 20:54:44 +0000538/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
539/// look up the corresponding CPEntry.
540ARMConstantIslands::CPEntry
541*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
542 const MachineInstr *CPEMI) {
543 std::vector<CPEntry> &CPEs = CPEntries[CPI];
544 // Number of entries per constpool index should be small, just do a
545 // linear search.
546 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
547 if (CPEs[i].CPEMI == CPEMI)
548 return &CPEs[i];
549 }
550 return NULL;
551}
552
Jim Grosbach80697d12009-11-12 17:25:07 +0000553/// JumpTableFunctionScan - Do a scan of the function, building up
554/// information about the sizes of each block and the locations of all
555/// the jump tables.
556void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
Jim Grosbach80697d12009-11-12 17:25:07 +0000557 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
558 MBBI != E; ++MBBI) {
559 MachineBasicBlock &MBB = *MBBI;
560
Jim Grosbach80697d12009-11-12 17:25:07 +0000561 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000562 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000563 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000564 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000565 }
566}
567
Evan Chenga8e29892007-01-19 07:51:42 +0000568/// InitialFunctionScan - Do the initial scan of the function, building up
569/// information about the sizes of each block, the location of all the water,
570/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000571void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000572 const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000573 BBInfo.clear();
574 BBInfo.resize(MF.getNumBlockIDs());
575
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000576 // First thing, compute the size of all basic blocks, and see if the function
577 // has any inline assembly in it. If so, we have to be conservative about
578 // alignment assumptions, as we don't know for sure the size of any
579 // instructions in the inline assembly.
580 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
581 ComputeBlockSize(I);
582
583 // The known bits of the entry block offset are determined by the function
584 // alignment.
585 BBInfo.front().KnownBits = MF.getAlignment();
586
587 // Compute block offsets and known bits.
588 AdjustBBOffsetsAfter(MF.begin());
589
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000590 // Now go back through the instructions and build up our data structures.
Evan Cheng5657c012009-07-29 02:18:14 +0000591 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000592 MBBI != E; ++MBBI) {
593 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000594
Evan Chenga8e29892007-01-19 07:51:42 +0000595 // If this block doesn't fall through into the next MBB, then this is
596 // 'water' that a constant pool island could be placed.
597 if (!BBHasFallthrough(&MBB))
598 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000599
Evan Chenga8e29892007-01-19 07:51:42 +0000600 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
601 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000602 if (I->isDebugValue())
603 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000604
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000605 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000606 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000607 bool isCond = false;
608 unsigned Bits = 0;
609 unsigned Scale = 1;
610 int UOpc = Opc;
611 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000612 default:
613 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000614 case ARM::t2BR_JT:
615 T2JumpTables.push_back(I);
616 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000617 case ARM::Bcc:
618 isCond = true;
619 UOpc = ARM::B;
620 // Fallthrough
621 case ARM::B:
622 Bits = 24;
623 Scale = 4;
624 break;
625 case ARM::tBcc:
626 isCond = true;
627 UOpc = ARM::tB;
628 Bits = 8;
629 Scale = 2;
630 break;
631 case ARM::tB:
632 Bits = 11;
633 Scale = 2;
634 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000635 case ARM::t2Bcc:
636 isCond = true;
637 UOpc = ARM::t2B;
638 Bits = 20;
639 Scale = 2;
640 break;
641 case ARM::t2B:
642 Bits = 24;
643 Scale = 2;
644 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000645 }
Evan Chengb43216e2007-02-01 10:16:15 +0000646
647 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000648 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000649 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000650 }
651
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000652 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
653 PushPopMIs.push_back(I);
654
Evan Chengd3d9d662009-07-23 18:27:47 +0000655 if (Opc == ARM::CONSTPOOL_ENTRY)
656 continue;
657
Evan Chenga8e29892007-01-19 07:51:42 +0000658 // Scan the instructions for constant pool operands.
659 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000660 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000661 // We found one. The addressing mode tells us the max displacement
662 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000663
Evan Chenga8e29892007-01-19 07:51:42 +0000664 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000665 unsigned Bits = 0;
666 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000667 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000668 bool IsSoImm = false;
669
670 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000671 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000672 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000673 break;
674
675 // Taking the address of a CP entry.
676 case ARM::LEApcrel:
677 // This takes a SoImm, which is 8 bit immediate rotated. We'll
678 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000679 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000680 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000681 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000682 Scale = 4;
683 NegOk = true;
684 IsSoImm = true;
685 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000686 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000687 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000688 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000689 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000690 case ARM::tLEApcrel:
691 Bits = 8;
692 Scale = 4;
693 break;
694
Jim Grosbach3e556122010-10-26 22:37:02 +0000695 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000696 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000697 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000698 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000699 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000700 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000701
702 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000703 Bits = 8;
704 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000705 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000706
Jim Grosbache5165492009-11-09 00:11:35 +0000707 case ARM::VLDRD:
708 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000709 Bits = 8;
710 Scale = 4; // +-(offset_8*4)
711 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000712 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000713 }
Evan Chengb43216e2007-02-01 10:16:15 +0000714
Evan Chenga8e29892007-01-19 07:51:42 +0000715 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000716 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000717 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000718 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000719 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000720
721 // Increment corresponding CPEntry reference count.
722 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
723 assert(CPE && "Cannot find a corresponding CPEntry!");
724 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000725
Evan Chenga8e29892007-01-19 07:51:42 +0000726 // Instructions can only use one CP entry, don't bother scanning the
727 // rest of the operands.
728 break;
729 }
730 }
Evan Chenga8e29892007-01-19 07:51:42 +0000731 }
732}
733
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000734/// ComputeBlockSize - Compute the size and some alignment information for MBB.
735/// This function updates BBInfo directly.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000736void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000737 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
738 BBI.Size = 0;
739 BBI.Unalign = 0;
740 BBI.PostAlign = 0;
741
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000742 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
743 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000744 BBI.Size += TII->GetInstSizeInBytes(I);
745 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
746 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000747 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000748 BBI.Unalign = isThumb ? 1 : 2;
749 }
750
751 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000752 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000753 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000754 MBB->getParent()->EnsureAlignment(2);
755 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000756}
757
Evan Chenga8e29892007-01-19 07:51:42 +0000758/// GetOffsetOf - Return the current offset of the specified machine instruction
759/// from the start of the function. This offset changes as stuff is moved
760/// around inside the function.
761unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
762 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000763
Evan Chenga8e29892007-01-19 07:51:42 +0000764 // The offset is composed of two things: the sum of the sizes of all MBB's
765 // before this instruction's block, and the offset from the start of the block
766 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000767 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000768
769 // Sum instructions before MI in MBB.
770 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
771 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
772 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000773 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000774 }
775}
776
777/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
778/// ID.
779static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
780 const MachineBasicBlock *RHS) {
781 return LHS->getNumber() < RHS->getNumber();
782}
783
784/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
785/// machine function, it upsets all of the block numbers. Renumber the blocks
786/// and update the arrays that parallel this numbering.
787void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000788 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000789 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000790
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000791 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000792 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000793 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000794
795 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000796 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000797 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000798 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
799 CompareMBBNumbers);
800 WaterList.insert(IP, NewBB);
801}
802
803
804/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000805/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000806/// account for this change and returns the newly created block.
807MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000808 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000809 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000810
811 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000812 MachineBasicBlock *NewBB =
813 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000814 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000815 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000816
Evan Chenga8e29892007-01-19 07:51:42 +0000817 // Splice the instructions starting with MI over to NewBB.
818 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000819
Evan Chenga8e29892007-01-19 07:51:42 +0000820 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000821 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000822 // There doesn't seem to be meaningful DebugInfo available; this doesn't
823 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000824 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000825 if (!isThumb)
826 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
827 else
828 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
829 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000830 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000831
Evan Chenga8e29892007-01-19 07:51:42 +0000832 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000833 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000834
Evan Chenga8e29892007-01-19 07:51:42 +0000835 // OrigBB branches to NewBB.
836 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000837
Evan Chenga8e29892007-01-19 07:51:42 +0000838 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000839 // This is almost the same as UpdateForInsertedWaterBlock, except that
840 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000841 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000842
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000843 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000844 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000845 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000846
Bob Wilson84945262009-05-12 17:09:30 +0000847 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000848 // available water after it (but not if it's already there, which happens
849 // when splitting before a conditional branch that is followed by an
850 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000851 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000852 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
853 CompareMBBNumbers);
854 MachineBasicBlock* WaterBB = *IP;
855 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000856 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000857 else
858 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000859 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000860
Dale Johannesen8086d582010-07-23 22:50:23 +0000861 // Figure out how large the OrigBB is. As the first half of the original
862 // block, it cannot contain a tablejump. The size includes
863 // the new jump we added. (It should be possible to do this without
864 // recounting everything, but it's very confusing, and this is rarely
865 // executed.)
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000866 ComputeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000867
Dale Johannesen8086d582010-07-23 22:50:23 +0000868 // Figure out how large the NewMBB is. As the second half of the original
869 // block, it may contain a tablejump.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000870 ComputeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000871
Dale Johannesen99c49a42007-02-25 00:47:03 +0000872 // All BBOffsets following these blocks must be modified.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000873 AdjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000874
875 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000876}
877
Dale Johannesen8593e412007-04-29 19:19:30 +0000878/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000879/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000880/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000881bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000882 unsigned TrialOffset, unsigned MaxDisp,
883 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000884 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
885 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000886 // Effectively, the valid range of displacements is 2 bytes smaller for such
887 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000888 unsigned TotalAdj = 0;
889 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000890 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000891 TotalAdj = 2;
892 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000893 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000894 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000895 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000896 TotalAdj += 2;
897 }
898
899 // In Thumb2 mode, later branch adjustments can shift instructions up and
900 // cause alignment change. In the worst case scenario this can cause the
901 // user's effective address to be subtracted by 2 and the CPE's address to
902 // be plus 2.
903 if (isThumb2 && TotalAdj != 4)
904 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000905
Dale Johannesen99c49a42007-02-25 00:47:03 +0000906 if (UserOffset <= TrialOffset) {
907 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000908 if (TrialOffset - UserOffset <= MaxDisp)
909 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000910 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000911 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000912 if (UserOffset - TrialOffset <= MaxDisp)
913 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000914 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000915 }
916 return false;
917}
918
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000919/// WaterIsInRange - Returns true if a CPE placed after the specified
920/// Water (a basic block) will be in range for the specific MI.
921
922bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000923 MachineBasicBlock* Water, CPUser &U) {
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000924 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000925
Dale Johannesend959aa42007-04-02 20:31:06 +0000926 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000927 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000928 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000929 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000930
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000931 return OffsetIsInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000932}
933
934/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000935/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000936bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000937 MachineInstr *CPEMI, unsigned MaxDisp,
938 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000939 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000940 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000941
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000942 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000943 DEBUG({
944 unsigned Block = MI->getParent()->getNumber();
945 const BasicBlockInfo &BBI = BBInfo[Block];
946 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
947 << " max delta=" << MaxDisp
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000948 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000949 << " in BB#" << Block << ": "
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000950 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
951 << format("CPE address=%#x offset=%+d: ", CPEOffset,
952 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000953 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000954 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000955
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000956 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000957}
958
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000959#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000960/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
961/// unconditionally branches to its only successor.
962static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
963 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
964 return false;
965
966 MachineBasicBlock *Succ = *MBB->succ_begin();
967 MachineBasicBlock *Pred = *MBB->pred_begin();
968 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000969 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
970 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000971 return PredMI->getOperand(0).getMBB() == Succ;
972 return false;
973}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000974#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000975
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000976void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000977 MachineFunction *MF = BB->getParent();
978 for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
979 // Get the offset and known bits at the end of the layout predecessor.
980 unsigned Offset = BBInfo[i - 1].postOffset();
981 unsigned KnownBits = BBInfo[i - 1].postKnownBits();
982
983 // Add padding before an aligned block. This may teach us more bits.
984 if (unsigned Align = MF->getBlockNumbered(i)->getAlignment()) {
985 Offset = WorstCaseAlign(Offset, Align, KnownBits);
986 KnownBits = std::max(KnownBits, Align);
Dale Johannesen8593e412007-04-29 19:19:30 +0000987 }
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000988
989 // This is where block i begins.
990 BBInfo[i].Offset = Offset;
991 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +0000992 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000993}
994
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000995/// DecrementOldEntry - find the constant pool entry with index CPI
996/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000997/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000998/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000999
Evan Chenged884f32007-04-03 23:39:48 +00001000bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +00001001 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +00001002 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1003 assert(CPE && "Unexpected!");
1004 if (--CPE->RefCount == 0) {
1005 RemoveDeadCPEMI(CPEMI);
1006 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +00001007 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001008 return true;
1009 }
1010 return false;
1011}
1012
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001013/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1014/// if not, see if an in-range clone of the CPE is in range, and if so,
1015/// change the data structures so the user references the clone. Returns:
1016/// 0 = no existing entry found
1017/// 1 = entry found, and there were no code insertions or deletions
1018/// 2 = entry found, and there were code insertions or deletions
1019int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1020{
1021 MachineInstr *UserMI = U.MI;
1022 MachineInstr *CPEMI = U.CPEMI;
1023
1024 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001025 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001026 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001027 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001028 }
1029
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001030 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001031 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001032 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1033 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1034 // We already tried this one
1035 if (CPEs[i].CPEMI == CPEMI)
1036 continue;
1037 // Removing CPEs can leave empty entries, skip
1038 if (CPEs[i].CPEMI == NULL)
1039 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001040 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001041 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001042 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001043 // Point the CPUser node to the replacement
1044 U.CPEMI = CPEs[i].CPEMI;
1045 // Change the CPI in the instruction operand to refer to the clone.
1046 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001047 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001048 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001049 break;
1050 }
1051 // Adjust the refcount of the clone...
1052 CPEs[i].RefCount++;
1053 // ...and the original. If we didn't remove the old entry, none of the
1054 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001055 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001056 }
1057 }
1058 return 0;
1059}
1060
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001061/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1062/// the specific unconditional branch instruction.
1063static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001064 switch (Opc) {
1065 case ARM::tB:
1066 return ((1<<10)-1)*2;
1067 case ARM::t2B:
1068 return ((1<<23)-1)*2;
1069 default:
1070 break;
1071 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001072
David Goodwin5e47a9a2009-06-30 18:04:13 +00001073 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001074}
1075
Bob Wilsonb9239532009-10-15 20:49:47 +00001076/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001077/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001078/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001079/// is set to the WaterList entry. For Thumb, prefer water that will not
1080/// introduce padding to water that will. To ensure that this pass
1081/// terminates, the CPE location for a particular CPUser is only allowed to
1082/// move to a lower address, so search backward from the end of the list and
1083/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001084bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001085 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001086 if (WaterList.empty())
1087 return false;
1088
Bob Wilson32c50e82009-10-12 20:45:53 +00001089 bool FoundWaterThatWouldPad = false;
1090 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001091 for (water_iterator IP = prior(WaterList.end()),
1092 B = WaterList.begin();; --IP) {
1093 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001094 // Check if water is in range and is either at a lower address than the
1095 // current "high water mark" or a new water block that was created since
1096 // the previous iteration by inserting an unconditional branch. In the
1097 // latter case, we want to allow resetting the high water mark back to
1098 // this new water since we haven't seen it before. Inserting branches
1099 // should be relatively uncommon and when it does happen, we want to be
1100 // sure to take advantage of it for all the CPEs near that block, so that
1101 // we don't insert more branches than necessary.
1102 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1103 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1104 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001105 unsigned WBBId = WaterBB->getNumber();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001106 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
Bob Wilson3b757352009-10-12 19:04:03 +00001107 // This is valid Water, but would introduce padding. Remember
1108 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001109 if (!FoundWaterThatWouldPad) {
1110 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001111 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001112 }
Bob Wilson3b757352009-10-12 19:04:03 +00001113 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001114 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001115 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001116 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001117 }
Bob Wilson3b757352009-10-12 19:04:03 +00001118 if (IP == B)
1119 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001120 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001121 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001122 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001123 return true;
1124 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001125 return false;
1126}
1127
Bob Wilson84945262009-05-12 17:09:30 +00001128/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001129/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1130/// block is used if in range, and the conditional branch munged so control
1131/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001132/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001133/// block following which the new island can be inserted (the WaterList
1134/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001135void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001136 unsigned UserOffset,
1137 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001138 CPUser &U = CPUsers[CPUserIndex];
1139 MachineInstr *UserMI = U.MI;
1140 MachineInstr *CPEMI = U.CPEMI;
1141 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001142 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1143 unsigned OffsetOfNextBlock = UserBBI.postOffset();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001144
Bob Wilson36fa5322009-10-15 05:10:36 +00001145 // If the block does not end in an unconditional branch already, and if the
1146 // end of the block is within range, make new water there. (The addition
1147 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1148 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001149 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001150 if (BBHasFallthrough(UserMBB) &&
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001151 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4), U)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001152 DEBUG(dbgs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001153 if (&UserMBB->back() == UserMI)
1154 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001155 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001156 // Add an unconditional branch from UserMBB to fallthrough block.
1157 // Record it for branch lengthening; this new branch will not get out of
1158 // range, but if the preceding conditional branch is out of range, the
1159 // targets will be exchanged, and the altered branch may be out of
1160 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001161 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001162 if (!isThumb)
1163 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1164 else
1165 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1166 .addImm(ARMCC::AL).addReg(0);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001167 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001168 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001169 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001170 int delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001171 BBInfo[UserMBB->getNumber()].Size += delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001172 AdjustBBOffsetsAfter(UserMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001173 } else {
1174 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001175 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001176 // and constant pool entries are 4 bytes: if instruction I references
1177 // island CPE, and instruction I+1 references CPE', it will
1178 // not work well to put CPE as far forward as possible, since then
1179 // CPE' cannot immediately follow it (that location is 2 bytes
1180 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001181 // a new island. So, we make a first guess, then walk through the
1182 // instructions between the one currently being looked at and the
1183 // possible insertion point, and make sure any other instructions
1184 // that reference CPEs will be able to use the same island area;
1185 // if not, we back up the insertion point.
1186
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001187 // Try to split the block so it's fully aligned. Compute the latest split
1188 // point where we can add a 4-byte branch instruction, and then
1189 // WorstCaseAlign to LogAlign.
1190 unsigned LogAlign = UserMBB->getParent()->getAlignment();
1191 unsigned KnownBits = UserBBI.internalKnownBits();
1192 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1193 unsigned BaseInsertOffset = UserOffset + U.MaxDisp;
1194 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1195 BaseInsertOffset));
1196
1197 // Account for alignment and unknown padding.
1198 BaseInsertOffset &= ~((1u << LogAlign) - 1);
1199 BaseInsertOffset -= UPad;
1200
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001201 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001202 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001203 // island is handled inside OffsetIsInRange.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001204 BaseInsertOffset -= 4;
1205
1206 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1207 << " la=" << LogAlign
1208 << " kb=" << KnownBits
1209 << " up=" << UPad << '\n');
1210
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001211 // This could point off the end of the block if we've already got
1212 // constant pool entries following this block; only the last one is
1213 // in the water list. Back past any possible branches (allow for a
1214 // conditional and a maximally long unconditional).
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001215 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1216 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
Evan Chengd3d9d662009-07-23 18:27:47 +00001217 (isThumb1 ? 6 : 8);
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001218 unsigned EndInsertOffset =
1219 WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1220 CPEMI->getOperand(2).getImm();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001221 MachineBasicBlock::iterator MI = UserMI;
1222 ++MI;
1223 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001224 unsigned NumCPUsers = CPUsers.size();
1225 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001226 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001227 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001228 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001229 MI = llvm::next(MI)) {
1230 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001231 CPUser &U = CPUsers[CPUIndex];
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001232 if (!OffsetIsInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001233 BaseInsertOffset -= 1u << LogAlign;
1234 EndInsertOffset -= 1u << LogAlign;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001235 }
1236 // This is overly conservative, as we don't account for CPEMIs
1237 // being reused within the block, but it doesn't matter much.
1238 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1239 CPUIndex++;
1240 }
Evan Cheng719510a2010-08-12 20:30:05 +00001241
1242 // Remember the last IT instruction.
1243 if (MI->getOpcode() == ARM::t2IT)
1244 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001245 }
Evan Cheng719510a2010-08-12 20:30:05 +00001246
Evan Cheng719510a2010-08-12 20:30:05 +00001247 --MI;
1248
1249 // Avoid splitting an IT block.
1250 if (LastIT) {
1251 unsigned PredReg = 0;
1252 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1253 if (CC != ARMCC::AL)
1254 MI = LastIT;
1255 }
1256 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001257 }
1258}
1259
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001260/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001261/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001262/// place in-range. Return true if we changed any addresses (thus must run
1263/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001264bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001265 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001266 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001267 MachineInstr *UserMI = U.MI;
1268 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001269 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001270 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001271 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001272 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001273 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001274
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001275 // See if the current entry is within range, or there is a clone of it
1276 // in range.
1277 int result = LookForExistingCPEntry(U, UserOffset);
1278 if (result==1) return false;
1279 else if (result==2) return true;
1280
1281 // No existing clone of this CPE is within range.
1282 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001283 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001284
Bob Wilsonf98032e2009-10-12 21:23:15 +00001285 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001286 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1287 MachineBasicBlock *NewMBB;
1288 water_iterator IP;
1289 if (LookForWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001290 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001291 MachineBasicBlock *WaterBB = *IP;
1292
1293 // If the original WaterList entry was "new water" on this iteration,
1294 // propagate that to the new island. This is just keeping NewWaterList
1295 // updated to match the WaterList, which will be updated below.
1296 if (NewWaterList.count(WaterBB)) {
1297 NewWaterList.erase(WaterBB);
1298 NewWaterList.insert(NewIsland);
1299 }
1300 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001301 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001302
1303 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001304 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001305 DEBUG(dbgs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001306 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001307
1308 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1309 // called while handling branches so that the water will be seen on the
1310 // next iteration for constant pools, but in this context, we don't want
1311 // it. Check for this so it will be removed from the WaterList.
1312 // Also remove any entry from NewWaterList.
1313 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1314 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1315 if (IP != WaterList.end())
1316 NewWaterList.erase(WaterBB);
1317
1318 // We are adding new water. Update NewWaterList.
1319 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001320 }
1321
Bob Wilsonb9239532009-10-15 20:49:47 +00001322 // Remove the original WaterList entry; we want subsequent insertions in
1323 // this vicinity to go after the one we're about to insert. This
1324 // considerably reduces the number of times we have to move the same CPE
1325 // more than once and is also important to ensure the algorithm terminates.
1326 if (IP != WaterList.end())
1327 WaterList.erase(IP);
1328
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001329 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001330 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001331
1332 // Update internal data structures to account for the newly inserted MBB.
1333 UpdateForInsertedWaterBlock(NewIsland);
1334
1335 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001336 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001337
1338 // Now that we have an island to add the CPE to, clone the original CPE and
1339 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001340 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001341 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001342 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001343 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001344 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001345
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001346 // Mark the basic block as 4-byte aligned as required by the const-pool entry.
1347 NewIsland->setAlignment(2);
1348
Evan Chenga8e29892007-01-19 07:51:42 +00001349 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001350 BBInfo[NewIsland->getNumber()].Size += Size;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001351 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001352
Evan Chenga8e29892007-01-19 07:51:42 +00001353 // Finally, change the CPI in the instruction operand to be ID.
1354 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001355 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001356 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001357 break;
1358 }
Bob Wilson84945262009-05-12 17:09:30 +00001359
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001360 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001361 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson84945262009-05-12 17:09:30 +00001362
Evan Chenga8e29892007-01-19 07:51:42 +00001363 return true;
1364}
1365
Evan Chenged884f32007-04-03 23:39:48 +00001366/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1367/// sizes and offsets of impacted basic blocks.
1368void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1369 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001370 unsigned Size = CPEMI->getOperand(2).getImm();
1371 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001372 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001373 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001374 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001375 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001376 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001377 // empty, so fix this.
1378 // All succeeding offsets have the current size value added in, fix this.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001379 if (BBInfo[CPEBB->getNumber()].Size != 0) {
1380 Size += BBInfo[CPEBB->getNumber()].Size;
1381 BBInfo[CPEBB->getNumber()].Size = 0;
Evan Chenged884f32007-04-03 23:39:48 +00001382 }
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001383
1384 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1385 CPEBB->setAlignment(0);
Evan Chenged884f32007-04-03 23:39:48 +00001386 }
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001387 AdjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001388 // An island has only one predecessor BB and one successor BB. Check if
1389 // this BB's predecessor jumps directly to this BB's successor. This
1390 // shouldn't happen currently.
1391 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1392 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001393}
1394
1395/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1396/// are zero.
1397bool ARMConstantIslands::RemoveUnusedCPEntries() {
1398 unsigned MadeChange = false;
1399 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1400 std::vector<CPEntry> &CPEs = CPEntries[i];
1401 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1402 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1403 RemoveDeadCPEMI(CPEs[j].CPEMI);
1404 CPEs[j].CPEMI = NULL;
1405 MadeChange = true;
1406 }
1407 }
Bob Wilson84945262009-05-12 17:09:30 +00001408 }
Evan Chenged884f32007-04-03 23:39:48 +00001409 return MadeChange;
1410}
1411
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001412/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001413/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001414bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1415 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001416 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001417 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001418 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001419
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001420 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001421 << " from BB#" << MI->getParent()->getNumber()
1422 << " max delta=" << MaxDisp
1423 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1424 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001425
Dale Johannesen8593e412007-04-29 19:19:30 +00001426 if (BrOffset <= DestOffset) {
1427 // Branch before the Dest.
1428 if (DestOffset-BrOffset <= MaxDisp)
1429 return true;
1430 } else {
1431 if (BrOffset-DestOffset <= MaxDisp)
1432 return true;
1433 }
1434 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001435}
1436
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001437/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1438/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001439bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001440 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001441 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001442
Evan Chengc0dbec72007-01-31 19:57:44 +00001443 // Check to see if the DestBB is already in-range.
1444 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001445 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001446
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001447 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001448 return FixUpUnconditionalBr(MF, Br);
1449 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001450}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001451
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001452/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1453/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001454/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001455/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001456bool
Evan Cheng5657c012009-07-29 02:18:14 +00001457ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001458 MachineInstr *MI = Br.MI;
1459 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001460 if (!isThumb1)
1461 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001462
1463 // Use BL to implement far jump.
1464 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001465 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001466 BBInfo[MBB->getNumber()].Size += 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001467 AdjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001468 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001469 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001470
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001471 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001472
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001473 return true;
1474}
1475
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001476/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001477/// far away to fit in its displacement field. It is converted to an inverse
1478/// conditional branch + an unconditional branch to the destination.
1479bool
Evan Cheng5657c012009-07-29 02:18:14 +00001480ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001481 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001482 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001483
Bob Wilson39bf0512009-05-12 17:35:29 +00001484 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001485 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001486 // blt L1
1487 // =>
1488 // bge L2
1489 // b L1
1490 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001491 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001492 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001493 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001494
1495 // If the branch is at the end of its MBB and that has a fall-through block,
1496 // direct the updated conditional branch to the fall-through block. Otherwise,
1497 // split the MBB before the next instruction.
1498 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001499 MachineInstr *BMI = &MBB->back();
1500 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001501
Dan Gohmanfe601042010-06-22 15:08:57 +00001502 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001503 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001504 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001505 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001506 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001507 // condition and swap destinations:
1508 // beq L1
1509 // b L2
1510 // =>
1511 // bne L2
1512 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001513 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001514 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001515 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001516 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001517 BMI->getOperand(0).setMBB(DestBB);
1518 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001519 MI->getOperand(1).setImm(CC);
1520 return true;
1521 }
1522 }
1523 }
1524
1525 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001526 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001527 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001528 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001529 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001530 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001531 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001532 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001533 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001534 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001535
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001536 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001537 << " also invert condition and change dest. to BB#"
1538 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001539
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001540 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001541 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001542 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001543 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001544 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001545 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001546 if (isThumb)
1547 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1548 .addImm(ARMCC::AL).addReg(0);
1549 else
1550 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001551 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001552 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001553 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001554
1555 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001556 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001557 MI->eraseFromParent();
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001558 AdjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001559 return true;
1560}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001561
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001562/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001563/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1564/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001565bool ARMConstantIslands::UndoLRSpillRestore() {
1566 bool MadeChange = false;
1567 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1568 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001569 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001570 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001571 MI->getOperand(2).getReg() == ARM::PC &&
1572 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001573 // Create the new insn and copy the predicate from the old.
1574 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1575 .addOperand(MI->getOperand(0))
1576 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001577 MI->eraseFromParent();
1578 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001579 }
1580 }
1581 return MadeChange;
1582}
Evan Cheng5657c012009-07-29 02:18:14 +00001583
Evan Chenga1efbbd2009-08-14 00:32:16 +00001584bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1585 bool MadeChange = false;
1586
1587 // Shrink ADR and LDR from constantpool.
1588 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1589 CPUser &U = CPUsers[i];
1590 unsigned Opcode = U.MI->getOpcode();
1591 unsigned NewOpc = 0;
1592 unsigned Scale = 1;
1593 unsigned Bits = 0;
1594 switch (Opcode) {
1595 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001596 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001597 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1598 NewOpc = ARM::tLEApcrel;
1599 Bits = 8;
1600 Scale = 4;
1601 }
1602 break;
1603 case ARM::t2LDRpci:
1604 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1605 NewOpc = ARM::tLDRpci;
1606 Bits = 8;
1607 Scale = 4;
1608 }
1609 break;
1610 }
1611
1612 if (!NewOpc)
1613 continue;
1614
1615 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1616 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1617 // FIXME: Check if offset is multiple of scale if scale is not 4.
1618 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1619 U.MI->setDesc(TII->get(NewOpc));
1620 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001621 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001622 AdjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001623 ++NumT2CPShrunk;
1624 MadeChange = true;
1625 }
1626 }
1627
Evan Chenga1efbbd2009-08-14 00:32:16 +00001628 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001629 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001630 return MadeChange;
1631}
1632
1633bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001634 bool MadeChange = false;
1635
1636 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1637 ImmBranch &Br = ImmBranches[i];
1638 unsigned Opcode = Br.MI->getOpcode();
1639 unsigned NewOpc = 0;
1640 unsigned Scale = 1;
1641 unsigned Bits = 0;
1642 switch (Opcode) {
1643 default: break;
1644 case ARM::t2B:
1645 NewOpc = ARM::tB;
1646 Bits = 11;
1647 Scale = 2;
1648 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001649 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001650 NewOpc = ARM::tBcc;
1651 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001652 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001653 break;
1654 }
Evan Chengde17fb62009-10-31 23:46:45 +00001655 }
1656 if (NewOpc) {
1657 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1658 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1659 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1660 Br.MI->setDesc(TII->get(NewOpc));
1661 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001662 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001663 AdjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001664 ++NumT2BrShrunk;
1665 MadeChange = true;
1666 }
1667 }
1668
1669 Opcode = Br.MI->getOpcode();
1670 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001671 continue;
1672
Evan Chengde17fb62009-10-31 23:46:45 +00001673 NewOpc = 0;
1674 unsigned PredReg = 0;
1675 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1676 if (Pred == ARMCC::EQ)
1677 NewOpc = ARM::tCBZ;
1678 else if (Pred == ARMCC::NE)
1679 NewOpc = ARM::tCBNZ;
1680 if (!NewOpc)
1681 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001682 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001683 // Check if the distance is within 126. Subtract starting offset by 2
1684 // because the cmp will be eliminated.
1685 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001686 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001687 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001688 MachineBasicBlock::iterator CmpMI = Br.MI;
1689 if (CmpMI != Br.MI->getParent()->begin()) {
1690 --CmpMI;
1691 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1692 unsigned Reg = CmpMI->getOperand(0).getReg();
1693 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1694 if (Pred == ARMCC::AL &&
1695 CmpMI->getOperand(1).getImm() == 0 &&
1696 isARMLowRegister(Reg)) {
1697 MachineBasicBlock *MBB = Br.MI->getParent();
1698 MachineInstr *NewBR =
1699 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1700 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1701 CmpMI->eraseFromParent();
1702 Br.MI->eraseFromParent();
1703 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001704 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001705 AdjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001706 ++NumCBZ;
1707 MadeChange = true;
1708 }
Evan Chengde17fb62009-10-31 23:46:45 +00001709 }
1710 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001711 }
1712 }
1713
1714 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001715}
1716
Evan Chenga1efbbd2009-08-14 00:32:16 +00001717/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1718/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001719bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1720 bool MadeChange = false;
1721
1722 // FIXME: After the tables are shrunk, can we get rid some of the
1723 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001724 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001725 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001726
Evan Cheng5657c012009-07-29 02:18:14 +00001727 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1728 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1729 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001730 const MCInstrDesc &MCID = MI->getDesc();
1731 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001732 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001733 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1734 unsigned JTI = JTOP.getIndex();
1735 assert(JTI < JT.size());
1736
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001737 bool ByteOk = true;
1738 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001739 unsigned JTOffset = GetOffsetOf(MI) + 4;
1740 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001741 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1742 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001743 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001744 // Negative offset is not ok. FIXME: We should change BB layout to make
1745 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001746 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001747 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001748 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001749 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001750 HalfWordOk = false;
1751 if (!ByteOk && !HalfWordOk)
1752 break;
1753 }
1754
1755 if (ByteOk || HalfWordOk) {
1756 MachineBasicBlock *MBB = MI->getParent();
1757 unsigned BaseReg = MI->getOperand(0).getReg();
1758 bool BaseRegKill = MI->getOperand(0).isKill();
1759 if (!BaseRegKill)
1760 continue;
1761 unsigned IdxReg = MI->getOperand(1).getReg();
1762 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001763
1764 // Scan backwards to find the instruction that defines the base
1765 // register. Due to post-RA scheduling, we can't count on it
1766 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001767 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001768 MachineBasicBlock::iterator B = MBB->begin();
1769 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1770 --PrevI;
1771
1772 // If for some reason we didn't find it, we can't do anything, so
1773 // just skip this one.
1774 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001775 continue;
1776
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001777 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001778 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001779 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001780 // Make sure it only defines the base register and kills any uses
1781 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001782 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1783 const MachineOperand &MO = AddrMI->getOperand(k);
1784 if (!MO.isReg() || !MO.getReg())
1785 continue;
1786 if (MO.isDef() && MO.getReg() != BaseReg) {
1787 OptOk = false;
1788 break;
1789 }
1790 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1791 OptOk = false;
1792 break;
1793 }
1794 }
1795 if (!OptOk)
1796 continue;
1797
Owen Anderson6b8719f2010-12-13 22:51:08 +00001798 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001799 // that gave us the initial base register definition.
1800 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1801 ;
1802
Owen Anderson6b8719f2010-12-13 22:51:08 +00001803 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001804 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001805 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001806 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001807 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001808 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001809 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001810
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001811 if (!OptOk)
1812 continue;
1813
Jim Grosbachd092a872010-11-29 21:28:32 +00001814 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001815 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1816 .addReg(IdxReg, getKillRegState(IdxRegKill))
1817 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1818 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1819 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1820 // is 2-byte aligned. For now, asm printer will fix it up.
1821 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1822 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1823 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1824 OrigSize += TII->GetInstSizeInBytes(MI);
1825
1826 AddrMI->eraseFromParent();
1827 LeaMI->eraseFromParent();
1828 MI->eraseFromParent();
1829
1830 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001831 BBInfo[MBB->getNumber()].Size -= delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001832 AdjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001833
1834 ++NumTBs;
1835 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001836 }
1837 }
1838
1839 return MadeChange;
1840}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001841
Jim Grosbach9249efe2009-11-16 18:55:47 +00001842/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1843/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach80697d12009-11-12 17:25:07 +00001844bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1845 bool MadeChange = false;
1846
1847 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001848 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001849
Jim Grosbach80697d12009-11-12 17:25:07 +00001850 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1851 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1852 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001853 const MCInstrDesc &MCID = MI->getDesc();
1854 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001855 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001856 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1857 unsigned JTI = JTOP.getIndex();
1858 assert(JTI < JT.size());
1859
1860 // We prefer if target blocks for the jump table come after the jump
1861 // instruction so we can use TB[BH]. Loop through the target blocks
1862 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001863 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001864 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1865 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1866 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001867 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001868
Jim Grosbach08cbda52009-11-16 18:58:52 +00001869 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001870 // The destination precedes the switch. Try to move the block forward
1871 // so we have a positive offset.
1872 MachineBasicBlock *NewBB =
1873 AdjustJTTargetBlockForward(MBB, MI->getParent());
1874 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001875 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001876 MadeChange = true;
1877 }
1878 }
1879 }
1880
1881 return MadeChange;
1882}
1883
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001884MachineBasicBlock *ARMConstantIslands::
1885AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1886{
1887 MachineFunction &MF = *BB->getParent();
1888
Jim Grosbach03e2d442010-07-07 22:53:35 +00001889 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001890 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001891 // table that branches back to the actual target. This is a very simple
1892 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001893 MachineBasicBlock *TBB = 0, *FBB = 0;
1894 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001895 SmallVector<MachineOperand, 4> CondPrior;
1896 MachineFunction::iterator BBi = BB;
1897 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001898
Jim Grosbachca215e72009-11-16 17:10:56 +00001899 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001900 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001901
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001902 // If the block ends in an unconditional branch, move it. The prior block
1903 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001904 // and make sure we're not trying to move the entry block of the function.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001905 if (!B && Cond.empty() && BB != MF.begin() &&
1906 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001907 BB->moveAfter(JTBB);
1908 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001909 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001910 // Update numbering to account for the block being moved.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001911 MF.RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001912 ++NumJTMoved;
1913 return NULL;
1914 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001915
1916 // Create a new MBB for the code after the jump BB.
1917 MachineBasicBlock *NewBB =
1918 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1919 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1920 MF.insert(MBBI, NewBB);
1921
1922 // Add an unconditional branch from NewBB to BB.
1923 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1924 // correspond directly to anything in the source.
1925 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001926 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1927 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001928
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001929 // Update internal data structures to account for the newly inserted MBB.
1930 MF.RenumberBlocks(NewBB);
1931
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001932 // Update the CFG.
1933 NewBB->addSuccessor(BB);
1934 JTBB->removeSuccessor(BB);
1935 JTBB->addSuccessor(NewBB);
1936
Jim Grosbach80697d12009-11-12 17:25:07 +00001937 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001938 return NewBB;
1939}