blob: 315bf214d7bf7ead47d80347e7d98ea65d471473 [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) {
315 DEBUG(errs() << "block " << J << " offset " << BBInfo[J].Offset
316 << " 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) {
Evan Chengb6879b22009-08-07 07:35:21 +0000389 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000390 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000391 CPChange |= HandleConstantPoolUser(MF, i);
392 if (CPChange && ++NoCPIters > 30)
393 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000394 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000395
Bob Wilsonb9239532009-10-15 20:49:47 +0000396 // Clear NewWaterList now. If we split a block for branches, it should
397 // appear as "new water" for the next iteration of constant pool placement.
398 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000399
400 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000401 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000402 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
403 if (BRChange && ++NoBRIters > 30)
404 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000405 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000406
407 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000408 break;
409 MadeChange = true;
410 }
Evan Chenged884f32007-04-03 23:39:48 +0000411
Evan Chenga1efbbd2009-08-14 00:32:16 +0000412 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000413 if (isThumb2 && !STI->prefers32BitThumb())
Evan Chenga1efbbd2009-08-14 00:32:16 +0000414 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000415
Dale Johannesen8593e412007-04-29 19:19:30 +0000416 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000417 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000418
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000419 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
420 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000421 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000422 MadeChange |= UndoLRSpillRestore();
423
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000424 // Save the mapping between original and cloned constpool entries.
425 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
426 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
427 const CPEntry & CPE = CPEntries[i][j];
428 AFI->recordCPEClone(i, CPE.CPI);
429 }
430 }
431
Evan Chengb1c857b2010-07-22 02:09:47 +0000432 DEBUG(errs() << '\n'; dumpBBs());
433
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000434 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000435 WaterList.clear();
436 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000437 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000438 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000439 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000440 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000441
442 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000443}
444
445/// DoInitialPlacement - Perform the initial placement of the constant pool
446/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000447void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000448 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000449 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000450 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
451 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000452
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000453 // Mark the basic block as 4-byte aligned as required by the const-pool.
454 BB->setAlignment(2);
455
Evan Chenga8e29892007-01-19 07:51:42 +0000456 // Add all of the constants from the constant pool to the end block, use an
457 // identity mapping of CPI's to CPE's.
458 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000459 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000460
Evan Cheng5657c012009-07-29 02:18:14 +0000461 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000462 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000463 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000464 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
465 // we would have to pad them out or something so that instructions stay
466 // aligned.
467 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
468 MachineInstr *CPEMI =
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000469 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
470 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000471 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000472
473 // Add a new CPEntry, but no corresponding CPUser yet.
474 std::vector<CPEntry> CPEs;
475 CPEs.push_back(CPEntry(CPEMI, i));
476 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000477 ++NumCPEs;
Chris Lattner893e1c92009-08-23 06:49:22 +0000478 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
479 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000480 }
481}
482
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000483/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000484/// into the block immediately after it.
485static bool BBHasFallthrough(MachineBasicBlock *MBB) {
486 // Get the next machine basic block in the function.
487 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000488 // Can't fall off end of function.
489 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000490 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000491
Chris Lattner7896c9f2009-12-03 00:50:42 +0000492 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000493 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
494 E = MBB->succ_end(); I != E; ++I)
495 if (*I == NextBB)
496 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000497
Evan Chenga8e29892007-01-19 07:51:42 +0000498 return false;
499}
500
Evan Chengc99ef082007-02-09 20:54:44 +0000501/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
502/// look up the corresponding CPEntry.
503ARMConstantIslands::CPEntry
504*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
505 const MachineInstr *CPEMI) {
506 std::vector<CPEntry> &CPEs = CPEntries[CPI];
507 // Number of entries per constpool index should be small, just do a
508 // linear search.
509 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
510 if (CPEs[i].CPEMI == CPEMI)
511 return &CPEs[i];
512 }
513 return NULL;
514}
515
Jim Grosbach80697d12009-11-12 17:25:07 +0000516/// JumpTableFunctionScan - Do a scan of the function, building up
517/// information about the sizes of each block and the locations of all
518/// the jump tables.
519void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
Jim Grosbach80697d12009-11-12 17:25:07 +0000520 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
521 MBBI != E; ++MBBI) {
522 MachineBasicBlock &MBB = *MBBI;
523
Jim Grosbach80697d12009-11-12 17:25:07 +0000524 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000525 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000526 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000527 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000528 }
529}
530
Evan Chenga8e29892007-01-19 07:51:42 +0000531/// InitialFunctionScan - Do the initial scan of the function, building up
532/// information about the sizes of each block, the location of all the water,
533/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000534void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000535 const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000536 BBInfo.clear();
537 BBInfo.resize(MF.getNumBlockIDs());
538
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000539 // First thing, compute the size of all basic blocks, and see if the function
540 // has any inline assembly in it. If so, we have to be conservative about
541 // alignment assumptions, as we don't know for sure the size of any
542 // instructions in the inline assembly.
543 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
544 ComputeBlockSize(I);
545
546 // The known bits of the entry block offset are determined by the function
547 // alignment.
548 BBInfo.front().KnownBits = MF.getAlignment();
549
550 // Compute block offsets and known bits.
551 AdjustBBOffsetsAfter(MF.begin());
552
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000553 // Now go back through the instructions and build up our data structures.
Evan Cheng5657c012009-07-29 02:18:14 +0000554 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000555 MBBI != E; ++MBBI) {
556 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000557
Evan Chenga8e29892007-01-19 07:51:42 +0000558 // If this block doesn't fall through into the next MBB, then this is
559 // 'water' that a constant pool island could be placed.
560 if (!BBHasFallthrough(&MBB))
561 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000562
Evan Chenga8e29892007-01-19 07:51:42 +0000563 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
564 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000565 if (I->isDebugValue())
566 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000567
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000568 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000569 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000570 bool isCond = false;
571 unsigned Bits = 0;
572 unsigned Scale = 1;
573 int UOpc = Opc;
574 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000575 default:
576 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000577 case ARM::t2BR_JT:
578 T2JumpTables.push_back(I);
579 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000580 case ARM::Bcc:
581 isCond = true;
582 UOpc = ARM::B;
583 // Fallthrough
584 case ARM::B:
585 Bits = 24;
586 Scale = 4;
587 break;
588 case ARM::tBcc:
589 isCond = true;
590 UOpc = ARM::tB;
591 Bits = 8;
592 Scale = 2;
593 break;
594 case ARM::tB:
595 Bits = 11;
596 Scale = 2;
597 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000598 case ARM::t2Bcc:
599 isCond = true;
600 UOpc = ARM::t2B;
601 Bits = 20;
602 Scale = 2;
603 break;
604 case ARM::t2B:
605 Bits = 24;
606 Scale = 2;
607 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000608 }
Evan Chengb43216e2007-02-01 10:16:15 +0000609
610 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000611 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000612 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000613 }
614
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000615 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
616 PushPopMIs.push_back(I);
617
Evan Chengd3d9d662009-07-23 18:27:47 +0000618 if (Opc == ARM::CONSTPOOL_ENTRY)
619 continue;
620
Evan Chenga8e29892007-01-19 07:51:42 +0000621 // Scan the instructions for constant pool operands.
622 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000623 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000624 // We found one. The addressing mode tells us the max displacement
625 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000626
Evan Chenga8e29892007-01-19 07:51:42 +0000627 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000628 unsigned Bits = 0;
629 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000630 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000631 bool IsSoImm = false;
632
633 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000634 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000635 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000636 break;
637
638 // Taking the address of a CP entry.
639 case ARM::LEApcrel:
640 // This takes a SoImm, which is 8 bit immediate rotated. We'll
641 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000642 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000643 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000644 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000645 Scale = 4;
646 NegOk = true;
647 IsSoImm = true;
648 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000649 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000650 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000651 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000652 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000653 case ARM::tLEApcrel:
654 Bits = 8;
655 Scale = 4;
656 break;
657
Jim Grosbach3e556122010-10-26 22:37:02 +0000658 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000659 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000660 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000661 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000662 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000663 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000664
665 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000666 Bits = 8;
667 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000668 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000669
Jim Grosbache5165492009-11-09 00:11:35 +0000670 case ARM::VLDRD:
671 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000672 Bits = 8;
673 Scale = 4; // +-(offset_8*4)
674 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000675 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000676 }
Evan Chengb43216e2007-02-01 10:16:15 +0000677
Evan Chenga8e29892007-01-19 07:51:42 +0000678 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000679 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000680 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000681 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000682 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000683
684 // Increment corresponding CPEntry reference count.
685 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
686 assert(CPE && "Cannot find a corresponding CPEntry!");
687 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000688
Evan Chenga8e29892007-01-19 07:51:42 +0000689 // Instructions can only use one CP entry, don't bother scanning the
690 // rest of the operands.
691 break;
692 }
693 }
Evan Chenga8e29892007-01-19 07:51:42 +0000694 }
695}
696
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000697/// ComputeBlockSize - Compute the size and some alignment information for MBB.
698/// This function updates BBInfo directly.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000699void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000700 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
701 BBI.Size = 0;
702 BBI.Unalign = 0;
703 BBI.PostAlign = 0;
704
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000705 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
706 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000707 BBI.Size += TII->GetInstSizeInBytes(I);
708 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
709 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000710 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000711 BBI.Unalign = isThumb ? 1 : 2;
712 }
713
714 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000715 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000716 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000717 MBB->getParent()->EnsureAlignment(2);
718 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000719}
720
Evan Chenga8e29892007-01-19 07:51:42 +0000721/// GetOffsetOf - Return the current offset of the specified machine instruction
722/// from the start of the function. This offset changes as stuff is moved
723/// around inside the function.
724unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
725 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000726
Evan Chenga8e29892007-01-19 07:51:42 +0000727 // The offset is composed of two things: the sum of the sizes of all MBB's
728 // before this instruction's block, and the offset from the start of the block
729 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000730 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000731
732 // Sum instructions before MI in MBB.
733 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
734 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
735 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000736 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000737 }
738}
739
740/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
741/// ID.
742static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
743 const MachineBasicBlock *RHS) {
744 return LHS->getNumber() < RHS->getNumber();
745}
746
747/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
748/// machine function, it upsets all of the block numbers. Renumber the blocks
749/// and update the arrays that parallel this numbering.
750void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000751 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000752 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000753
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000754 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000755 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000756 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000757
758 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000759 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000760 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000761 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
762 CompareMBBNumbers);
763 WaterList.insert(IP, NewBB);
764}
765
766
767/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000768/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000769/// account for this change and returns the newly created block.
770MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000771 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000772 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000773
774 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000775 MachineBasicBlock *NewBB =
776 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000777 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000778 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000779
Evan Chenga8e29892007-01-19 07:51:42 +0000780 // Splice the instructions starting with MI over to NewBB.
781 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000782
Evan Chenga8e29892007-01-19 07:51:42 +0000783 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000784 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000785 // There doesn't seem to be meaningful DebugInfo available; this doesn't
786 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000787 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000788 if (!isThumb)
789 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
790 else
791 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
792 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000793 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000794
Evan Chenga8e29892007-01-19 07:51:42 +0000795 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000796 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000797
Evan Chenga8e29892007-01-19 07:51:42 +0000798 // OrigBB branches to NewBB.
799 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000800
Evan Chenga8e29892007-01-19 07:51:42 +0000801 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000802 // This is almost the same as UpdateForInsertedWaterBlock, except that
803 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000804 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000805
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000806 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000807 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000808 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000809
Bob Wilson84945262009-05-12 17:09:30 +0000810 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000811 // available water after it (but not if it's already there, which happens
812 // when splitting before a conditional branch that is followed by an
813 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000814 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000815 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
816 CompareMBBNumbers);
817 MachineBasicBlock* WaterBB = *IP;
818 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000819 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000820 else
821 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000822 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000823
Dale Johannesen8086d582010-07-23 22:50:23 +0000824 // Figure out how large the OrigBB is. As the first half of the original
825 // block, it cannot contain a tablejump. The size includes
826 // the new jump we added. (It should be possible to do this without
827 // recounting everything, but it's very confusing, and this is rarely
828 // executed.)
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000829 ComputeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000830
Dale Johannesen8086d582010-07-23 22:50:23 +0000831 // Figure out how large the NewMBB is. As the second half of the original
832 // block, it may contain a tablejump.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000833 ComputeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000834
Dale Johannesen99c49a42007-02-25 00:47:03 +0000835 // All BBOffsets following these blocks must be modified.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000836 AdjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000837
838 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000839}
840
Dale Johannesen8593e412007-04-29 19:19:30 +0000841/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000842/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000843/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000844bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000845 unsigned TrialOffset, unsigned MaxDisp,
846 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000847 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
848 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000849 // Effectively, the valid range of displacements is 2 bytes smaller for such
850 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000851 unsigned TotalAdj = 0;
852 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000853 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000854 TotalAdj = 2;
855 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000856 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000857 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000858 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000859 TotalAdj += 2;
860 }
861
862 // In Thumb2 mode, later branch adjustments can shift instructions up and
863 // cause alignment change. In the worst case scenario this can cause the
864 // user's effective address to be subtracted by 2 and the CPE's address to
865 // be plus 2.
866 if (isThumb2 && TotalAdj != 4)
867 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000868
Dale Johannesen99c49a42007-02-25 00:47:03 +0000869 if (UserOffset <= TrialOffset) {
870 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000871 if (TrialOffset - UserOffset <= MaxDisp)
872 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000873 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000874 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000875 if (UserOffset - TrialOffset <= MaxDisp)
876 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000877 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000878 }
879 return false;
880}
881
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000882/// WaterIsInRange - Returns true if a CPE placed after the specified
883/// Water (a basic block) will be in range for the specific MI.
884
885bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000886 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000887 unsigned MaxDisp = U.MaxDisp;
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000888 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000889
Dale Johannesend959aa42007-04-02 20:31:06 +0000890 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000891 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000892 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000893 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000894
Evan Chengd3d9d662009-07-23 18:27:47 +0000895 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000896}
897
898/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000899/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000900bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000901 MachineInstr *CPEMI, unsigned MaxDisp,
902 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000903 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000904 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000905
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000906 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000907 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
908 << " max delta=" << MaxDisp
909 << " insn address=" << UserOffset
910 << " CPE address=" << CPEOffset
911 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000912 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000913
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000914 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000915}
916
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000917#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000918/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
919/// unconditionally branches to its only successor.
920static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
921 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
922 return false;
923
924 MachineBasicBlock *Succ = *MBB->succ_begin();
925 MachineBasicBlock *Pred = *MBB->pred_begin();
926 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000927 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
928 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000929 return PredMI->getOperand(0).getMBB() == Succ;
930 return false;
931}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000932#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000933
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000934void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000935 MachineFunction *MF = BB->getParent();
936 for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
937 // Get the offset and known bits at the end of the layout predecessor.
938 unsigned Offset = BBInfo[i - 1].postOffset();
939 unsigned KnownBits = BBInfo[i - 1].postKnownBits();
940
941 // Add padding before an aligned block. This may teach us more bits.
942 if (unsigned Align = MF->getBlockNumbered(i)->getAlignment()) {
943 Offset = WorstCaseAlign(Offset, Align, KnownBits);
944 KnownBits = std::max(KnownBits, Align);
Dale Johannesen8593e412007-04-29 19:19:30 +0000945 }
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000946
947 // This is where block i begins.
948 BBInfo[i].Offset = Offset;
949 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +0000950 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000951}
952
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000953/// DecrementOldEntry - find the constant pool entry with index CPI
954/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000955/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000956/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000957
Evan Chenged884f32007-04-03 23:39:48 +0000958bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000959 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000960 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
961 assert(CPE && "Unexpected!");
962 if (--CPE->RefCount == 0) {
963 RemoveDeadCPEMI(CPEMI);
964 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +0000965 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000966 return true;
967 }
968 return false;
969}
970
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000971/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
972/// if not, see if an in-range clone of the CPE is in range, and if so,
973/// change the data structures so the user references the clone. Returns:
974/// 0 = no existing entry found
975/// 1 = entry found, and there were no code insertions or deletions
976/// 2 = entry found, and there were code insertions or deletions
977int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
978{
979 MachineInstr *UserMI = U.MI;
980 MachineInstr *CPEMI = U.CPEMI;
981
982 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000983 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000984 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000985 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000986 }
987
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000988 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000989 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000990 std::vector<CPEntry> &CPEs = CPEntries[CPI];
991 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
992 // We already tried this one
993 if (CPEs[i].CPEMI == CPEMI)
994 continue;
995 // Removing CPEs can leave empty entries, skip
996 if (CPEs[i].CPEMI == NULL)
997 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000998 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000999 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1000 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001001 // Point the CPUser node to the replacement
1002 U.CPEMI = CPEs[i].CPEMI;
1003 // Change the CPI in the instruction operand to refer to the clone.
1004 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001005 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001006 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001007 break;
1008 }
1009 // Adjust the refcount of the clone...
1010 CPEs[i].RefCount++;
1011 // ...and the original. If we didn't remove the old entry, none of the
1012 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001013 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001014 }
1015 }
1016 return 0;
1017}
1018
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001019/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1020/// the specific unconditional branch instruction.
1021static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001022 switch (Opc) {
1023 case ARM::tB:
1024 return ((1<<10)-1)*2;
1025 case ARM::t2B:
1026 return ((1<<23)-1)*2;
1027 default:
1028 break;
1029 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001030
David Goodwin5e47a9a2009-06-30 18:04:13 +00001031 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001032}
1033
Bob Wilsonb9239532009-10-15 20:49:47 +00001034/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001035/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001036/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001037/// is set to the WaterList entry. For Thumb, prefer water that will not
1038/// introduce padding to water that will. To ensure that this pass
1039/// terminates, the CPE location for a particular CPUser is only allowed to
1040/// move to a lower address, so search backward from the end of the list and
1041/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001042bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001043 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001044 if (WaterList.empty())
1045 return false;
1046
Bob Wilson32c50e82009-10-12 20:45:53 +00001047 bool FoundWaterThatWouldPad = false;
1048 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001049 for (water_iterator IP = prior(WaterList.end()),
1050 B = WaterList.begin();; --IP) {
1051 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001052 // Check if water is in range and is either at a lower address than the
1053 // current "high water mark" or a new water block that was created since
1054 // the previous iteration by inserting an unconditional branch. In the
1055 // latter case, we want to allow resetting the high water mark back to
1056 // this new water since we haven't seen it before. Inserting branches
1057 // should be relatively uncommon and when it does happen, we want to be
1058 // sure to take advantage of it for all the CPEs near that block, so that
1059 // we don't insert more branches than necessary.
1060 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1061 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1062 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001063 unsigned WBBId = WaterBB->getNumber();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001064 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
Bob Wilson3b757352009-10-12 19:04:03 +00001065 // This is valid Water, but would introduce padding. Remember
1066 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001067 if (!FoundWaterThatWouldPad) {
1068 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001069 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001070 }
Bob Wilson3b757352009-10-12 19:04:03 +00001071 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001072 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001073 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001074 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001075 }
Bob Wilson3b757352009-10-12 19:04:03 +00001076 if (IP == B)
1077 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001078 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001079 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001080 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001081 return true;
1082 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001083 return false;
1084}
1085
Bob Wilson84945262009-05-12 17:09:30 +00001086/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001087/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1088/// block is used if in range, and the conditional branch munged so control
1089/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001090/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001091/// block following which the new island can be inserted (the WaterList
1092/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001093void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001094 unsigned UserOffset,
1095 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001096 CPUser &U = CPUsers[CPUserIndex];
1097 MachineInstr *UserMI = U.MI;
1098 MachineInstr *CPEMI = U.CPEMI;
1099 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001100 unsigned OffsetOfNextBlock = BBInfo[UserMBB->getNumber()].postOffset();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001101
Bob Wilson36fa5322009-10-15 05:10:36 +00001102 // If the block does not end in an unconditional branch already, and if the
1103 // end of the block is within range, make new water there. (The addition
1104 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1105 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001106 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001107 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001108 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1109 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001110 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001111 if (&UserMBB->back() == UserMI)
1112 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001113 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001114 // Add an unconditional branch from UserMBB to fallthrough block.
1115 // Record it for branch lengthening; this new branch will not get out of
1116 // range, but if the preceding conditional branch is out of range, the
1117 // targets will be exchanged, and the altered branch may be out of
1118 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001119 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001120 if (!isThumb)
1121 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1122 else
1123 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1124 .addImm(ARMCC::AL).addReg(0);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001125 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001126 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001127 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001128 int delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001129 BBInfo[UserMBB->getNumber()].Size += delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001130 AdjustBBOffsetsAfter(UserMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001131 } else {
1132 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001133 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001134 // and constant pool entries are 4 bytes: if instruction I references
1135 // island CPE, and instruction I+1 references CPE', it will
1136 // not work well to put CPE as far forward as possible, since then
1137 // CPE' cannot immediately follow it (that location is 2 bytes
1138 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001139 // a new island. So, we make a first guess, then walk through the
1140 // instructions between the one currently being looked at and the
1141 // possible insertion point, and make sure any other instructions
1142 // that reference CPEs will be able to use the same island area;
1143 // if not, we back up the insertion point.
1144
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001145 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001146 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001147 // island is handled inside OffsetIsInRange.
1148 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001149 // This could point off the end of the block if we've already got
1150 // constant pool entries following this block; only the last one is
1151 // in the water list. Back past any possible branches (allow for a
1152 // conditional and a maximally long unconditional).
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001153 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1154 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
Evan Chengd3d9d662009-07-23 18:27:47 +00001155 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001156 unsigned EndInsertOffset = BaseInsertOffset +
1157 CPEMI->getOperand(2).getImm();
1158 MachineBasicBlock::iterator MI = UserMI;
1159 ++MI;
1160 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001161 unsigned NumCPUsers = CPUsers.size();
1162 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001163 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001164 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001165 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001166 MI = llvm::next(MI)) {
1167 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001168 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001169 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001170 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1171 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1172 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001173 }
1174 // This is overly conservative, as we don't account for CPEMIs
1175 // being reused within the block, but it doesn't matter much.
1176 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1177 CPUIndex++;
1178 }
Evan Cheng719510a2010-08-12 20:30:05 +00001179
1180 // Remember the last IT instruction.
1181 if (MI->getOpcode() == ARM::t2IT)
1182 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001183 }
Evan Cheng719510a2010-08-12 20:30:05 +00001184
Chris Lattner893e1c92009-08-23 06:49:22 +00001185 DEBUG(errs() << "Split in middle of big block\n");
Evan Cheng719510a2010-08-12 20:30:05 +00001186 --MI;
1187
1188 // Avoid splitting an IT block.
1189 if (LastIT) {
1190 unsigned PredReg = 0;
1191 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1192 if (CC != ARMCC::AL)
1193 MI = LastIT;
1194 }
1195 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001196 }
1197}
1198
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001199/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001200/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001201/// place in-range. Return true if we changed any addresses (thus must run
1202/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001203bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001204 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001205 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001206 MachineInstr *UserMI = U.MI;
1207 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001208 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001209 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001210 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001211 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001212 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001213
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001214 // See if the current entry is within range, or there is a clone of it
1215 // in range.
1216 int result = LookForExistingCPEntry(U, UserOffset);
1217 if (result==1) return false;
1218 else if (result==2) return true;
1219
1220 // No existing clone of this CPE is within range.
1221 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001222 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001223
Bob Wilsonf98032e2009-10-12 21:23:15 +00001224 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001225 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1226 MachineBasicBlock *NewMBB;
1227 water_iterator IP;
1228 if (LookForWater(U, UserOffset, IP)) {
1229 DEBUG(errs() << "found water in range\n");
1230 MachineBasicBlock *WaterBB = *IP;
1231
1232 // If the original WaterList entry was "new water" on this iteration,
1233 // propagate that to the new island. This is just keeping NewWaterList
1234 // updated to match the WaterList, which will be updated below.
1235 if (NewWaterList.count(WaterBB)) {
1236 NewWaterList.erase(WaterBB);
1237 NewWaterList.insert(NewIsland);
1238 }
1239 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001240 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001241
1242 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001243 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001244 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001245 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001246
1247 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1248 // called while handling branches so that the water will be seen on the
1249 // next iteration for constant pools, but in this context, we don't want
1250 // it. Check for this so it will be removed from the WaterList.
1251 // Also remove any entry from NewWaterList.
1252 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1253 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1254 if (IP != WaterList.end())
1255 NewWaterList.erase(WaterBB);
1256
1257 // We are adding new water. Update NewWaterList.
1258 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001259 }
1260
Bob Wilsonb9239532009-10-15 20:49:47 +00001261 // Remove the original WaterList entry; we want subsequent insertions in
1262 // this vicinity to go after the one we're about to insert. This
1263 // considerably reduces the number of times we have to move the same CPE
1264 // more than once and is also important to ensure the algorithm terminates.
1265 if (IP != WaterList.end())
1266 WaterList.erase(IP);
1267
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001268 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001269 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001270
1271 // Update internal data structures to account for the newly inserted MBB.
1272 UpdateForInsertedWaterBlock(NewIsland);
1273
1274 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001275 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001276
1277 // Now that we have an island to add the CPE to, clone the original CPE and
1278 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001279 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001280 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001281 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001282 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001283 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001284
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001285 // Mark the basic block as 4-byte aligned as required by the const-pool entry.
1286 NewIsland->setAlignment(2);
1287
Evan Chenga8e29892007-01-19 07:51:42 +00001288 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001289 BBInfo[NewIsland->getNumber()].Size += Size;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001290 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001291
Evan Chenga8e29892007-01-19 07:51:42 +00001292 // Finally, change the CPI in the instruction operand to be ID.
1293 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001294 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001295 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001296 break;
1297 }
Bob Wilson84945262009-05-12 17:09:30 +00001298
Chris Lattner705e07f2009-08-23 03:41:05 +00001299 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1300 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001301
Evan Chenga8e29892007-01-19 07:51:42 +00001302 return true;
1303}
1304
Evan Chenged884f32007-04-03 23:39:48 +00001305/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1306/// sizes and offsets of impacted basic blocks.
1307void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1308 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001309 unsigned Size = CPEMI->getOperand(2).getImm();
1310 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001311 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001312 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001313 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001314 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001315 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001316 // empty, so fix this.
1317 // All succeeding offsets have the current size value added in, fix this.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001318 if (BBInfo[CPEBB->getNumber()].Size != 0) {
1319 Size += BBInfo[CPEBB->getNumber()].Size;
1320 BBInfo[CPEBB->getNumber()].Size = 0;
Evan Chenged884f32007-04-03 23:39:48 +00001321 }
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001322
1323 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1324 CPEBB->setAlignment(0);
Evan Chenged884f32007-04-03 23:39:48 +00001325 }
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001326 AdjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001327 // An island has only one predecessor BB and one successor BB. Check if
1328 // this BB's predecessor jumps directly to this BB's successor. This
1329 // shouldn't happen currently.
1330 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1331 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001332}
1333
1334/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1335/// are zero.
1336bool ARMConstantIslands::RemoveUnusedCPEntries() {
1337 unsigned MadeChange = false;
1338 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1339 std::vector<CPEntry> &CPEs = CPEntries[i];
1340 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1341 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1342 RemoveDeadCPEMI(CPEs[j].CPEMI);
1343 CPEs[j].CPEMI = NULL;
1344 MadeChange = true;
1345 }
1346 }
Bob Wilson84945262009-05-12 17:09:30 +00001347 }
Evan Chenged884f32007-04-03 23:39:48 +00001348 return MadeChange;
1349}
1350
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001351/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001352/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001353bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1354 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001355 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001356 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001357 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001358
Chris Lattner705e07f2009-08-23 03:41:05 +00001359 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1360 << " from BB#" << MI->getParent()->getNumber()
1361 << " max delta=" << MaxDisp
1362 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1363 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001364
Dale Johannesen8593e412007-04-29 19:19:30 +00001365 if (BrOffset <= DestOffset) {
1366 // Branch before the Dest.
1367 if (DestOffset-BrOffset <= MaxDisp)
1368 return true;
1369 } else {
1370 if (BrOffset-DestOffset <= MaxDisp)
1371 return true;
1372 }
1373 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001374}
1375
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001376/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1377/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001378bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001379 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001380 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001381
Evan Chengc0dbec72007-01-31 19:57:44 +00001382 // Check to see if the DestBB is already in-range.
1383 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001384 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001385
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001386 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001387 return FixUpUnconditionalBr(MF, Br);
1388 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001389}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001390
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001391/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1392/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001393/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001394/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001395bool
Evan Cheng5657c012009-07-29 02:18:14 +00001396ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001397 MachineInstr *MI = Br.MI;
1398 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001399 if (!isThumb1)
1400 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001401
1402 // Use BL to implement far jump.
1403 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001404 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001405 BBInfo[MBB->getNumber()].Size += 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001406 AdjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001407 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001408 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001409
Chris Lattner705e07f2009-08-23 03:41:05 +00001410 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001411
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001412 return true;
1413}
1414
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001415/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001416/// far away to fit in its displacement field. It is converted to an inverse
1417/// conditional branch + an unconditional branch to the destination.
1418bool
Evan Cheng5657c012009-07-29 02:18:14 +00001419ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001420 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001421 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001422
Bob Wilson39bf0512009-05-12 17:35:29 +00001423 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001424 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001425 // blt L1
1426 // =>
1427 // bge L2
1428 // b L1
1429 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001430 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001431 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001432 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001433
1434 // If the branch is at the end of its MBB and that has a fall-through block,
1435 // direct the updated conditional branch to the fall-through block. Otherwise,
1436 // split the MBB before the next instruction.
1437 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001438 MachineInstr *BMI = &MBB->back();
1439 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001440
Dan Gohmanfe601042010-06-22 15:08:57 +00001441 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001442 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001443 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001444 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001445 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001446 // condition and swap destinations:
1447 // beq L1
1448 // b L2
1449 // =>
1450 // bne L2
1451 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001452 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001453 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001454 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1455 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001456 BMI->getOperand(0).setMBB(DestBB);
1457 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001458 MI->getOperand(1).setImm(CC);
1459 return true;
1460 }
1461 }
1462 }
1463
1464 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001465 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001466 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001467 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001468 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001469 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001470 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001471 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001472 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001473 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001474
Chris Lattner893e1c92009-08-23 06:49:22 +00001475 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1476 << " also invert condition and change dest. to BB#"
1477 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001478
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001479 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001480 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001481 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001482 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001483 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001484 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001485 if (isThumb)
1486 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1487 .addImm(ARMCC::AL).addReg(0);
1488 else
1489 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001490 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001491 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001492 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001493
1494 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001495 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001496 MI->eraseFromParent();
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001497 AdjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001498 return true;
1499}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001500
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001501/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001502/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1503/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001504bool ARMConstantIslands::UndoLRSpillRestore() {
1505 bool MadeChange = false;
1506 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1507 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001508 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001509 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001510 MI->getOperand(2).getReg() == ARM::PC &&
1511 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001512 // Create the new insn and copy the predicate from the old.
1513 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1514 .addOperand(MI->getOperand(0))
1515 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001516 MI->eraseFromParent();
1517 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001518 }
1519 }
1520 return MadeChange;
1521}
Evan Cheng5657c012009-07-29 02:18:14 +00001522
Evan Chenga1efbbd2009-08-14 00:32:16 +00001523bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1524 bool MadeChange = false;
1525
1526 // Shrink ADR and LDR from constantpool.
1527 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1528 CPUser &U = CPUsers[i];
1529 unsigned Opcode = U.MI->getOpcode();
1530 unsigned NewOpc = 0;
1531 unsigned Scale = 1;
1532 unsigned Bits = 0;
1533 switch (Opcode) {
1534 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001535 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001536 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1537 NewOpc = ARM::tLEApcrel;
1538 Bits = 8;
1539 Scale = 4;
1540 }
1541 break;
1542 case ARM::t2LDRpci:
1543 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1544 NewOpc = ARM::tLDRpci;
1545 Bits = 8;
1546 Scale = 4;
1547 }
1548 break;
1549 }
1550
1551 if (!NewOpc)
1552 continue;
1553
1554 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1555 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1556 // FIXME: Check if offset is multiple of scale if scale is not 4.
1557 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1558 U.MI->setDesc(TII->get(NewOpc));
1559 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001560 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001561 AdjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001562 ++NumT2CPShrunk;
1563 MadeChange = true;
1564 }
1565 }
1566
Evan Chenga1efbbd2009-08-14 00:32:16 +00001567 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001568 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001569 return MadeChange;
1570}
1571
1572bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001573 bool MadeChange = false;
1574
1575 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1576 ImmBranch &Br = ImmBranches[i];
1577 unsigned Opcode = Br.MI->getOpcode();
1578 unsigned NewOpc = 0;
1579 unsigned Scale = 1;
1580 unsigned Bits = 0;
1581 switch (Opcode) {
1582 default: break;
1583 case ARM::t2B:
1584 NewOpc = ARM::tB;
1585 Bits = 11;
1586 Scale = 2;
1587 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001588 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001589 NewOpc = ARM::tBcc;
1590 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001591 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001592 break;
1593 }
Evan Chengde17fb62009-10-31 23:46:45 +00001594 }
1595 if (NewOpc) {
1596 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1597 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1598 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1599 Br.MI->setDesc(TII->get(NewOpc));
1600 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001601 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001602 AdjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001603 ++NumT2BrShrunk;
1604 MadeChange = true;
1605 }
1606 }
1607
1608 Opcode = Br.MI->getOpcode();
1609 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001610 continue;
1611
Evan Chengde17fb62009-10-31 23:46:45 +00001612 NewOpc = 0;
1613 unsigned PredReg = 0;
1614 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1615 if (Pred == ARMCC::EQ)
1616 NewOpc = ARM::tCBZ;
1617 else if (Pred == ARMCC::NE)
1618 NewOpc = ARM::tCBNZ;
1619 if (!NewOpc)
1620 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001621 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001622 // Check if the distance is within 126. Subtract starting offset by 2
1623 // because the cmp will be eliminated.
1624 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001625 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001626 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001627 MachineBasicBlock::iterator CmpMI = Br.MI;
1628 if (CmpMI != Br.MI->getParent()->begin()) {
1629 --CmpMI;
1630 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1631 unsigned Reg = CmpMI->getOperand(0).getReg();
1632 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1633 if (Pred == ARMCC::AL &&
1634 CmpMI->getOperand(1).getImm() == 0 &&
1635 isARMLowRegister(Reg)) {
1636 MachineBasicBlock *MBB = Br.MI->getParent();
1637 MachineInstr *NewBR =
1638 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1639 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1640 CmpMI->eraseFromParent();
1641 Br.MI->eraseFromParent();
1642 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001643 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001644 AdjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001645 ++NumCBZ;
1646 MadeChange = true;
1647 }
Evan Chengde17fb62009-10-31 23:46:45 +00001648 }
1649 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001650 }
1651 }
1652
1653 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001654}
1655
Evan Chenga1efbbd2009-08-14 00:32:16 +00001656/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1657/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001658bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1659 bool MadeChange = false;
1660
1661 // FIXME: After the tables are shrunk, can we get rid some of the
1662 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001663 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001664 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001665
Evan Cheng5657c012009-07-29 02:18:14 +00001666 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1667 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1668 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001669 const MCInstrDesc &MCID = MI->getDesc();
1670 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001671 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001672 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1673 unsigned JTI = JTOP.getIndex();
1674 assert(JTI < JT.size());
1675
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001676 bool ByteOk = true;
1677 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001678 unsigned JTOffset = GetOffsetOf(MI) + 4;
1679 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001680 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1681 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001682 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001683 // Negative offset is not ok. FIXME: We should change BB layout to make
1684 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001685 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001686 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001687 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001688 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001689 HalfWordOk = false;
1690 if (!ByteOk && !HalfWordOk)
1691 break;
1692 }
1693
1694 if (ByteOk || HalfWordOk) {
1695 MachineBasicBlock *MBB = MI->getParent();
1696 unsigned BaseReg = MI->getOperand(0).getReg();
1697 bool BaseRegKill = MI->getOperand(0).isKill();
1698 if (!BaseRegKill)
1699 continue;
1700 unsigned IdxReg = MI->getOperand(1).getReg();
1701 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001702
1703 // Scan backwards to find the instruction that defines the base
1704 // register. Due to post-RA scheduling, we can't count on it
1705 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001706 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001707 MachineBasicBlock::iterator B = MBB->begin();
1708 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1709 --PrevI;
1710
1711 // If for some reason we didn't find it, we can't do anything, so
1712 // just skip this one.
1713 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001714 continue;
1715
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001716 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001717 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001718 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001719 // Make sure it only defines the base register and kills any uses
1720 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001721 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1722 const MachineOperand &MO = AddrMI->getOperand(k);
1723 if (!MO.isReg() || !MO.getReg())
1724 continue;
1725 if (MO.isDef() && MO.getReg() != BaseReg) {
1726 OptOk = false;
1727 break;
1728 }
1729 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1730 OptOk = false;
1731 break;
1732 }
1733 }
1734 if (!OptOk)
1735 continue;
1736
Owen Anderson6b8719f2010-12-13 22:51:08 +00001737 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001738 // that gave us the initial base register definition.
1739 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1740 ;
1741
Owen Anderson6b8719f2010-12-13 22:51:08 +00001742 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001743 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001744 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001745 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001746 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001747 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001748 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001749
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001750 if (!OptOk)
1751 continue;
1752
Jim Grosbachd092a872010-11-29 21:28:32 +00001753 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001754 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1755 .addReg(IdxReg, getKillRegState(IdxRegKill))
1756 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1757 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1758 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1759 // is 2-byte aligned. For now, asm printer will fix it up.
1760 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1761 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1762 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1763 OrigSize += TII->GetInstSizeInBytes(MI);
1764
1765 AddrMI->eraseFromParent();
1766 LeaMI->eraseFromParent();
1767 MI->eraseFromParent();
1768
1769 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001770 BBInfo[MBB->getNumber()].Size -= delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001771 AdjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001772
1773 ++NumTBs;
1774 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001775 }
1776 }
1777
1778 return MadeChange;
1779}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001780
Jim Grosbach9249efe2009-11-16 18:55:47 +00001781/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1782/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach80697d12009-11-12 17:25:07 +00001783bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1784 bool MadeChange = false;
1785
1786 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001787 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001788
Jim Grosbach80697d12009-11-12 17:25:07 +00001789 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1790 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1791 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001792 const MCInstrDesc &MCID = MI->getDesc();
1793 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001794 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001795 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1796 unsigned JTI = JTOP.getIndex();
1797 assert(JTI < JT.size());
1798
1799 // We prefer if target blocks for the jump table come after the jump
1800 // instruction so we can use TB[BH]. Loop through the target blocks
1801 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001802 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001803 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1804 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1805 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001806 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001807
Jim Grosbach08cbda52009-11-16 18:58:52 +00001808 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001809 // The destination precedes the switch. Try to move the block forward
1810 // so we have a positive offset.
1811 MachineBasicBlock *NewBB =
1812 AdjustJTTargetBlockForward(MBB, MI->getParent());
1813 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001814 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001815 MadeChange = true;
1816 }
1817 }
1818 }
1819
1820 return MadeChange;
1821}
1822
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001823MachineBasicBlock *ARMConstantIslands::
1824AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1825{
1826 MachineFunction &MF = *BB->getParent();
1827
Jim Grosbach03e2d442010-07-07 22:53:35 +00001828 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001829 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001830 // table that branches back to the actual target. This is a very simple
1831 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001832 MachineBasicBlock *TBB = 0, *FBB = 0;
1833 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001834 SmallVector<MachineOperand, 4> CondPrior;
1835 MachineFunction::iterator BBi = BB;
1836 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001837
Jim Grosbachca215e72009-11-16 17:10:56 +00001838 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001839 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001840
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001841 // If the block ends in an unconditional branch, move it. The prior block
1842 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001843 // and make sure we're not trying to move the entry block of the function.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001844 if (!B && Cond.empty() && BB != MF.begin() &&
1845 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001846 BB->moveAfter(JTBB);
1847 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001848 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001849 // Update numbering to account for the block being moved.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001850 MF.RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001851 ++NumJTMoved;
1852 return NULL;
1853 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001854
1855 // Create a new MBB for the code after the jump BB.
1856 MachineBasicBlock *NewBB =
1857 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1858 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1859 MF.insert(MBBI, NewBB);
1860
1861 // Add an unconditional branch from NewBB to BB.
1862 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1863 // correspond directly to anything in the source.
1864 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001865 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1866 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001867
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001868 // Update internal data structures to account for the newly inserted MBB.
1869 MF.RenumberBlocks(NewBB);
1870
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001871 // Update the CFG.
1872 NewBB->addSuccessor(BB);
1873 JTBB->removeSuccessor(BB);
1874 JTBB->addSuccessor(NewBB);
1875
Jim Grosbach80697d12009-11-12 17:25:07 +00001876 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001877 return NewBB;
1878}