blob: a57cd8ee134a30b5d7c6c5a42d1fc671ee96c241 [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"
Chris Lattner705e07f2009-08-23 03:41:05 +000029#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000031#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000034#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000035#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000036using namespace llvm;
37
Evan Chenga1efbbd2009-08-14 00:32:16 +000038STATISTIC(NumCPEs, "Number of constpool entries");
39STATISTIC(NumSplit, "Number of uncond branches inserted");
40STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42STATISTIC(NumTBs, "Number of table branches generated");
43STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000044STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000045STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000046STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000047STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000048
49
50static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000051AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000052 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000053
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000054/// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
55/// add padding such that:
56///
57/// 1. The result is aligned to 1 << LogAlign.
58///
59/// 2. No other value of the unknown bits would require more padding.
60///
61/// This may add more padding than is required to satisfy just one of the
62/// constraints. It is necessary to compute alignment this way to guarantee
63/// that we don't underestimate the padding before an aligned block. If the
64/// real padding before a block is larger than we think, constant pool entries
65/// may go out of range.
66static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
67 unsigned KnownBits) {
68 // Add the worst possible padding that the unknown bits could cause.
69 if (KnownBits < LogAlign)
70 Offset += (1u << LogAlign) - (1u << KnownBits);
71
72 // Then align the result.
73 return RoundUpToAlignment(Offset, 1u << LogAlign);
74}
75
Evan Chenga8e29892007-01-19 07:51:42 +000076namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000077 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000078 /// requires constant pool entries to be scattered among the instructions
79 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000080 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000081 /// special instructions.
82 ///
83 /// The terminology used in this pass includes:
84 /// Islands - Clumps of constants placed in the function.
85 /// Water - Potential places where an island could be formed.
86 /// CPE - A constant pool entry that has been placed somewhere, which
87 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000088 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000089 /// BasicBlockInfo - Information about the offset and size of a single
90 /// basic block.
91 struct BasicBlockInfo {
92 /// Offset - Distance from the beginning of the function to the beginning
93 /// of this basic block.
94 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000095 /// The offset is always aligned as required by the basic block.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000096 unsigned Offset;
Bob Wilson84945262009-05-12 17:09:30 +000097
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +000098 /// Size - Size of the basic block in bytes. If the block contains
99 /// inline assembly, this is a worst case estimate.
100 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000101 /// The size does not include any alignment padding whether from the
102 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000103 unsigned Size;
104
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000105 /// KnownBits - The number of low bits in Offset that are known to be
106 /// exact. The remaining bits of Offset are an upper bound.
107 uint8_t KnownBits;
108
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000109 /// Unalign - When non-zero, the block contains instructions (inline asm)
110 /// of unknown size. The real size may be smaller than Size bytes by a
111 /// multiple of 1 << Unalign.
112 uint8_t Unalign;
113
114 /// PostAlign - When non-zero, the block terminator contains a .align
115 /// directive, so the end of the block is aligned to 1 << PostAlign
116 /// bytes.
117 uint8_t PostAlign;
118
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000119 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
120 PostAlign(0) {}
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000121
122 /// Compute the offset immediately following this block.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000123 unsigned postOffset() const {
124 unsigned PO = Offset + Size;
125 if (!PostAlign)
126 return PO;
127 // Add alignment padding from the terminator.
128 return WorstCaseAlign(PO, PostAlign, Unalign ? Unalign : KnownBits);
129 }
130
131 /// Compute the number of known low bits of postOffset. If this block
132 /// contains inline asm, the number of known bits drops to the
133 /// instruction alignment. An aligned terminator may increase the number
134 /// of know bits.
135 unsigned postKnownBits() const {
136 return std::max(PostAlign, Unalign ? Unalign : KnownBits);
137 }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000138 };
139
140 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000141
Evan Chenga8e29892007-01-19 07:51:42 +0000142 /// WaterList - A sorted list of basic blocks where islands could be placed
143 /// (i.e. blocks that don't fall through to the following block, due
144 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +0000145 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +0000146
Bob Wilsonb9239532009-10-15 20:49:47 +0000147 /// NewWaterList - The subset of WaterList that was created since the
148 /// previous iteration by inserting unconditional branches.
149 SmallSet<MachineBasicBlock*, 4> NewWaterList;
150
Bob Wilson034de5f2009-10-12 18:52:13 +0000151 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
152
Evan Chenga8e29892007-01-19 07:51:42 +0000153 /// CPUser - One user of a constant pool, keeping the machine instruction
154 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000155 /// allowed from the instruction to the CP. The HighWaterMark records the
156 /// highest basic block where a new CPEntry can be placed. To ensure this
157 /// pass terminates, the CP entries are initially placed at the end of the
158 /// function and then move monotonically to lower addresses. The
159 /// exception to this rule is when the current CP entry for a particular
160 /// CPUser is out of range, but there is another CP entry for the same
161 /// constant value in range. We want to use the existing in-range CP
162 /// entry, but if it later moves out of range, the search for new water
163 /// should resume where it left off. The HighWaterMark is used to record
164 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000165 struct CPUser {
166 MachineInstr *MI;
167 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000168 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000169 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000170 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000171 bool IsSoImm;
172 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
173 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000174 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
175 HighWaterMark = CPEMI->getParent();
176 }
Evan Chenga8e29892007-01-19 07:51:42 +0000177 };
Bob Wilson84945262009-05-12 17:09:30 +0000178
Evan Chenga8e29892007-01-19 07:51:42 +0000179 /// CPUsers - Keep track of all of the machine instructions that use various
180 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000181 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000182
Evan Chengc99ef082007-02-09 20:54:44 +0000183 /// CPEntry - One per constant pool entry, keeping the machine instruction
184 /// pointer, the constpool index, and the number of CPUser's which
185 /// reference this entry.
186 struct CPEntry {
187 MachineInstr *CPEMI;
188 unsigned CPI;
189 unsigned RefCount;
190 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
191 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
192 };
193
194 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000195 /// instructions. For each original constpool index (i.e. those that
196 /// existed upon entry to this pass), it keeps a vector of entries.
197 /// Original elements are cloned as we go along; the clones are
198 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000199 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000200
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000201 /// ImmBranch - One per immediate branch, keeping the machine instruction
202 /// pointer, conditional or unconditional, the max displacement,
203 /// and (if isCond is true) the corresponding unconditional branch
204 /// opcode.
205 struct ImmBranch {
206 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000207 unsigned MaxDisp : 31;
208 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000209 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000210 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
211 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000212 };
213
Evan Cheng2706f972007-05-16 05:14:06 +0000214 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000215 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000216 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000217
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000218 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
219 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000220 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000221
Evan Cheng5657c012009-07-29 02:18:14 +0000222 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
223 SmallVector<MachineInstr*, 4> T2JumpTables;
224
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000225 /// HasFarJump - True if any far jump instruction has been emitted during
226 /// the branch fix up pass.
227 bool HasFarJump;
228
Chris Lattner20628752010-07-22 21:27:00 +0000229 const ARMInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000230 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000231 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000232 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000233 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000234 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000235 public:
Devang Patel19974732007-05-03 01:11:54 +0000236 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000237 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000238
Evan Cheng5657c012009-07-29 02:18:14 +0000239 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000240
241 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000242 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000243 }
Bob Wilson84945262009-05-12 17:09:30 +0000244
Evan Chenga8e29892007-01-19 07:51:42 +0000245 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000246 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000247 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000248 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jim Grosbach80697d12009-11-12 17:25:07 +0000249 void JumpTableFunctionScan(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000250 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000251 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000252 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000253 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000254 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
Evan Chenged884f32007-04-03 23:39:48 +0000255 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000256 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000257 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000258 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000259 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000260 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000261 void RemoveDeadCPEMI(MachineInstr *CPEMI);
262 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000263 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000264 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
265 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000266 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000267 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000268 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000269 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000270 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000271 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
272 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
273 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000274 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000275 bool OptimizeThumb2Instructions(MachineFunction &MF);
276 bool OptimizeThumb2Branches(MachineFunction &MF);
Jim Grosbach80697d12009-11-12 17:25:07 +0000277 bool ReorderThumb2JumpTables(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000278 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000279 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
280 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000281
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000282 void ComputeBlockSize(MachineBasicBlock *MBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000283 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000284 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000285 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000286 };
Devang Patel19974732007-05-03 01:11:54 +0000287 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000288}
289
Dale Johannesen8593e412007-04-29 19:19:30 +0000290/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000291void ARMConstantIslands::verify(MachineFunction &MF) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000292#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000293 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000294 MBBI != E; ++MBBI) {
295 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000296 unsigned Align = MBB->getAlignment();
297 unsigned MBBId = MBB->getNumber();
298 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
299 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000300 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000301 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
302 CPUser &U = CPUsers[i];
303 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000304 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
305 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
306 UserOffset - CPEOffset;
307 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000308 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000309#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000310}
311
312/// print block size and offset information - debugging
313void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000314 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000315 DEBUG(dbgs() << "block " << J << " offset " << BBInfo[J].Offset
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000316 << " size " << BBInfo[J].Size << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000317 }
318}
319
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000320/// createARMConstantIslandPass - returns an instance of the constpool
321/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000322FunctionPass *llvm::createARMConstantIslandPass() {
323 return new ARMConstantIslands();
324}
325
Evan Cheng5657c012009-07-29 02:18:14 +0000326bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
327 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000328
Chris Lattner20628752010-07-22 21:27:00 +0000329 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
Evan Cheng5657c012009-07-29 02:18:14 +0000330 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000331 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
332
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000333 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000334 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000335 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000336
337 HasFarJump = false;
338
Evan Chenga8e29892007-01-19 07:51:42 +0000339 // Renumber all of the machine basic blocks in the function, guaranteeing that
340 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000341 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000342
Jim Grosbach80697d12009-11-12 17:25:07 +0000343 // Try to reorder and otherwise adjust the block layout to make good use
344 // of the TB[BH] instructions.
345 bool MadeChange = false;
346 if (isThumb2 && AdjustJumpTableBlocks) {
347 JumpTableFunctionScan(MF);
348 MadeChange |= ReorderThumb2JumpTables(MF);
349 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000350 T2JumpTables.clear();
351 // Blocks may have shifted around. Keep the numbering up to date.
352 MF.RenumberBlocks();
353 }
354
Evan Chengd26b14c2009-07-31 18:28:05 +0000355 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000356 // This is so we can keep exact track of where the alignment padding goes.
357
Chris Lattner7d7dab02010-01-27 23:37:36 +0000358 // ARM and Thumb2 functions need to be 4-byte aligned.
359 if (!isThumb1)
360 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000361
Evan Chenga8e29892007-01-19 07:51:42 +0000362 // Perform the initial placement of the constant pool entries. To start with,
363 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000364 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000365 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000366 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000367 if (isThumb1)
Chris Lattner7d7dab02010-01-27 23:37:36 +0000368 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000369 }
Bob Wilson84945262009-05-12 17:09:30 +0000370
Evan Chenga8e29892007-01-19 07:51:42 +0000371 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000372 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000373
Evan Chenga8e29892007-01-19 07:51:42 +0000374 // Do the initial scan of the function, building up information about the
375 // sizes of each block, the location of all the water, and finding all of the
376 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000377 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000378 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000379 DEBUG(dumpBBs());
380
Bob Wilson84945262009-05-12 17:09:30 +0000381
Evan Chenged884f32007-04-03 23:39:48 +0000382 /// Remove dead constant pool entries.
Bill Wendlingcd080242010-12-18 01:53:06 +0000383 MadeChange |= RemoveUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000384
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000385 // Iteratively place constant pool entries and fix up branches until there
386 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000387 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000388 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000389 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000390 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000391 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000392 CPChange |= HandleConstantPoolUser(MF, i);
393 if (CPChange && ++NoCPIters > 30)
394 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000395 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000396
Bob Wilsonb9239532009-10-15 20:49:47 +0000397 // Clear NewWaterList now. If we split a block for branches, it should
398 // appear as "new water" for the next iteration of constant pool placement.
399 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000400
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000401 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000402 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000403 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000404 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
405 if (BRChange && ++NoBRIters > 30)
406 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000407 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000408
409 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000410 break;
411 MadeChange = true;
412 }
Evan Chenged884f32007-04-03 23:39:48 +0000413
Evan Chenga1efbbd2009-08-14 00:32:16 +0000414 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000415 if (isThumb2 && !STI->prefers32BitThumb())
Evan Chenga1efbbd2009-08-14 00:32:16 +0000416 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000417
Dale Johannesen8593e412007-04-29 19:19:30 +0000418 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000419 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000420
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000421 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
422 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000423 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000424 MadeChange |= UndoLRSpillRestore();
425
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000426 // Save the mapping between original and cloned constpool entries.
427 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
428 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
429 const CPEntry & CPE = CPEntries[i][j];
430 AFI->recordCPEClone(i, CPE.CPI);
431 }
432 }
433
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000434 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000435
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000436 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000437 WaterList.clear();
438 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000439 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000440 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000441 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000442 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000443
444 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000445}
446
447/// DoInitialPlacement - Perform the initial placement of the constant pool
448/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000449void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000450 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000451 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000452 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
453 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000454
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000455 // Mark the basic block as 4-byte aligned as required by the const-pool.
456 BB->setAlignment(2);
457
Evan Chenga8e29892007-01-19 07:51:42 +0000458 // Add all of the constants from the constant pool to the end block, use an
459 // identity mapping of CPI's to CPE's.
460 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000461 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000462
Evan Cheng5657c012009-07-29 02:18:14 +0000463 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000464 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000465 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000466 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
467 // we would have to pad them out or something so that instructions stay
468 // aligned.
469 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
470 MachineInstr *CPEMI =
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000471 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
472 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000473 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000474
475 // Add a new CPEntry, but no corresponding CPUser yet.
476 std::vector<CPEntry> CPEs;
477 CPEs.push_back(CPEntry(CPEMI, i));
478 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000479 ++NumCPEs;
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000480 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function as #" << i
Chris Lattner893e1c92009-08-23 06:49:22 +0000481 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000482 }
483}
484
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000485/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000486/// into the block immediately after it.
487static bool BBHasFallthrough(MachineBasicBlock *MBB) {
488 // Get the next machine basic block in the function.
489 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000490 // Can't fall off end of function.
491 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000492 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000493
Chris Lattner7896c9f2009-12-03 00:50:42 +0000494 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000495 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
496 E = MBB->succ_end(); I != E; ++I)
497 if (*I == NextBB)
498 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000499
Evan Chenga8e29892007-01-19 07:51:42 +0000500 return false;
501}
502
Evan Chengc99ef082007-02-09 20:54:44 +0000503/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
504/// look up the corresponding CPEntry.
505ARMConstantIslands::CPEntry
506*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
507 const MachineInstr *CPEMI) {
508 std::vector<CPEntry> &CPEs = CPEntries[CPI];
509 // Number of entries per constpool index should be small, just do a
510 // linear search.
511 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
512 if (CPEs[i].CPEMI == CPEMI)
513 return &CPEs[i];
514 }
515 return NULL;
516}
517
Jim Grosbach80697d12009-11-12 17:25:07 +0000518/// JumpTableFunctionScan - Do a scan of the function, building up
519/// information about the sizes of each block and the locations of all
520/// the jump tables.
521void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
Jim Grosbach80697d12009-11-12 17:25:07 +0000522 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
523 MBBI != E; ++MBBI) {
524 MachineBasicBlock &MBB = *MBBI;
525
Jim Grosbach80697d12009-11-12 17:25:07 +0000526 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000527 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000528 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000529 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000530 }
531}
532
Evan Chenga8e29892007-01-19 07:51:42 +0000533/// InitialFunctionScan - Do the initial scan of the function, building up
534/// information about the sizes of each block, the location of all the water,
535/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000536void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000537 const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000538 BBInfo.clear();
539 BBInfo.resize(MF.getNumBlockIDs());
540
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000541 // First thing, compute the size of all basic blocks, and see if the function
542 // has any inline assembly in it. If so, we have to be conservative about
543 // alignment assumptions, as we don't know for sure the size of any
544 // instructions in the inline assembly.
545 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
546 ComputeBlockSize(I);
547
548 // The known bits of the entry block offset are determined by the function
549 // alignment.
550 BBInfo.front().KnownBits = MF.getAlignment();
551
552 // Compute block offsets and known bits.
553 AdjustBBOffsetsAfter(MF.begin());
554
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000555 // Now go back through the instructions and build up our data structures.
Evan Cheng5657c012009-07-29 02:18:14 +0000556 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000557 MBBI != E; ++MBBI) {
558 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000559
Evan Chenga8e29892007-01-19 07:51:42 +0000560 // If this block doesn't fall through into the next MBB, then this is
561 // 'water' that a constant pool island could be placed.
562 if (!BBHasFallthrough(&MBB))
563 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000564
Evan Chenga8e29892007-01-19 07:51:42 +0000565 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
566 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000567 if (I->isDebugValue())
568 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000569
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000570 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000571 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000572 bool isCond = false;
573 unsigned Bits = 0;
574 unsigned Scale = 1;
575 int UOpc = Opc;
576 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000577 default:
578 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000579 case ARM::t2BR_JT:
580 T2JumpTables.push_back(I);
581 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000582 case ARM::Bcc:
583 isCond = true;
584 UOpc = ARM::B;
585 // Fallthrough
586 case ARM::B:
587 Bits = 24;
588 Scale = 4;
589 break;
590 case ARM::tBcc:
591 isCond = true;
592 UOpc = ARM::tB;
593 Bits = 8;
594 Scale = 2;
595 break;
596 case ARM::tB:
597 Bits = 11;
598 Scale = 2;
599 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000600 case ARM::t2Bcc:
601 isCond = true;
602 UOpc = ARM::t2B;
603 Bits = 20;
604 Scale = 2;
605 break;
606 case ARM::t2B:
607 Bits = 24;
608 Scale = 2;
609 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000610 }
Evan Chengb43216e2007-02-01 10:16:15 +0000611
612 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000613 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000614 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000615 }
616
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000617 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
618 PushPopMIs.push_back(I);
619
Evan Chengd3d9d662009-07-23 18:27:47 +0000620 if (Opc == ARM::CONSTPOOL_ENTRY)
621 continue;
622
Evan Chenga8e29892007-01-19 07:51:42 +0000623 // Scan the instructions for constant pool operands.
624 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000625 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000626 // We found one. The addressing mode tells us the max displacement
627 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000628
Evan Chenga8e29892007-01-19 07:51:42 +0000629 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000630 unsigned Bits = 0;
631 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000632 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000633 bool IsSoImm = false;
634
635 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000636 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000637 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000638 break;
639
640 // Taking the address of a CP entry.
641 case ARM::LEApcrel:
642 // This takes a SoImm, which is 8 bit immediate rotated. We'll
643 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000644 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000645 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000646 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000647 Scale = 4;
648 NegOk = true;
649 IsSoImm = true;
650 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000651 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000652 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000653 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000654 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000655 case ARM::tLEApcrel:
656 Bits = 8;
657 Scale = 4;
658 break;
659
Jim Grosbach3e556122010-10-26 22:37:02 +0000660 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000661 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000662 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000663 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000664 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000665 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000666
667 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000668 Bits = 8;
669 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000670 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000671
Jim Grosbache5165492009-11-09 00:11:35 +0000672 case ARM::VLDRD:
673 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000674 Bits = 8;
675 Scale = 4; // +-(offset_8*4)
676 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000677 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000678 }
Evan Chengb43216e2007-02-01 10:16:15 +0000679
Evan Chenga8e29892007-01-19 07:51:42 +0000680 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000681 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000682 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000683 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000684 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000685
686 // Increment corresponding CPEntry reference count.
687 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
688 assert(CPE && "Cannot find a corresponding CPEntry!");
689 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000690
Evan Chenga8e29892007-01-19 07:51:42 +0000691 // Instructions can only use one CP entry, don't bother scanning the
692 // rest of the operands.
693 break;
694 }
695 }
Evan Chenga8e29892007-01-19 07:51:42 +0000696 }
697}
698
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000699/// ComputeBlockSize - Compute the size and some alignment information for MBB.
700/// This function updates BBInfo directly.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000701void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000702 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
703 BBI.Size = 0;
704 BBI.Unalign = 0;
705 BBI.PostAlign = 0;
706
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000707 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
708 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000709 BBI.Size += TII->GetInstSizeInBytes(I);
710 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
711 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000712 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000713 BBI.Unalign = isThumb ? 1 : 2;
714 }
715
716 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000717 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000718 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000719 MBB->getParent()->EnsureAlignment(2);
720 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000721}
722
Evan Chenga8e29892007-01-19 07:51:42 +0000723/// GetOffsetOf - Return the current offset of the specified machine instruction
724/// from the start of the function. This offset changes as stuff is moved
725/// around inside the function.
726unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
727 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000728
Evan Chenga8e29892007-01-19 07:51:42 +0000729 // The offset is composed of two things: the sum of the sizes of all MBB's
730 // before this instruction's block, and the offset from the start of the block
731 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000732 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000733
734 // Sum instructions before MI in MBB.
735 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
736 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
737 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000738 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000739 }
740}
741
742/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
743/// ID.
744static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
745 const MachineBasicBlock *RHS) {
746 return LHS->getNumber() < RHS->getNumber();
747}
748
749/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
750/// machine function, it upsets all of the block numbers. Renumber the blocks
751/// and update the arrays that parallel this numbering.
752void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000753 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000754 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000755
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000756 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000757 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000758 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000759
760 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000761 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000762 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000763 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
764 CompareMBBNumbers);
765 WaterList.insert(IP, NewBB);
766}
767
768
769/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000770/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000771/// account for this change and returns the newly created block.
772MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000773 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000774 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000775
776 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000777 MachineBasicBlock *NewBB =
778 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000779 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000780 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000781
Evan Chenga8e29892007-01-19 07:51:42 +0000782 // Splice the instructions starting with MI over to NewBB.
783 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000784
Evan Chenga8e29892007-01-19 07:51:42 +0000785 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000786 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000787 // There doesn't seem to be meaningful DebugInfo available; this doesn't
788 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000789 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000790 if (!isThumb)
791 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
792 else
793 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
794 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000795 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000796
Evan Chenga8e29892007-01-19 07:51:42 +0000797 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000798 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000799
Evan Chenga8e29892007-01-19 07:51:42 +0000800 // OrigBB branches to NewBB.
801 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000802
Evan Chenga8e29892007-01-19 07:51:42 +0000803 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000804 // This is almost the same as UpdateForInsertedWaterBlock, except that
805 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000806 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000807
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000808 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000809 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000810 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000811
Bob Wilson84945262009-05-12 17:09:30 +0000812 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000813 // available water after it (but not if it's already there, which happens
814 // when splitting before a conditional branch that is followed by an
815 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000816 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000817 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
818 CompareMBBNumbers);
819 MachineBasicBlock* WaterBB = *IP;
820 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000821 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000822 else
823 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000824 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000825
Dale Johannesen8086d582010-07-23 22:50:23 +0000826 // Figure out how large the OrigBB is. As the first half of the original
827 // block, it cannot contain a tablejump. The size includes
828 // the new jump we added. (It should be possible to do this without
829 // recounting everything, but it's very confusing, and this is rarely
830 // executed.)
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000831 ComputeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000832
Dale Johannesen8086d582010-07-23 22:50:23 +0000833 // Figure out how large the NewMBB is. As the second half of the original
834 // block, it may contain a tablejump.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000835 ComputeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000836
Dale Johannesen99c49a42007-02-25 00:47:03 +0000837 // All BBOffsets following these blocks must be modified.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000838 AdjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000839
840 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000841}
842
Dale Johannesen8593e412007-04-29 19:19:30 +0000843/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000844/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000845/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000846bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000847 unsigned TrialOffset, unsigned MaxDisp,
848 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000849 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
850 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000851 // Effectively, the valid range of displacements is 2 bytes smaller for such
852 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000853 unsigned TotalAdj = 0;
854 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000855 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000856 TotalAdj = 2;
857 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000858 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000859 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000860 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000861 TotalAdj += 2;
862 }
863
864 // In Thumb2 mode, later branch adjustments can shift instructions up and
865 // cause alignment change. In the worst case scenario this can cause the
866 // user's effective address to be subtracted by 2 and the CPE's address to
867 // be plus 2.
868 if (isThumb2 && TotalAdj != 4)
869 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000870
Dale Johannesen99c49a42007-02-25 00:47:03 +0000871 if (UserOffset <= TrialOffset) {
872 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000873 if (TrialOffset - UserOffset <= MaxDisp)
874 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000875 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000876 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000877 if (UserOffset - TrialOffset <= MaxDisp)
878 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000879 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000880 }
881 return false;
882}
883
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000884/// WaterIsInRange - Returns true if a CPE placed after the specified
885/// Water (a basic block) will be in range for the specific MI.
886
887bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000888 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000889 unsigned MaxDisp = U.MaxDisp;
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000890 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000891
Dale Johannesend959aa42007-04-02 20:31:06 +0000892 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000893 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000894 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000895 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000896
Evan Chengd3d9d662009-07-23 18:27:47 +0000897 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000898}
899
900/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000901/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000902bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000903 MachineInstr *CPEMI, unsigned MaxDisp,
904 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000905 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000906 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000907
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000908 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000909 DEBUG({
910 unsigned Block = MI->getParent()->getNumber();
911 const BasicBlockInfo &BBI = BBInfo[Block];
912 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
913 << " max delta=" << MaxDisp
914 << " insn address=" << UserOffset
915 << " in BB#" << Block << ": "
916 << BBI.Offset << " - " << BBI.postOffset() << "\t" << *MI
917 << "CPE address=" << CPEOffset
918 << " offset=" << int(CPEOffset-UserOffset) << ": ";
919 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000920 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000921
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000922 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000923}
924
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000925#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000926/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
927/// unconditionally branches to its only successor.
928static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
929 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
930 return false;
931
932 MachineBasicBlock *Succ = *MBB->succ_begin();
933 MachineBasicBlock *Pred = *MBB->pred_begin();
934 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000935 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
936 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000937 return PredMI->getOperand(0).getMBB() == Succ;
938 return false;
939}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000940#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000941
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000942void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000943 MachineFunction *MF = BB->getParent();
944 for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
945 // Get the offset and known bits at the end of the layout predecessor.
946 unsigned Offset = BBInfo[i - 1].postOffset();
947 unsigned KnownBits = BBInfo[i - 1].postKnownBits();
948
949 // Add padding before an aligned block. This may teach us more bits.
950 if (unsigned Align = MF->getBlockNumbered(i)->getAlignment()) {
951 Offset = WorstCaseAlign(Offset, Align, KnownBits);
952 KnownBits = std::max(KnownBits, Align);
Dale Johannesen8593e412007-04-29 19:19:30 +0000953 }
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000954
955 // This is where block i begins.
956 BBInfo[i].Offset = Offset;
957 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +0000958 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000959}
960
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000961/// DecrementOldEntry - find the constant pool entry with index CPI
962/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000963/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000964/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000965
Evan Chenged884f32007-04-03 23:39:48 +0000966bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000967 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000968 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
969 assert(CPE && "Unexpected!");
970 if (--CPE->RefCount == 0) {
971 RemoveDeadCPEMI(CPEMI);
972 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +0000973 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000974 return true;
975 }
976 return false;
977}
978
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000979/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
980/// if not, see if an in-range clone of the CPE is in range, and if so,
981/// change the data structures so the user references the clone. Returns:
982/// 0 = no existing entry found
983/// 1 = entry found, and there were no code insertions or deletions
984/// 2 = entry found, and there were code insertions or deletions
985int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
986{
987 MachineInstr *UserMI = U.MI;
988 MachineInstr *CPEMI = U.CPEMI;
989
990 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000991 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000992 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000993 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000994 }
995
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000996 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000997 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000998 std::vector<CPEntry> &CPEs = CPEntries[CPI];
999 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1000 // We already tried this one
1001 if (CPEs[i].CPEMI == CPEMI)
1002 continue;
1003 // Removing CPEs can leave empty entries, skip
1004 if (CPEs[i].CPEMI == NULL)
1005 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001006 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001007 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001008 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001009 // Point the CPUser node to the replacement
1010 U.CPEMI = CPEs[i].CPEMI;
1011 // Change the CPI in the instruction operand to refer to the clone.
1012 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001013 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001014 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001015 break;
1016 }
1017 // Adjust the refcount of the clone...
1018 CPEs[i].RefCount++;
1019 // ...and the original. If we didn't remove the old entry, none of the
1020 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001021 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001022 }
1023 }
1024 return 0;
1025}
1026
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001027/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1028/// the specific unconditional branch instruction.
1029static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001030 switch (Opc) {
1031 case ARM::tB:
1032 return ((1<<10)-1)*2;
1033 case ARM::t2B:
1034 return ((1<<23)-1)*2;
1035 default:
1036 break;
1037 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001038
David Goodwin5e47a9a2009-06-30 18:04:13 +00001039 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001040}
1041
Bob Wilsonb9239532009-10-15 20:49:47 +00001042/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001043/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001044/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001045/// is set to the WaterList entry. For Thumb, prefer water that will not
1046/// introduce padding to water that will. To ensure that this pass
1047/// terminates, the CPE location for a particular CPUser is only allowed to
1048/// move to a lower address, so search backward from the end of the list and
1049/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001050bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001051 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001052 if (WaterList.empty())
1053 return false;
1054
Bob Wilson32c50e82009-10-12 20:45:53 +00001055 bool FoundWaterThatWouldPad = false;
1056 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001057 for (water_iterator IP = prior(WaterList.end()),
1058 B = WaterList.begin();; --IP) {
1059 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001060 // Check if water is in range and is either at a lower address than the
1061 // current "high water mark" or a new water block that was created since
1062 // the previous iteration by inserting an unconditional branch. In the
1063 // latter case, we want to allow resetting the high water mark back to
1064 // this new water since we haven't seen it before. Inserting branches
1065 // should be relatively uncommon and when it does happen, we want to be
1066 // sure to take advantage of it for all the CPEs near that block, so that
1067 // we don't insert more branches than necessary.
1068 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1069 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1070 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001071 unsigned WBBId = WaterBB->getNumber();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001072 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
Bob Wilson3b757352009-10-12 19:04:03 +00001073 // This is valid Water, but would introduce padding. Remember
1074 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001075 if (!FoundWaterThatWouldPad) {
1076 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001077 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001078 }
Bob Wilson3b757352009-10-12 19:04:03 +00001079 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001080 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001081 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001082 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001083 }
Bob Wilson3b757352009-10-12 19:04:03 +00001084 if (IP == B)
1085 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001086 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001087 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001088 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001089 return true;
1090 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001091 return false;
1092}
1093
Bob Wilson84945262009-05-12 17:09:30 +00001094/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001095/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1096/// block is used if in range, and the conditional branch munged so control
1097/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001098/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001099/// block following which the new island can be inserted (the WaterList
1100/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001101void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001102 unsigned UserOffset,
1103 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001104 CPUser &U = CPUsers[CPUserIndex];
1105 MachineInstr *UserMI = U.MI;
1106 MachineInstr *CPEMI = U.CPEMI;
1107 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001108 unsigned OffsetOfNextBlock = BBInfo[UserMBB->getNumber()].postOffset();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001109
Bob Wilson36fa5322009-10-15 05:10:36 +00001110 // If the block does not end in an unconditional branch already, and if the
1111 // end of the block is within range, make new water there. (The addition
1112 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1113 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001114 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001115 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001116 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1117 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001118 DEBUG(dbgs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001119 if (&UserMBB->back() == UserMI)
1120 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001121 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001122 // Add an unconditional branch from UserMBB to fallthrough block.
1123 // Record it for branch lengthening; this new branch will not get out of
1124 // range, but if the preceding conditional branch is out of range, the
1125 // targets will be exchanged, and the altered branch may be out of
1126 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001127 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001128 if (!isThumb)
1129 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1130 else
1131 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1132 .addImm(ARMCC::AL).addReg(0);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001133 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001134 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001135 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001136 int delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001137 BBInfo[UserMBB->getNumber()].Size += delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001138 AdjustBBOffsetsAfter(UserMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001139 } else {
1140 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001141 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001142 // and constant pool entries are 4 bytes: if instruction I references
1143 // island CPE, and instruction I+1 references CPE', it will
1144 // not work well to put CPE as far forward as possible, since then
1145 // CPE' cannot immediately follow it (that location is 2 bytes
1146 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001147 // a new island. So, we make a first guess, then walk through the
1148 // instructions between the one currently being looked at and the
1149 // possible insertion point, and make sure any other instructions
1150 // that reference CPEs will be able to use the same island area;
1151 // if not, we back up the insertion point.
1152
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001153 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001154 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001155 // island is handled inside OffsetIsInRange.
1156 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001157 // This could point off the end of the block if we've already got
1158 // constant pool entries following this block; only the last one is
1159 // in the water list. Back past any possible branches (allow for a
1160 // conditional and a maximally long unconditional).
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001161 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1162 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
Evan Chengd3d9d662009-07-23 18:27:47 +00001163 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001164 unsigned EndInsertOffset = BaseInsertOffset +
1165 CPEMI->getOperand(2).getImm();
1166 MachineBasicBlock::iterator MI = UserMI;
1167 ++MI;
1168 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001169 unsigned NumCPUsers = CPUsers.size();
1170 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001171 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001172 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001173 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001174 MI = llvm::next(MI)) {
1175 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001176 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001177 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001178 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1179 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1180 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001181 }
1182 // This is overly conservative, as we don't account for CPEMIs
1183 // being reused within the block, but it doesn't matter much.
1184 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1185 CPUIndex++;
1186 }
Evan Cheng719510a2010-08-12 20:30:05 +00001187
1188 // Remember the last IT instruction.
1189 if (MI->getOpcode() == ARM::t2IT)
1190 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001191 }
Evan Cheng719510a2010-08-12 20:30:05 +00001192
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001193 DEBUG(dbgs() << "Split in middle of big block\n");
Evan Cheng719510a2010-08-12 20:30:05 +00001194 --MI;
1195
1196 // Avoid splitting an IT block.
1197 if (LastIT) {
1198 unsigned PredReg = 0;
1199 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1200 if (CC != ARMCC::AL)
1201 MI = LastIT;
1202 }
1203 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001204 }
1205}
1206
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001207/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001208/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001209/// place in-range. Return true if we changed any addresses (thus must run
1210/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001211bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001212 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001213 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001214 MachineInstr *UserMI = U.MI;
1215 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001216 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001217 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001218 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001219 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001220 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001221
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001222 // See if the current entry is within range, or there is a clone of it
1223 // in range.
1224 int result = LookForExistingCPEntry(U, UserOffset);
1225 if (result==1) return false;
1226 else if (result==2) return true;
1227
1228 // No existing clone of this CPE is within range.
1229 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001230 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001231
Bob Wilsonf98032e2009-10-12 21:23:15 +00001232 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001233 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1234 MachineBasicBlock *NewMBB;
1235 water_iterator IP;
1236 if (LookForWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001237 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001238 MachineBasicBlock *WaterBB = *IP;
1239
1240 // If the original WaterList entry was "new water" on this iteration,
1241 // propagate that to the new island. This is just keeping NewWaterList
1242 // updated to match the WaterList, which will be updated below.
1243 if (NewWaterList.count(WaterBB)) {
1244 NewWaterList.erase(WaterBB);
1245 NewWaterList.insert(NewIsland);
1246 }
1247 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001248 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001249
1250 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001251 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001252 DEBUG(dbgs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001253 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001254
1255 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1256 // called while handling branches so that the water will be seen on the
1257 // next iteration for constant pools, but in this context, we don't want
1258 // it. Check for this so it will be removed from the WaterList.
1259 // Also remove any entry from NewWaterList.
1260 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1261 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1262 if (IP != WaterList.end())
1263 NewWaterList.erase(WaterBB);
1264
1265 // We are adding new water. Update NewWaterList.
1266 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001267 }
1268
Bob Wilsonb9239532009-10-15 20:49:47 +00001269 // Remove the original WaterList entry; we want subsequent insertions in
1270 // this vicinity to go after the one we're about to insert. This
1271 // considerably reduces the number of times we have to move the same CPE
1272 // more than once and is also important to ensure the algorithm terminates.
1273 if (IP != WaterList.end())
1274 WaterList.erase(IP);
1275
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001276 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001277 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001278
1279 // Update internal data structures to account for the newly inserted MBB.
1280 UpdateForInsertedWaterBlock(NewIsland);
1281
1282 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001283 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001284
1285 // Now that we have an island to add the CPE to, clone the original CPE and
1286 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001287 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001288 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001289 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001290 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001291 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001292
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001293 // Mark the basic block as 4-byte aligned as required by the const-pool entry.
1294 NewIsland->setAlignment(2);
1295
Evan Chenga8e29892007-01-19 07:51:42 +00001296 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001297 BBInfo[NewIsland->getNumber()].Size += Size;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001298 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001299
Evan Chenga8e29892007-01-19 07:51:42 +00001300 // Finally, change the CPI in the instruction operand to be ID.
1301 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001302 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001303 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001304 break;
1305 }
Bob Wilson84945262009-05-12 17:09:30 +00001306
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001307 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1308 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001309
Evan Chenga8e29892007-01-19 07:51:42 +00001310 return true;
1311}
1312
Evan Chenged884f32007-04-03 23:39:48 +00001313/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1314/// sizes and offsets of impacted basic blocks.
1315void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1316 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001317 unsigned Size = CPEMI->getOperand(2).getImm();
1318 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001319 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001320 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001321 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001322 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001323 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001324 // empty, so fix this.
1325 // All succeeding offsets have the current size value added in, fix this.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001326 if (BBInfo[CPEBB->getNumber()].Size != 0) {
1327 Size += BBInfo[CPEBB->getNumber()].Size;
1328 BBInfo[CPEBB->getNumber()].Size = 0;
Evan Chenged884f32007-04-03 23:39:48 +00001329 }
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001330
1331 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1332 CPEBB->setAlignment(0);
Evan Chenged884f32007-04-03 23:39:48 +00001333 }
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001334 AdjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001335 // An island has only one predecessor BB and one successor BB. Check if
1336 // this BB's predecessor jumps directly to this BB's successor. This
1337 // shouldn't happen currently.
1338 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1339 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001340}
1341
1342/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1343/// are zero.
1344bool ARMConstantIslands::RemoveUnusedCPEntries() {
1345 unsigned MadeChange = false;
1346 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1347 std::vector<CPEntry> &CPEs = CPEntries[i];
1348 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1349 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1350 RemoveDeadCPEMI(CPEs[j].CPEMI);
1351 CPEs[j].CPEMI = NULL;
1352 MadeChange = true;
1353 }
1354 }
Bob Wilson84945262009-05-12 17:09:30 +00001355 }
Evan Chenged884f32007-04-03 23:39:48 +00001356 return MadeChange;
1357}
1358
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001359/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001360/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001361bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1362 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001363 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001364 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001365 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001366
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001367 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001368 << " from BB#" << MI->getParent()->getNumber()
1369 << " max delta=" << MaxDisp
1370 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1371 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001372
Dale Johannesen8593e412007-04-29 19:19:30 +00001373 if (BrOffset <= DestOffset) {
1374 // Branch before the Dest.
1375 if (DestOffset-BrOffset <= MaxDisp)
1376 return true;
1377 } else {
1378 if (BrOffset-DestOffset <= MaxDisp)
1379 return true;
1380 }
1381 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001382}
1383
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001384/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1385/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001386bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001387 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001388 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001389
Evan Chengc0dbec72007-01-31 19:57:44 +00001390 // Check to see if the DestBB is already in-range.
1391 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001392 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001393
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001394 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001395 return FixUpUnconditionalBr(MF, Br);
1396 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001397}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001398
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001399/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1400/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001401/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001402/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001403bool
Evan Cheng5657c012009-07-29 02:18:14 +00001404ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001405 MachineInstr *MI = Br.MI;
1406 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001407 if (!isThumb1)
1408 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001409
1410 // Use BL to implement far jump.
1411 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001412 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001413 BBInfo[MBB->getNumber()].Size += 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001414 AdjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001415 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001416 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001417
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001418 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001419
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001420 return true;
1421}
1422
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001423/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001424/// far away to fit in its displacement field. It is converted to an inverse
1425/// conditional branch + an unconditional branch to the destination.
1426bool
Evan Cheng5657c012009-07-29 02:18:14 +00001427ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001428 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001429 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001430
Bob Wilson39bf0512009-05-12 17:35:29 +00001431 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001432 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001433 // blt L1
1434 // =>
1435 // bge L2
1436 // b L1
1437 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001438 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001439 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001440 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001441
1442 // If the branch is at the end of its MBB and that has a fall-through block,
1443 // direct the updated conditional branch to the fall-through block. Otherwise,
1444 // split the MBB before the next instruction.
1445 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001446 MachineInstr *BMI = &MBB->back();
1447 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001448
Dan Gohmanfe601042010-06-22 15:08:57 +00001449 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001450 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001451 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001452 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001453 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001454 // condition and swap destinations:
1455 // beq L1
1456 // b L2
1457 // =>
1458 // bne L2
1459 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001460 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001461 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001462 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001463 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001464 BMI->getOperand(0).setMBB(DestBB);
1465 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001466 MI->getOperand(1).setImm(CC);
1467 return true;
1468 }
1469 }
1470 }
1471
1472 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001473 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001474 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001475 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001476 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001477 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001478 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001479 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001480 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001481 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001482
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001483 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001484 << " also invert condition and change dest. to BB#"
1485 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001486
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001487 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001488 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001489 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001490 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001491 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001492 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001493 if (isThumb)
1494 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1495 .addImm(ARMCC::AL).addReg(0);
1496 else
1497 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001498 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001499 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001500 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001501
1502 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001503 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001504 MI->eraseFromParent();
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001505 AdjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001506 return true;
1507}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001508
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001509/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001510/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1511/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001512bool ARMConstantIslands::UndoLRSpillRestore() {
1513 bool MadeChange = false;
1514 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1515 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001516 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001517 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001518 MI->getOperand(2).getReg() == ARM::PC &&
1519 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001520 // Create the new insn and copy the predicate from the old.
1521 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1522 .addOperand(MI->getOperand(0))
1523 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001524 MI->eraseFromParent();
1525 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001526 }
1527 }
1528 return MadeChange;
1529}
Evan Cheng5657c012009-07-29 02:18:14 +00001530
Evan Chenga1efbbd2009-08-14 00:32:16 +00001531bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1532 bool MadeChange = false;
1533
1534 // Shrink ADR and LDR from constantpool.
1535 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1536 CPUser &U = CPUsers[i];
1537 unsigned Opcode = U.MI->getOpcode();
1538 unsigned NewOpc = 0;
1539 unsigned Scale = 1;
1540 unsigned Bits = 0;
1541 switch (Opcode) {
1542 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001543 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001544 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1545 NewOpc = ARM::tLEApcrel;
1546 Bits = 8;
1547 Scale = 4;
1548 }
1549 break;
1550 case ARM::t2LDRpci:
1551 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1552 NewOpc = ARM::tLDRpci;
1553 Bits = 8;
1554 Scale = 4;
1555 }
1556 break;
1557 }
1558
1559 if (!NewOpc)
1560 continue;
1561
1562 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1563 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1564 // FIXME: Check if offset is multiple of scale if scale is not 4.
1565 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1566 U.MI->setDesc(TII->get(NewOpc));
1567 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001568 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001569 AdjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001570 ++NumT2CPShrunk;
1571 MadeChange = true;
1572 }
1573 }
1574
Evan Chenga1efbbd2009-08-14 00:32:16 +00001575 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001576 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001577 return MadeChange;
1578}
1579
1580bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001581 bool MadeChange = false;
1582
1583 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1584 ImmBranch &Br = ImmBranches[i];
1585 unsigned Opcode = Br.MI->getOpcode();
1586 unsigned NewOpc = 0;
1587 unsigned Scale = 1;
1588 unsigned Bits = 0;
1589 switch (Opcode) {
1590 default: break;
1591 case ARM::t2B:
1592 NewOpc = ARM::tB;
1593 Bits = 11;
1594 Scale = 2;
1595 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001596 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001597 NewOpc = ARM::tBcc;
1598 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001599 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001600 break;
1601 }
Evan Chengde17fb62009-10-31 23:46:45 +00001602 }
1603 if (NewOpc) {
1604 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1605 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1606 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1607 Br.MI->setDesc(TII->get(NewOpc));
1608 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001609 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001610 AdjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001611 ++NumT2BrShrunk;
1612 MadeChange = true;
1613 }
1614 }
1615
1616 Opcode = Br.MI->getOpcode();
1617 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001618 continue;
1619
Evan Chengde17fb62009-10-31 23:46:45 +00001620 NewOpc = 0;
1621 unsigned PredReg = 0;
1622 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1623 if (Pred == ARMCC::EQ)
1624 NewOpc = ARM::tCBZ;
1625 else if (Pred == ARMCC::NE)
1626 NewOpc = ARM::tCBNZ;
1627 if (!NewOpc)
1628 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001629 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001630 // Check if the distance is within 126. Subtract starting offset by 2
1631 // because the cmp will be eliminated.
1632 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001633 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001634 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001635 MachineBasicBlock::iterator CmpMI = Br.MI;
1636 if (CmpMI != Br.MI->getParent()->begin()) {
1637 --CmpMI;
1638 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1639 unsigned Reg = CmpMI->getOperand(0).getReg();
1640 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1641 if (Pred == ARMCC::AL &&
1642 CmpMI->getOperand(1).getImm() == 0 &&
1643 isARMLowRegister(Reg)) {
1644 MachineBasicBlock *MBB = Br.MI->getParent();
1645 MachineInstr *NewBR =
1646 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1647 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1648 CmpMI->eraseFromParent();
1649 Br.MI->eraseFromParent();
1650 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001651 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001652 AdjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001653 ++NumCBZ;
1654 MadeChange = true;
1655 }
Evan Chengde17fb62009-10-31 23:46:45 +00001656 }
1657 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001658 }
1659 }
1660
1661 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001662}
1663
Evan Chenga1efbbd2009-08-14 00:32:16 +00001664/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1665/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001666bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1667 bool MadeChange = false;
1668
1669 // FIXME: After the tables are shrunk, can we get rid some of the
1670 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001671 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001672 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001673
Evan Cheng5657c012009-07-29 02:18:14 +00001674 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1675 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1676 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001677 const MCInstrDesc &MCID = MI->getDesc();
1678 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001679 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001680 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1681 unsigned JTI = JTOP.getIndex();
1682 assert(JTI < JT.size());
1683
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001684 bool ByteOk = true;
1685 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001686 unsigned JTOffset = GetOffsetOf(MI) + 4;
1687 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001688 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1689 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001690 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001691 // Negative offset is not ok. FIXME: We should change BB layout to make
1692 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001693 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001694 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001695 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001696 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001697 HalfWordOk = false;
1698 if (!ByteOk && !HalfWordOk)
1699 break;
1700 }
1701
1702 if (ByteOk || HalfWordOk) {
1703 MachineBasicBlock *MBB = MI->getParent();
1704 unsigned BaseReg = MI->getOperand(0).getReg();
1705 bool BaseRegKill = MI->getOperand(0).isKill();
1706 if (!BaseRegKill)
1707 continue;
1708 unsigned IdxReg = MI->getOperand(1).getReg();
1709 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001710
1711 // Scan backwards to find the instruction that defines the base
1712 // register. Due to post-RA scheduling, we can't count on it
1713 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001714 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001715 MachineBasicBlock::iterator B = MBB->begin();
1716 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1717 --PrevI;
1718
1719 // If for some reason we didn't find it, we can't do anything, so
1720 // just skip this one.
1721 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001722 continue;
1723
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001724 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001725 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001726 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001727 // Make sure it only defines the base register and kills any uses
1728 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001729 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1730 const MachineOperand &MO = AddrMI->getOperand(k);
1731 if (!MO.isReg() || !MO.getReg())
1732 continue;
1733 if (MO.isDef() && MO.getReg() != BaseReg) {
1734 OptOk = false;
1735 break;
1736 }
1737 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1738 OptOk = false;
1739 break;
1740 }
1741 }
1742 if (!OptOk)
1743 continue;
1744
Owen Anderson6b8719f2010-12-13 22:51:08 +00001745 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001746 // that gave us the initial base register definition.
1747 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1748 ;
1749
Owen Anderson6b8719f2010-12-13 22:51:08 +00001750 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001751 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001752 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001753 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001754 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001755 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001756 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001757
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001758 if (!OptOk)
1759 continue;
1760
Jim Grosbachd092a872010-11-29 21:28:32 +00001761 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001762 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1763 .addReg(IdxReg, getKillRegState(IdxRegKill))
1764 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1765 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1766 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1767 // is 2-byte aligned. For now, asm printer will fix it up.
1768 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1769 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1770 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1771 OrigSize += TII->GetInstSizeInBytes(MI);
1772
1773 AddrMI->eraseFromParent();
1774 LeaMI->eraseFromParent();
1775 MI->eraseFromParent();
1776
1777 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001778 BBInfo[MBB->getNumber()].Size -= delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001779 AdjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001780
1781 ++NumTBs;
1782 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001783 }
1784 }
1785
1786 return MadeChange;
1787}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001788
Jim Grosbach9249efe2009-11-16 18:55:47 +00001789/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1790/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach80697d12009-11-12 17:25:07 +00001791bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1792 bool MadeChange = false;
1793
1794 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001795 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001796
Jim Grosbach80697d12009-11-12 17:25:07 +00001797 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1798 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1799 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001800 const MCInstrDesc &MCID = MI->getDesc();
1801 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001802 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001803 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1804 unsigned JTI = JTOP.getIndex();
1805 assert(JTI < JT.size());
1806
1807 // We prefer if target blocks for the jump table come after the jump
1808 // instruction so we can use TB[BH]. Loop through the target blocks
1809 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001810 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001811 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1812 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1813 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001814 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001815
Jim Grosbach08cbda52009-11-16 18:58:52 +00001816 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001817 // The destination precedes the switch. Try to move the block forward
1818 // so we have a positive offset.
1819 MachineBasicBlock *NewBB =
1820 AdjustJTTargetBlockForward(MBB, MI->getParent());
1821 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001822 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001823 MadeChange = true;
1824 }
1825 }
1826 }
1827
1828 return MadeChange;
1829}
1830
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001831MachineBasicBlock *ARMConstantIslands::
1832AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1833{
1834 MachineFunction &MF = *BB->getParent();
1835
Jim Grosbach03e2d442010-07-07 22:53:35 +00001836 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001837 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001838 // table that branches back to the actual target. This is a very simple
1839 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001840 MachineBasicBlock *TBB = 0, *FBB = 0;
1841 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001842 SmallVector<MachineOperand, 4> CondPrior;
1843 MachineFunction::iterator BBi = BB;
1844 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001845
Jim Grosbachca215e72009-11-16 17:10:56 +00001846 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001847 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001848
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001849 // If the block ends in an unconditional branch, move it. The prior block
1850 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001851 // and make sure we're not trying to move the entry block of the function.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001852 if (!B && Cond.empty() && BB != MF.begin() &&
1853 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001854 BB->moveAfter(JTBB);
1855 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001856 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001857 // Update numbering to account for the block being moved.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001858 MF.RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001859 ++NumJTMoved;
1860 return NULL;
1861 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001862
1863 // Create a new MBB for the code after the jump BB.
1864 MachineBasicBlock *NewBB =
1865 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1866 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1867 MF.insert(MBBI, NewBB);
1868
1869 // Add an unconditional branch from NewBB to BB.
1870 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1871 // correspond directly to anything in the source.
1872 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001873 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1874 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001875
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001876 // Update internal data structures to account for the newly inserted MBB.
1877 MF.RenumberBlocks(NewBB);
1878
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001879 // Update the CFG.
1880 NewBB->addSuccessor(BB);
1881 JTBB->removeSuccessor(BB);
1882 JTBB->addSuccessor(NewBB);
1883
Jim Grosbach80697d12009-11-12 17:25:07 +00001884 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001885 return NewBB;
1886}