blob: e2dafc41840dec619a064f0c0a9b9d694295080f [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);
Evan Chengc0dbec72007-01-31 19:57:44 +0000268 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000269 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
270 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
271 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000272 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000273 bool OptimizeThumb2Instructions(MachineFunction &MF);
274 bool OptimizeThumb2Branches(MachineFunction &MF);
Jim Grosbach80697d12009-11-12 17:25:07 +0000275 bool ReorderThumb2JumpTables(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000276 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000277 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
278 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000279
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000280 void ComputeBlockSize(MachineBasicBlock *MBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000281 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000282 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000283 void verify(MachineFunction &MF);
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000284
285 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
286 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
287 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
288 const CPUser &U) {
289 return OffsetIsInRange(UserOffset, TrialOffset,
290 U.MaxDisp, U.NegOk, U.IsSoImm);
291 }
Evan Chenga8e29892007-01-19 07:51:42 +0000292 };
Devang Patel19974732007-05-03 01:11:54 +0000293 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000294}
295
Dale Johannesen8593e412007-04-29 19:19:30 +0000296/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000297void ARMConstantIslands::verify(MachineFunction &MF) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000298#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000299 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000300 MBBI != E; ++MBBI) {
301 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000302 unsigned Align = MBB->getAlignment();
303 unsigned MBBId = MBB->getNumber();
304 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
305 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000306 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000307 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
308 CPUser &U = CPUsers[i];
309 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000310 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
311 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
312 UserOffset - CPEOffset;
313 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000314 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000315#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000316}
317
318/// print block size and offset information - debugging
319void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000320 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000321 DEBUG(dbgs() << "block " << J << " offset " << BBInfo[J].Offset
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000322 << " size " << BBInfo[J].Size << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000323 }
324}
325
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000326/// createARMConstantIslandPass - returns an instance of the constpool
327/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000328FunctionPass *llvm::createARMConstantIslandPass() {
329 return new ARMConstantIslands();
330}
331
Evan Cheng5657c012009-07-29 02:18:14 +0000332bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
333 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000334
Chris Lattner20628752010-07-22 21:27:00 +0000335 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
Evan Cheng5657c012009-07-29 02:18:14 +0000336 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000337 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
338
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000339 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000340 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000341 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000342
343 HasFarJump = false;
344
Evan Chenga8e29892007-01-19 07:51:42 +0000345 // Renumber all of the machine basic blocks in the function, guaranteeing that
346 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000347 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000348
Jim Grosbach80697d12009-11-12 17:25:07 +0000349 // Try to reorder and otherwise adjust the block layout to make good use
350 // of the TB[BH] instructions.
351 bool MadeChange = false;
352 if (isThumb2 && AdjustJumpTableBlocks) {
353 JumpTableFunctionScan(MF);
354 MadeChange |= ReorderThumb2JumpTables(MF);
355 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000356 T2JumpTables.clear();
357 // Blocks may have shifted around. Keep the numbering up to date.
358 MF.RenumberBlocks();
359 }
360
Evan Chengd26b14c2009-07-31 18:28:05 +0000361 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000362 // This is so we can keep exact track of where the alignment padding goes.
363
Chris Lattner7d7dab02010-01-27 23:37:36 +0000364 // ARM and Thumb2 functions need to be 4-byte aligned.
365 if (!isThumb1)
366 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000367
Evan Chenga8e29892007-01-19 07:51:42 +0000368 // Perform the initial placement of the constant pool entries. To start with,
369 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000370 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000371 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000372 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000373 if (isThumb1)
Chris Lattner7d7dab02010-01-27 23:37:36 +0000374 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000375 }
Bob Wilson84945262009-05-12 17:09:30 +0000376
Evan Chenga8e29892007-01-19 07:51:42 +0000377 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000378 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000379
Evan Chenga8e29892007-01-19 07:51:42 +0000380 // Do the initial scan of the function, building up information about the
381 // sizes of each block, the location of all the water, and finding all of the
382 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000383 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000384 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000385 DEBUG(dumpBBs());
386
Bob Wilson84945262009-05-12 17:09:30 +0000387
Evan Chenged884f32007-04-03 23:39:48 +0000388 /// Remove dead constant pool entries.
Bill Wendlingcd080242010-12-18 01:53:06 +0000389 MadeChange |= RemoveUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000390
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000391 // Iteratively place constant pool entries and fix up branches until there
392 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000393 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000394 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000395 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000396 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000397 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000398 CPChange |= HandleConstantPoolUser(MF, i);
399 if (CPChange && ++NoCPIters > 30)
400 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000401 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000402
Bob Wilsonb9239532009-10-15 20:49:47 +0000403 // Clear NewWaterList now. If we split a block for branches, it should
404 // appear as "new water" for the next iteration of constant pool placement.
405 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000406
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000407 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000408 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000409 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000410 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
411 if (BRChange && ++NoBRIters > 30)
412 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000413 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000414
415 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000416 break;
417 MadeChange = true;
418 }
Evan Chenged884f32007-04-03 23:39:48 +0000419
Evan Chenga1efbbd2009-08-14 00:32:16 +0000420 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000421 if (isThumb2 && !STI->prefers32BitThumb())
Evan Chenga1efbbd2009-08-14 00:32:16 +0000422 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000423
Dale Johannesen8593e412007-04-29 19:19:30 +0000424 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000425 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000426
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000427 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
428 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000429 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000430 MadeChange |= UndoLRSpillRestore();
431
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000432 // Save the mapping between original and cloned constpool entries.
433 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
434 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
435 const CPEntry & CPE = CPEntries[i][j];
436 AFI->recordCPEClone(i, CPE.CPI);
437 }
438 }
439
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000440 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000441
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000442 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000443 WaterList.clear();
444 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000445 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000446 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000447 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000448 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000449
450 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000451}
452
453/// DoInitialPlacement - Perform the initial placement of the constant pool
454/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000455void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000456 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000457 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000458 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
459 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000460
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000461 // Mark the basic block as 4-byte aligned as required by the const-pool.
462 BB->setAlignment(2);
463
Evan Chenga8e29892007-01-19 07:51:42 +0000464 // Add all of the constants from the constant pool to the end block, use an
465 // identity mapping of CPI's to CPE's.
466 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000467 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000468
Evan Cheng5657c012009-07-29 02:18:14 +0000469 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000470 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000471 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000472 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
473 // we would have to pad them out or something so that instructions stay
474 // aligned.
475 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
476 MachineInstr *CPEMI =
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000477 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
478 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000479 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000480
481 // Add a new CPEntry, but no corresponding CPUser yet.
482 std::vector<CPEntry> CPEs;
483 CPEs.push_back(CPEntry(CPEMI, i));
484 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000485 ++NumCPEs;
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000486 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function as #" << i
Chris Lattner893e1c92009-08-23 06:49:22 +0000487 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000488 }
489}
490
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000491/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000492/// into the block immediately after it.
493static bool BBHasFallthrough(MachineBasicBlock *MBB) {
494 // Get the next machine basic block in the function.
495 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000496 // Can't fall off end of function.
497 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000498 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000499
Chris Lattner7896c9f2009-12-03 00:50:42 +0000500 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000501 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
502 E = MBB->succ_end(); I != E; ++I)
503 if (*I == NextBB)
504 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000505
Evan Chenga8e29892007-01-19 07:51:42 +0000506 return false;
507}
508
Evan Chengc99ef082007-02-09 20:54:44 +0000509/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
510/// look up the corresponding CPEntry.
511ARMConstantIslands::CPEntry
512*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
513 const MachineInstr *CPEMI) {
514 std::vector<CPEntry> &CPEs = CPEntries[CPI];
515 // Number of entries per constpool index should be small, just do a
516 // linear search.
517 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
518 if (CPEs[i].CPEMI == CPEMI)
519 return &CPEs[i];
520 }
521 return NULL;
522}
523
Jim Grosbach80697d12009-11-12 17:25:07 +0000524/// JumpTableFunctionScan - Do a scan of the function, building up
525/// information about the sizes of each block and the locations of all
526/// the jump tables.
527void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
Jim Grosbach80697d12009-11-12 17:25:07 +0000528 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
529 MBBI != E; ++MBBI) {
530 MachineBasicBlock &MBB = *MBBI;
531
Jim Grosbach80697d12009-11-12 17:25:07 +0000532 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000533 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000534 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000535 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000536 }
537}
538
Evan Chenga8e29892007-01-19 07:51:42 +0000539/// InitialFunctionScan - Do the initial scan of the function, building up
540/// information about the sizes of each block, the location of all the water,
541/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000542void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000543 const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000544 BBInfo.clear();
545 BBInfo.resize(MF.getNumBlockIDs());
546
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000547 // First thing, compute the size of all basic blocks, and see if the function
548 // has any inline assembly in it. If so, we have to be conservative about
549 // alignment assumptions, as we don't know for sure the size of any
550 // instructions in the inline assembly.
551 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
552 ComputeBlockSize(I);
553
554 // The known bits of the entry block offset are determined by the function
555 // alignment.
556 BBInfo.front().KnownBits = MF.getAlignment();
557
558 // Compute block offsets and known bits.
559 AdjustBBOffsetsAfter(MF.begin());
560
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000561 // Now go back through the instructions and build up our data structures.
Evan Cheng5657c012009-07-29 02:18:14 +0000562 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000563 MBBI != E; ++MBBI) {
564 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000565
Evan Chenga8e29892007-01-19 07:51:42 +0000566 // If this block doesn't fall through into the next MBB, then this is
567 // 'water' that a constant pool island could be placed.
568 if (!BBHasFallthrough(&MBB))
569 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000570
Evan Chenga8e29892007-01-19 07:51:42 +0000571 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
572 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000573 if (I->isDebugValue())
574 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000575
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000576 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000577 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000578 bool isCond = false;
579 unsigned Bits = 0;
580 unsigned Scale = 1;
581 int UOpc = Opc;
582 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000583 default:
584 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000585 case ARM::t2BR_JT:
586 T2JumpTables.push_back(I);
587 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000588 case ARM::Bcc:
589 isCond = true;
590 UOpc = ARM::B;
591 // Fallthrough
592 case ARM::B:
593 Bits = 24;
594 Scale = 4;
595 break;
596 case ARM::tBcc:
597 isCond = true;
598 UOpc = ARM::tB;
599 Bits = 8;
600 Scale = 2;
601 break;
602 case ARM::tB:
603 Bits = 11;
604 Scale = 2;
605 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000606 case ARM::t2Bcc:
607 isCond = true;
608 UOpc = ARM::t2B;
609 Bits = 20;
610 Scale = 2;
611 break;
612 case ARM::t2B:
613 Bits = 24;
614 Scale = 2;
615 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000616 }
Evan Chengb43216e2007-02-01 10:16:15 +0000617
618 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000619 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000620 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000621 }
622
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000623 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
624 PushPopMIs.push_back(I);
625
Evan Chengd3d9d662009-07-23 18:27:47 +0000626 if (Opc == ARM::CONSTPOOL_ENTRY)
627 continue;
628
Evan Chenga8e29892007-01-19 07:51:42 +0000629 // Scan the instructions for constant pool operands.
630 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000631 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000632 // We found one. The addressing mode tells us the max displacement
633 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000634
Evan Chenga8e29892007-01-19 07:51:42 +0000635 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000636 unsigned Bits = 0;
637 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000638 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000639 bool IsSoImm = false;
640
641 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000642 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000643 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000644 break;
645
646 // Taking the address of a CP entry.
647 case ARM::LEApcrel:
648 // This takes a SoImm, which is 8 bit immediate rotated. We'll
649 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000650 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000651 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000652 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000653 Scale = 4;
654 NegOk = true;
655 IsSoImm = true;
656 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000657 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000658 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000659 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000660 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000661 case ARM::tLEApcrel:
662 Bits = 8;
663 Scale = 4;
664 break;
665
Jim Grosbach3e556122010-10-26 22:37:02 +0000666 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000667 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000668 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000669 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000670 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000671 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000672
673 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000674 Bits = 8;
675 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000676 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000677
Jim Grosbache5165492009-11-09 00:11:35 +0000678 case ARM::VLDRD:
679 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000680 Bits = 8;
681 Scale = 4; // +-(offset_8*4)
682 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000683 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000684 }
Evan Chengb43216e2007-02-01 10:16:15 +0000685
Evan Chenga8e29892007-01-19 07:51:42 +0000686 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000687 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000688 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000689 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000690 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000691
692 // Increment corresponding CPEntry reference count.
693 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
694 assert(CPE && "Cannot find a corresponding CPEntry!");
695 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000696
Evan Chenga8e29892007-01-19 07:51:42 +0000697 // Instructions can only use one CP entry, don't bother scanning the
698 // rest of the operands.
699 break;
700 }
701 }
Evan Chenga8e29892007-01-19 07:51:42 +0000702 }
703}
704
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000705/// ComputeBlockSize - Compute the size and some alignment information for MBB.
706/// This function updates BBInfo directly.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000707void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000708 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
709 BBI.Size = 0;
710 BBI.Unalign = 0;
711 BBI.PostAlign = 0;
712
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000713 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
714 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000715 BBI.Size += TII->GetInstSizeInBytes(I);
716 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
717 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000718 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000719 BBI.Unalign = isThumb ? 1 : 2;
720 }
721
722 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000723 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000724 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000725 MBB->getParent()->EnsureAlignment(2);
726 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000727}
728
Evan Chenga8e29892007-01-19 07:51:42 +0000729/// GetOffsetOf - Return the current offset of the specified machine instruction
730/// from the start of the function. This offset changes as stuff is moved
731/// around inside the function.
732unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
733 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000734
Evan Chenga8e29892007-01-19 07:51:42 +0000735 // The offset is composed of two things: the sum of the sizes of all MBB's
736 // before this instruction's block, and the offset from the start of the block
737 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000738 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000739
740 // Sum instructions before MI in MBB.
741 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
742 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
743 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000744 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000745 }
746}
747
748/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
749/// ID.
750static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
751 const MachineBasicBlock *RHS) {
752 return LHS->getNumber() < RHS->getNumber();
753}
754
755/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
756/// machine function, it upsets all of the block numbers. Renumber the blocks
757/// and update the arrays that parallel this numbering.
758void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000759 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000760 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000761
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000762 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000763 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000764 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000765
766 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000767 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000768 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000769 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
770 CompareMBBNumbers);
771 WaterList.insert(IP, NewBB);
772}
773
774
775/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000776/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000777/// account for this change and returns the newly created block.
778MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000779 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000780 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000781
782 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000783 MachineBasicBlock *NewBB =
784 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000785 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000786 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000787
Evan Chenga8e29892007-01-19 07:51:42 +0000788 // Splice the instructions starting with MI over to NewBB.
789 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000790
Evan Chenga8e29892007-01-19 07:51:42 +0000791 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000792 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000793 // There doesn't seem to be meaningful DebugInfo available; this doesn't
794 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000795 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000796 if (!isThumb)
797 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
798 else
799 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
800 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000801 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000802
Evan Chenga8e29892007-01-19 07:51:42 +0000803 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000804 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000805
Evan Chenga8e29892007-01-19 07:51:42 +0000806 // OrigBB branches to NewBB.
807 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000808
Evan Chenga8e29892007-01-19 07:51:42 +0000809 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000810 // This is almost the same as UpdateForInsertedWaterBlock, except that
811 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000812 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000813
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000814 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000815 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000816 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000817
Bob Wilson84945262009-05-12 17:09:30 +0000818 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000819 // available water after it (but not if it's already there, which happens
820 // when splitting before a conditional branch that is followed by an
821 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000822 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000823 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
824 CompareMBBNumbers);
825 MachineBasicBlock* WaterBB = *IP;
826 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000827 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000828 else
829 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000830 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000831
Dale Johannesen8086d582010-07-23 22:50:23 +0000832 // Figure out how large the OrigBB is. As the first half of the original
833 // block, it cannot contain a tablejump. The size includes
834 // the new jump we added. (It should be possible to do this without
835 // recounting everything, but it's very confusing, and this is rarely
836 // executed.)
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000837 ComputeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000838
Dale Johannesen8086d582010-07-23 22:50:23 +0000839 // Figure out how large the NewMBB is. As the second half of the original
840 // block, it may contain a tablejump.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000841 ComputeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000842
Dale Johannesen99c49a42007-02-25 00:47:03 +0000843 // All BBOffsets following these blocks must be modified.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000844 AdjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000845
846 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000847}
848
Dale Johannesen8593e412007-04-29 19:19:30 +0000849/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000850/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000851/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000852bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000853 unsigned TrialOffset, unsigned MaxDisp,
854 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000855 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
856 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000857 // Effectively, the valid range of displacements is 2 bytes smaller for such
858 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000859 unsigned TotalAdj = 0;
860 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000861 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000862 TotalAdj = 2;
863 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000864 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000865 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000866 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000867 TotalAdj += 2;
868 }
869
870 // In Thumb2 mode, later branch adjustments can shift instructions up and
871 // cause alignment change. In the worst case scenario this can cause the
872 // user's effective address to be subtracted by 2 and the CPE's address to
873 // be plus 2.
874 if (isThumb2 && TotalAdj != 4)
875 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000876
Dale Johannesen99c49a42007-02-25 00:47:03 +0000877 if (UserOffset <= TrialOffset) {
878 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000879 if (TrialOffset - UserOffset <= MaxDisp)
880 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000881 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000882 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000883 if (UserOffset - TrialOffset <= MaxDisp)
884 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000885 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000886 }
887 return false;
888}
889
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000890/// WaterIsInRange - Returns true if a CPE placed after the specified
891/// Water (a basic block) will be in range for the specific MI.
892
893bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000894 MachineBasicBlock* Water, CPUser &U) {
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000895 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000896
Dale Johannesend959aa42007-04-02 20:31:06 +0000897 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000898 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000899 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000900 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000901
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000902 return OffsetIsInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000903}
904
905/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000906/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000907bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000908 MachineInstr *CPEMI, unsigned MaxDisp,
909 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000910 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000911 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000912
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000913 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000914 DEBUG({
915 unsigned Block = MI->getParent()->getNumber();
916 const BasicBlockInfo &BBI = BBInfo[Block];
917 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
918 << " max delta=" << MaxDisp
919 << " insn address=" << UserOffset
920 << " in BB#" << Block << ": "
921 << BBI.Offset << " - " << BBI.postOffset() << "\t" << *MI
922 << "CPE address=" << CPEOffset
923 << " offset=" << int(CPEOffset-UserOffset) << ": ";
924 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000925 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000926
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000927 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000928}
929
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000930#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000931/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
932/// unconditionally branches to its only successor.
933static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
934 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
935 return false;
936
937 MachineBasicBlock *Succ = *MBB->succ_begin();
938 MachineBasicBlock *Pred = *MBB->pred_begin();
939 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000940 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
941 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000942 return PredMI->getOperand(0).getMBB() == Succ;
943 return false;
944}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000945#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000946
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000947void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000948 MachineFunction *MF = BB->getParent();
949 for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
950 // Get the offset and known bits at the end of the layout predecessor.
951 unsigned Offset = BBInfo[i - 1].postOffset();
952 unsigned KnownBits = BBInfo[i - 1].postKnownBits();
953
954 // Add padding before an aligned block. This may teach us more bits.
955 if (unsigned Align = MF->getBlockNumbered(i)->getAlignment()) {
956 Offset = WorstCaseAlign(Offset, Align, KnownBits);
957 KnownBits = std::max(KnownBits, Align);
Dale Johannesen8593e412007-04-29 19:19:30 +0000958 }
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000959
960 // This is where block i begins.
961 BBInfo[i].Offset = Offset;
962 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +0000963 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000964}
965
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000966/// DecrementOldEntry - find the constant pool entry with index CPI
967/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000968/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000969/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000970
Evan Chenged884f32007-04-03 23:39:48 +0000971bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000972 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000973 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
974 assert(CPE && "Unexpected!");
975 if (--CPE->RefCount == 0) {
976 RemoveDeadCPEMI(CPEMI);
977 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +0000978 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000979 return true;
980 }
981 return false;
982}
983
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000984/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
985/// if not, see if an in-range clone of the CPE is in range, and if so,
986/// change the data structures so the user references the clone. Returns:
987/// 0 = no existing entry found
988/// 1 = entry found, and there were no code insertions or deletions
989/// 2 = entry found, and there were code insertions or deletions
990int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
991{
992 MachineInstr *UserMI = U.MI;
993 MachineInstr *CPEMI = U.CPEMI;
994
995 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000996 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000997 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000998 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000999 }
1000
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001001 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001002 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001003 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1004 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1005 // We already tried this one
1006 if (CPEs[i].CPEMI == CPEMI)
1007 continue;
1008 // Removing CPEs can leave empty entries, skip
1009 if (CPEs[i].CPEMI == NULL)
1010 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001011 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001012 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001013 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001014 // Point the CPUser node to the replacement
1015 U.CPEMI = CPEs[i].CPEMI;
1016 // Change the CPI in the instruction operand to refer to the clone.
1017 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001018 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001019 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001020 break;
1021 }
1022 // Adjust the refcount of the clone...
1023 CPEs[i].RefCount++;
1024 // ...and the original. If we didn't remove the old entry, none of the
1025 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001026 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001027 }
1028 }
1029 return 0;
1030}
1031
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001032/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1033/// the specific unconditional branch instruction.
1034static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001035 switch (Opc) {
1036 case ARM::tB:
1037 return ((1<<10)-1)*2;
1038 case ARM::t2B:
1039 return ((1<<23)-1)*2;
1040 default:
1041 break;
1042 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001043
David Goodwin5e47a9a2009-06-30 18:04:13 +00001044 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001045}
1046
Bob Wilsonb9239532009-10-15 20:49:47 +00001047/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001048/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001049/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001050/// is set to the WaterList entry. For Thumb, prefer water that will not
1051/// introduce padding to water that will. To ensure that this pass
1052/// terminates, the CPE location for a particular CPUser is only allowed to
1053/// move to a lower address, so search backward from the end of the list and
1054/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001055bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001056 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001057 if (WaterList.empty())
1058 return false;
1059
Bob Wilson32c50e82009-10-12 20:45:53 +00001060 bool FoundWaterThatWouldPad = false;
1061 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001062 for (water_iterator IP = prior(WaterList.end()),
1063 B = WaterList.begin();; --IP) {
1064 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001065 // Check if water is in range and is either at a lower address than the
1066 // current "high water mark" or a new water block that was created since
1067 // the previous iteration by inserting an unconditional branch. In the
1068 // latter case, we want to allow resetting the high water mark back to
1069 // this new water since we haven't seen it before. Inserting branches
1070 // should be relatively uncommon and when it does happen, we want to be
1071 // sure to take advantage of it for all the CPEs near that block, so that
1072 // we don't insert more branches than necessary.
1073 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1074 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1075 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001076 unsigned WBBId = WaterBB->getNumber();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001077 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
Bob Wilson3b757352009-10-12 19:04:03 +00001078 // This is valid Water, but would introduce padding. Remember
1079 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001080 if (!FoundWaterThatWouldPad) {
1081 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001082 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001083 }
Bob Wilson3b757352009-10-12 19:04:03 +00001084 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001085 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001086 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001087 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001088 }
Bob Wilson3b757352009-10-12 19:04:03 +00001089 if (IP == B)
1090 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001091 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001092 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001093 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001094 return true;
1095 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001096 return false;
1097}
1098
Bob Wilson84945262009-05-12 17:09:30 +00001099/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001100/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1101/// block is used if in range, and the conditional branch munged so control
1102/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001103/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001104/// block following which the new island can be inserted (the WaterList
1105/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001106void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001107 unsigned UserOffset,
1108 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001109 CPUser &U = CPUsers[CPUserIndex];
1110 MachineInstr *UserMI = U.MI;
1111 MachineInstr *CPEMI = U.CPEMI;
1112 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +00001113 unsigned OffsetOfNextBlock = BBInfo[UserMBB->getNumber()].postOffset();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001114
Bob Wilson36fa5322009-10-15 05:10:36 +00001115 // If the block does not end in an unconditional branch already, and if the
1116 // end of the block is within range, make new water there. (The addition
1117 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1118 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001119 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001120 if (BBHasFallthrough(UserMBB) &&
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001121 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4), U)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001122 DEBUG(dbgs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001123 if (&UserMBB->back() == UserMI)
1124 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001125 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001126 // Add an unconditional branch from UserMBB to fallthrough block.
1127 // Record it for branch lengthening; this new branch will not get out of
1128 // range, but if the preceding conditional branch is out of range, the
1129 // targets will be exchanged, and the altered branch may be out of
1130 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001131 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001132 if (!isThumb)
1133 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1134 else
1135 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1136 .addImm(ARMCC::AL).addReg(0);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001137 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001138 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001139 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001140 int delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001141 BBInfo[UserMBB->getNumber()].Size += delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001142 AdjustBBOffsetsAfter(UserMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001143 } else {
1144 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001145 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001146 // and constant pool entries are 4 bytes: if instruction I references
1147 // island CPE, and instruction I+1 references CPE', it will
1148 // not work well to put CPE as far forward as possible, since then
1149 // CPE' cannot immediately follow it (that location is 2 bytes
1150 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001151 // a new island. So, we make a first guess, then walk through the
1152 // instructions between the one currently being looked at and the
1153 // possible insertion point, and make sure any other instructions
1154 // that reference CPEs will be able to use the same island area;
1155 // if not, we back up the insertion point.
1156
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001157 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001158 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001159 // island is handled inside OffsetIsInRange.
1160 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001161 // This could point off the end of the block if we've already got
1162 // constant pool entries following this block; only the last one is
1163 // in the water list. Back past any possible branches (allow for a
1164 // conditional and a maximally long unconditional).
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001165 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1166 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
Evan Chengd3d9d662009-07-23 18:27:47 +00001167 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001168 unsigned EndInsertOffset = BaseInsertOffset +
1169 CPEMI->getOperand(2).getImm();
1170 MachineBasicBlock::iterator MI = UserMI;
1171 ++MI;
1172 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001173 unsigned NumCPUsers = CPUsers.size();
1174 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001175 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001176 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001177 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001178 MI = llvm::next(MI)) {
1179 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001180 CPUser &U = CPUsers[CPUIndex];
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +00001181 if (!OffsetIsInRange(Offset, EndInsertOffset, U)) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001182 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1183 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001184 }
1185 // This is overly conservative, as we don't account for CPEMIs
1186 // being reused within the block, but it doesn't matter much.
1187 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1188 CPUIndex++;
1189 }
Evan Cheng719510a2010-08-12 20:30:05 +00001190
1191 // Remember the last IT instruction.
1192 if (MI->getOpcode() == ARM::t2IT)
1193 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001194 }
Evan Cheng719510a2010-08-12 20:30:05 +00001195
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001196 DEBUG(dbgs() << "Split in middle of big block\n");
Evan Cheng719510a2010-08-12 20:30:05 +00001197 --MI;
1198
1199 // Avoid splitting an IT block.
1200 if (LastIT) {
1201 unsigned PredReg = 0;
1202 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1203 if (CC != ARMCC::AL)
1204 MI = LastIT;
1205 }
1206 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001207 }
1208}
1209
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001210/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001211/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001212/// place in-range. Return true if we changed any addresses (thus must run
1213/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001214bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001215 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001216 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001217 MachineInstr *UserMI = U.MI;
1218 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001219 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001220 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001221 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001222 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001223 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001224
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001225 // See if the current entry is within range, or there is a clone of it
1226 // in range.
1227 int result = LookForExistingCPEntry(U, UserOffset);
1228 if (result==1) return false;
1229 else if (result==2) return true;
1230
1231 // No existing clone of this CPE is within range.
1232 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001233 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001234
Bob Wilsonf98032e2009-10-12 21:23:15 +00001235 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001236 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1237 MachineBasicBlock *NewMBB;
1238 water_iterator IP;
1239 if (LookForWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001240 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001241 MachineBasicBlock *WaterBB = *IP;
1242
1243 // If the original WaterList entry was "new water" on this iteration,
1244 // propagate that to the new island. This is just keeping NewWaterList
1245 // updated to match the WaterList, which will be updated below.
1246 if (NewWaterList.count(WaterBB)) {
1247 NewWaterList.erase(WaterBB);
1248 NewWaterList.insert(NewIsland);
1249 }
1250 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001251 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001252
1253 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001254 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001255 DEBUG(dbgs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001256 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001257
1258 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1259 // called while handling branches so that the water will be seen on the
1260 // next iteration for constant pools, but in this context, we don't want
1261 // it. Check for this so it will be removed from the WaterList.
1262 // Also remove any entry from NewWaterList.
1263 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1264 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1265 if (IP != WaterList.end())
1266 NewWaterList.erase(WaterBB);
1267
1268 // We are adding new water. Update NewWaterList.
1269 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001270 }
1271
Bob Wilsonb9239532009-10-15 20:49:47 +00001272 // Remove the original WaterList entry; we want subsequent insertions in
1273 // this vicinity to go after the one we're about to insert. This
1274 // considerably reduces the number of times we have to move the same CPE
1275 // more than once and is also important to ensure the algorithm terminates.
1276 if (IP != WaterList.end())
1277 WaterList.erase(IP);
1278
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001279 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001280 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001281
1282 // Update internal data structures to account for the newly inserted MBB.
1283 UpdateForInsertedWaterBlock(NewIsland);
1284
1285 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001286 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001287
1288 // Now that we have an island to add the CPE to, clone the original CPE and
1289 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001290 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001291 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001292 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001293 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001294 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001295
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001296 // Mark the basic block as 4-byte aligned as required by the const-pool entry.
1297 NewIsland->setAlignment(2);
1298
Evan Chenga8e29892007-01-19 07:51:42 +00001299 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001300 BBInfo[NewIsland->getNumber()].Size += Size;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001301 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001302
Evan Chenga8e29892007-01-19 07:51:42 +00001303 // Finally, change the CPI in the instruction operand to be ID.
1304 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001305 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001306 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001307 break;
1308 }
Bob Wilson84945262009-05-12 17:09:30 +00001309
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001310 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1311 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001312
Evan Chenga8e29892007-01-19 07:51:42 +00001313 return true;
1314}
1315
Evan Chenged884f32007-04-03 23:39:48 +00001316/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1317/// sizes and offsets of impacted basic blocks.
1318void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1319 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001320 unsigned Size = CPEMI->getOperand(2).getImm();
1321 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001322 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001323 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001324 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001325 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001326 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001327 // empty, so fix this.
1328 // All succeeding offsets have the current size value added in, fix this.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001329 if (BBInfo[CPEBB->getNumber()].Size != 0) {
1330 Size += BBInfo[CPEBB->getNumber()].Size;
1331 BBInfo[CPEBB->getNumber()].Size = 0;
Evan Chenged884f32007-04-03 23:39:48 +00001332 }
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001333
1334 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1335 CPEBB->setAlignment(0);
Evan Chenged884f32007-04-03 23:39:48 +00001336 }
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001337 AdjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001338 // An island has only one predecessor BB and one successor BB. Check if
1339 // this BB's predecessor jumps directly to this BB's successor. This
1340 // shouldn't happen currently.
1341 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1342 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001343}
1344
1345/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1346/// are zero.
1347bool ARMConstantIslands::RemoveUnusedCPEntries() {
1348 unsigned MadeChange = false;
1349 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1350 std::vector<CPEntry> &CPEs = CPEntries[i];
1351 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1352 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1353 RemoveDeadCPEMI(CPEs[j].CPEMI);
1354 CPEs[j].CPEMI = NULL;
1355 MadeChange = true;
1356 }
1357 }
Bob Wilson84945262009-05-12 17:09:30 +00001358 }
Evan Chenged884f32007-04-03 23:39:48 +00001359 return MadeChange;
1360}
1361
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001362/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001363/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001364bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1365 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001366 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001367 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001368 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001369
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001370 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001371 << " from BB#" << MI->getParent()->getNumber()
1372 << " max delta=" << MaxDisp
1373 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1374 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001375
Dale Johannesen8593e412007-04-29 19:19:30 +00001376 if (BrOffset <= DestOffset) {
1377 // Branch before the Dest.
1378 if (DestOffset-BrOffset <= MaxDisp)
1379 return true;
1380 } else {
1381 if (BrOffset-DestOffset <= MaxDisp)
1382 return true;
1383 }
1384 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001385}
1386
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001387/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1388/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001389bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001390 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001391 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001392
Evan Chengc0dbec72007-01-31 19:57:44 +00001393 // Check to see if the DestBB is already in-range.
1394 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001395 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001396
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001397 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001398 return FixUpUnconditionalBr(MF, Br);
1399 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001400}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001401
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001402/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1403/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001404/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001405/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001406bool
Evan Cheng5657c012009-07-29 02:18:14 +00001407ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001408 MachineInstr *MI = Br.MI;
1409 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001410 if (!isThumb1)
1411 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001412
1413 // Use BL to implement far jump.
1414 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001415 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001416 BBInfo[MBB->getNumber()].Size += 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001417 AdjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001418 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001419 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001420
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001421 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001422
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001423 return true;
1424}
1425
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001426/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001427/// far away to fit in its displacement field. It is converted to an inverse
1428/// conditional branch + an unconditional branch to the destination.
1429bool
Evan Cheng5657c012009-07-29 02:18:14 +00001430ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001431 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001432 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001433
Bob Wilson39bf0512009-05-12 17:35:29 +00001434 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001435 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001436 // blt L1
1437 // =>
1438 // bge L2
1439 // b L1
1440 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001441 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001442 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001443 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001444
1445 // If the branch is at the end of its MBB and that has a fall-through block,
1446 // direct the updated conditional branch to the fall-through block. Otherwise,
1447 // split the MBB before the next instruction.
1448 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001449 MachineInstr *BMI = &MBB->back();
1450 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001451
Dan Gohmanfe601042010-06-22 15:08:57 +00001452 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001453 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001454 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001455 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001456 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001457 // condition and swap destinations:
1458 // beq L1
1459 // b L2
1460 // =>
1461 // bne L2
1462 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001463 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001464 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001465 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001466 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001467 BMI->getOperand(0).setMBB(DestBB);
1468 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001469 MI->getOperand(1).setImm(CC);
1470 return true;
1471 }
1472 }
1473 }
1474
1475 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001476 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001477 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001478 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001479 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001480 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001481 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001482 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001483 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001484 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001485
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001486 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001487 << " also invert condition and change dest. to BB#"
1488 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001489
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001490 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001491 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001492 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001493 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001494 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001495 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001496 if (isThumb)
1497 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1498 .addImm(ARMCC::AL).addReg(0);
1499 else
1500 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001501 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001502 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001503 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001504
1505 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001506 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001507 MI->eraseFromParent();
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001508 AdjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001509 return true;
1510}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001511
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001512/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001513/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1514/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001515bool ARMConstantIslands::UndoLRSpillRestore() {
1516 bool MadeChange = false;
1517 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1518 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001519 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001520 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001521 MI->getOperand(2).getReg() == ARM::PC &&
1522 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001523 // Create the new insn and copy the predicate from the old.
1524 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1525 .addOperand(MI->getOperand(0))
1526 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001527 MI->eraseFromParent();
1528 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001529 }
1530 }
1531 return MadeChange;
1532}
Evan Cheng5657c012009-07-29 02:18:14 +00001533
Evan Chenga1efbbd2009-08-14 00:32:16 +00001534bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1535 bool MadeChange = false;
1536
1537 // Shrink ADR and LDR from constantpool.
1538 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1539 CPUser &U = CPUsers[i];
1540 unsigned Opcode = U.MI->getOpcode();
1541 unsigned NewOpc = 0;
1542 unsigned Scale = 1;
1543 unsigned Bits = 0;
1544 switch (Opcode) {
1545 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001546 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001547 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1548 NewOpc = ARM::tLEApcrel;
1549 Bits = 8;
1550 Scale = 4;
1551 }
1552 break;
1553 case ARM::t2LDRpci:
1554 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1555 NewOpc = ARM::tLDRpci;
1556 Bits = 8;
1557 Scale = 4;
1558 }
1559 break;
1560 }
1561
1562 if (!NewOpc)
1563 continue;
1564
1565 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1566 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1567 // FIXME: Check if offset is multiple of scale if scale is not 4.
1568 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1569 U.MI->setDesc(TII->get(NewOpc));
1570 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001571 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001572 AdjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001573 ++NumT2CPShrunk;
1574 MadeChange = true;
1575 }
1576 }
1577
Evan Chenga1efbbd2009-08-14 00:32:16 +00001578 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001579 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001580 return MadeChange;
1581}
1582
1583bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001584 bool MadeChange = false;
1585
1586 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1587 ImmBranch &Br = ImmBranches[i];
1588 unsigned Opcode = Br.MI->getOpcode();
1589 unsigned NewOpc = 0;
1590 unsigned Scale = 1;
1591 unsigned Bits = 0;
1592 switch (Opcode) {
1593 default: break;
1594 case ARM::t2B:
1595 NewOpc = ARM::tB;
1596 Bits = 11;
1597 Scale = 2;
1598 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001599 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001600 NewOpc = ARM::tBcc;
1601 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001602 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001603 break;
1604 }
Evan Chengde17fb62009-10-31 23:46:45 +00001605 }
1606 if (NewOpc) {
1607 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1608 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1609 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1610 Br.MI->setDesc(TII->get(NewOpc));
1611 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001612 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001613 AdjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001614 ++NumT2BrShrunk;
1615 MadeChange = true;
1616 }
1617 }
1618
1619 Opcode = Br.MI->getOpcode();
1620 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001621 continue;
1622
Evan Chengde17fb62009-10-31 23:46:45 +00001623 NewOpc = 0;
1624 unsigned PredReg = 0;
1625 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1626 if (Pred == ARMCC::EQ)
1627 NewOpc = ARM::tCBZ;
1628 else if (Pred == ARMCC::NE)
1629 NewOpc = ARM::tCBNZ;
1630 if (!NewOpc)
1631 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001632 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001633 // Check if the distance is within 126. Subtract starting offset by 2
1634 // because the cmp will be eliminated.
1635 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001636 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001637 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001638 MachineBasicBlock::iterator CmpMI = Br.MI;
1639 if (CmpMI != Br.MI->getParent()->begin()) {
1640 --CmpMI;
1641 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1642 unsigned Reg = CmpMI->getOperand(0).getReg();
1643 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1644 if (Pred == ARMCC::AL &&
1645 CmpMI->getOperand(1).getImm() == 0 &&
1646 isARMLowRegister(Reg)) {
1647 MachineBasicBlock *MBB = Br.MI->getParent();
1648 MachineInstr *NewBR =
1649 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1650 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1651 CmpMI->eraseFromParent();
1652 Br.MI->eraseFromParent();
1653 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001654 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001655 AdjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001656 ++NumCBZ;
1657 MadeChange = true;
1658 }
Evan Chengde17fb62009-10-31 23:46:45 +00001659 }
1660 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001661 }
1662 }
1663
1664 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001665}
1666
Evan Chenga1efbbd2009-08-14 00:32:16 +00001667/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1668/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001669bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1670 bool MadeChange = false;
1671
1672 // FIXME: After the tables are shrunk, can we get rid some of the
1673 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001674 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001675 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001676
Evan Cheng5657c012009-07-29 02:18:14 +00001677 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1678 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1679 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001680 const MCInstrDesc &MCID = MI->getDesc();
1681 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001682 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001683 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1684 unsigned JTI = JTOP.getIndex();
1685 assert(JTI < JT.size());
1686
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001687 bool ByteOk = true;
1688 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001689 unsigned JTOffset = GetOffsetOf(MI) + 4;
1690 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001691 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1692 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001693 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001694 // Negative offset is not ok. FIXME: We should change BB layout to make
1695 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001696 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001697 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001698 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001699 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001700 HalfWordOk = false;
1701 if (!ByteOk && !HalfWordOk)
1702 break;
1703 }
1704
1705 if (ByteOk || HalfWordOk) {
1706 MachineBasicBlock *MBB = MI->getParent();
1707 unsigned BaseReg = MI->getOperand(0).getReg();
1708 bool BaseRegKill = MI->getOperand(0).isKill();
1709 if (!BaseRegKill)
1710 continue;
1711 unsigned IdxReg = MI->getOperand(1).getReg();
1712 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001713
1714 // Scan backwards to find the instruction that defines the base
1715 // register. Due to post-RA scheduling, we can't count on it
1716 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001717 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001718 MachineBasicBlock::iterator B = MBB->begin();
1719 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1720 --PrevI;
1721
1722 // If for some reason we didn't find it, we can't do anything, so
1723 // just skip this one.
1724 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001725 continue;
1726
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001727 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001728 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001729 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001730 // Make sure it only defines the base register and kills any uses
1731 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001732 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1733 const MachineOperand &MO = AddrMI->getOperand(k);
1734 if (!MO.isReg() || !MO.getReg())
1735 continue;
1736 if (MO.isDef() && MO.getReg() != BaseReg) {
1737 OptOk = false;
1738 break;
1739 }
1740 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1741 OptOk = false;
1742 break;
1743 }
1744 }
1745 if (!OptOk)
1746 continue;
1747
Owen Anderson6b8719f2010-12-13 22:51:08 +00001748 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001749 // that gave us the initial base register definition.
1750 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1751 ;
1752
Owen Anderson6b8719f2010-12-13 22:51:08 +00001753 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001754 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001755 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001756 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001757 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001758 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001759 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001760
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001761 if (!OptOk)
1762 continue;
1763
Jim Grosbachd092a872010-11-29 21:28:32 +00001764 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001765 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1766 .addReg(IdxReg, getKillRegState(IdxRegKill))
1767 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1768 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1769 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1770 // is 2-byte aligned. For now, asm printer will fix it up.
1771 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1772 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1773 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1774 OrigSize += TII->GetInstSizeInBytes(MI);
1775
1776 AddrMI->eraseFromParent();
1777 LeaMI->eraseFromParent();
1778 MI->eraseFromParent();
1779
1780 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001781 BBInfo[MBB->getNumber()].Size -= delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001782 AdjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001783
1784 ++NumTBs;
1785 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001786 }
1787 }
1788
1789 return MadeChange;
1790}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001791
Jim Grosbach9249efe2009-11-16 18:55:47 +00001792/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1793/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach80697d12009-11-12 17:25:07 +00001794bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1795 bool MadeChange = false;
1796
1797 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001798 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001799
Jim Grosbach80697d12009-11-12 17:25:07 +00001800 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1801 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1802 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001803 const MCInstrDesc &MCID = MI->getDesc();
1804 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001805 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001806 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1807 unsigned JTI = JTOP.getIndex();
1808 assert(JTI < JT.size());
1809
1810 // We prefer if target blocks for the jump table come after the jump
1811 // instruction so we can use TB[BH]. Loop through the target blocks
1812 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001813 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001814 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1815 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1816 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001817 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001818
Jim Grosbach08cbda52009-11-16 18:58:52 +00001819 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001820 // The destination precedes the switch. Try to move the block forward
1821 // so we have a positive offset.
1822 MachineBasicBlock *NewBB =
1823 AdjustJTTargetBlockForward(MBB, MI->getParent());
1824 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001825 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001826 MadeChange = true;
1827 }
1828 }
1829 }
1830
1831 return MadeChange;
1832}
1833
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001834MachineBasicBlock *ARMConstantIslands::
1835AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1836{
1837 MachineFunction &MF = *BB->getParent();
1838
Jim Grosbach03e2d442010-07-07 22:53:35 +00001839 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001840 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001841 // table that branches back to the actual target. This is a very simple
1842 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001843 MachineBasicBlock *TBB = 0, *FBB = 0;
1844 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001845 SmallVector<MachineOperand, 4> CondPrior;
1846 MachineFunction::iterator BBi = BB;
1847 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001848
Jim Grosbachca215e72009-11-16 17:10:56 +00001849 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001850 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001851
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001852 // If the block ends in an unconditional branch, move it. The prior block
1853 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001854 // and make sure we're not trying to move the entry block of the function.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001855 if (!B && Cond.empty() && BB != MF.begin() &&
1856 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001857 BB->moveAfter(JTBB);
1858 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001859 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001860 // Update numbering to account for the block being moved.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001861 MF.RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001862 ++NumJTMoved;
1863 return NULL;
1864 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001865
1866 // Create a new MBB for the code after the jump BB.
1867 MachineBasicBlock *NewBB =
1868 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1869 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1870 MF.insert(MBBI, NewBB);
1871
1872 // Add an unconditional branch from NewBB to BB.
1873 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1874 // correspond directly to anything in the source.
1875 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001876 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1877 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001878
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001879 // Update internal data structures to account for the newly inserted MBB.
1880 MF.RenumberBlocks(NewBB);
1881
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001882 // Update the CFG.
1883 NewBB->addSuccessor(BB);
1884 JTBB->removeSuccessor(BB);
1885 JTBB->addSuccessor(NewBB);
1886
Jim Grosbach80697d12009-11-12 17:25:07 +00001887 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001888 return NewBB;
1889}