blob: 36be2308c97cfa4d0781eea3a9027dbe4e1190ba [file] [log] [blame]
Bill Wendling9a4d2e42010-12-21 01:54:40 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
Evan Chenga8e29892007-01-19 07:51:42 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chenga8e29892007-01-19 07:51:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000018#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000019#include "ARMInstrInfo.h"
Evan Cheng719510a2010-08-12 20:30:05 +000020#include "Thumb2InstrInfo.h"
Evan Chengee04a6d2011-07-20 23:34:39 +000021#include "MCTargetDesc/ARMAddressingModes.h"
Evan Chenga8e29892007-01-19 07:51:42 +000022#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +000029#include "llvm/Support/Format.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000030#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000031#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000032#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000033#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000035#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000036#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000037using namespace llvm;
38
Evan Chenga1efbbd2009-08-14 00:32:16 +000039STATISTIC(NumCPEs, "Number of constpool entries");
40STATISTIC(NumSplit, "Number of uncond branches inserted");
41STATISTIC(NumCBrFixed, "Number of cond branches fixed");
42STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
43STATISTIC(NumTBs, "Number of table branches generated");
44STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000045STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000046STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000047STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000048STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000049
50
51static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000052AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000053 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000054
Jakob Stoklund Olesenf5bb45f2011-12-16 16:07:41 +000055// FIXME: This option should be removed once it has received sufficient testing.
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +000056static cl::opt<bool>
Jakob Stoklund Olesenb6ff6ec2011-12-15 22:14:45 +000057AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(true),
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +000058 cl::desc("Align constant islands in code"));
59
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000060/// UnknownPadding - Return the worst case padding that could result from
61/// unknown offset bits. This does not include alignment padding caused by
62/// known offset bits.
63///
64/// @param LogAlign log2(alignment)
65/// @param KnownBits Number of known low offset bits.
66static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
67 if (KnownBits < LogAlign)
68 return (1u << LogAlign) - (1u << KnownBits);
69 return 0;
70}
71
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000072/// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
73/// add padding such that:
74///
75/// 1. The result is aligned to 1 << LogAlign.
76///
77/// 2. No other value of the unknown bits would require more padding.
78///
79/// This may add more padding than is required to satisfy just one of the
80/// constraints. It is necessary to compute alignment this way to guarantee
81/// that we don't underestimate the padding before an aligned block. If the
82/// real padding before a block is larger than we think, constant pool entries
83/// may go out of range.
84static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
85 unsigned KnownBits) {
86 // Add the worst possible padding that the unknown bits could cause.
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +000087 Offset += UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +000088
89 // Then align the result.
90 return RoundUpToAlignment(Offset, 1u << LogAlign);
91}
92
Evan Chenga8e29892007-01-19 07:51:42 +000093namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000094 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000095 /// requires constant pool entries to be scattered among the instructions
96 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000097 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000098 /// special instructions.
99 ///
100 /// The terminology used in this pass includes:
101 /// Islands - Clumps of constants placed in the function.
102 /// Water - Potential places where an island could be formed.
103 /// CPE - A constant pool entry that has been placed somewhere, which
104 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000105 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000106 /// BasicBlockInfo - Information about the offset and size of a single
107 /// basic block.
108 struct BasicBlockInfo {
109 /// Offset - Distance from the beginning of the function to the beginning
110 /// of this basic block.
111 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000112 /// The offset is always aligned as required by the basic block.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000113 unsigned Offset;
Bob Wilson84945262009-05-12 17:09:30 +0000114
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000115 /// Size - Size of the basic block in bytes. If the block contains
116 /// inline assembly, this is a worst case estimate.
117 ///
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000118 /// The size does not include any alignment padding whether from the
119 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000120 unsigned Size;
121
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000122 /// KnownBits - The number of low bits in Offset that are known to be
123 /// exact. The remaining bits of Offset are an upper bound.
124 uint8_t KnownBits;
125
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000126 /// Unalign - When non-zero, the block contains instructions (inline asm)
127 /// of unknown size. The real size may be smaller than Size bytes by a
128 /// multiple of 1 << Unalign.
129 uint8_t Unalign;
130
131 /// PostAlign - When non-zero, the block terminator contains a .align
132 /// directive, so the end of the block is aligned to 1 << PostAlign
133 /// bytes.
134 uint8_t PostAlign;
135
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000136 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
137 PostAlign(0) {}
Jakob Stoklund Olesen5bb32532011-12-07 01:22:52 +0000138
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +0000139 /// Compute the number of known offset bits internally to this block.
140 /// This number should be used to predict worst case padding when
141 /// splitting the block.
142 unsigned internalKnownBits() const {
143 return Unalign ? Unalign : KnownBits;
144 }
145
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000146 /// Compute the offset immediately following this block. If LogAlign is
147 /// specified, return the offset the successor block will get if it has
148 /// this alignment.
149 unsigned postOffset(unsigned LogAlign = 0) const {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000150 unsigned PO = Offset + Size;
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000151 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
152 if (!LA)
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000153 return PO;
154 // Add alignment padding from the terminator.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000155 return WorstCaseAlign(PO, LA, internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000156 }
157
158 /// Compute the number of known low bits of postOffset. If this block
159 /// contains inline asm, the number of known bits drops to the
160 /// instruction alignment. An aligned terminator may increase the number
161 /// of know bits.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +0000162 /// If LogAlign is given, also consider the alignment of the next block.
163 unsigned postKnownBits(unsigned LogAlign = 0) const {
164 return std::max(std::max(unsigned(PostAlign), LogAlign),
165 internalKnownBits());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000166 }
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000167 };
168
169 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000170
Evan Chenga8e29892007-01-19 07:51:42 +0000171 /// WaterList - A sorted list of basic blocks where islands could be placed
172 /// (i.e. blocks that don't fall through to the following block, due
173 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +0000174 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +0000175
Bob Wilsonb9239532009-10-15 20:49:47 +0000176 /// NewWaterList - The subset of WaterList that was created since the
177 /// previous iteration by inserting unconditional branches.
178 SmallSet<MachineBasicBlock*, 4> NewWaterList;
179
Bob Wilson034de5f2009-10-12 18:52:13 +0000180 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
181
Evan Chenga8e29892007-01-19 07:51:42 +0000182 /// CPUser - One user of a constant pool, keeping the machine instruction
183 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +0000184 /// allowed from the instruction to the CP. The HighWaterMark records the
185 /// highest basic block where a new CPEntry can be placed. To ensure this
186 /// pass terminates, the CP entries are initially placed at the end of the
187 /// function and then move monotonically to lower addresses. The
188 /// exception to this rule is when the current CP entry for a particular
189 /// CPUser is out of range, but there is another CP entry for the same
190 /// constant value in range. We want to use the existing in-range CP
191 /// entry, but if it later moves out of range, the search for new water
192 /// should resume where it left off. The HighWaterMark is used to record
193 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000194 struct CPUser {
195 MachineInstr *MI;
196 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000197 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000198 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000199 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000200 bool IsSoImm;
201 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
202 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000203 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
204 HighWaterMark = CPEMI->getParent();
205 }
Evan Chenga8e29892007-01-19 07:51:42 +0000206 };
Bob Wilson84945262009-05-12 17:09:30 +0000207
Evan Chenga8e29892007-01-19 07:51:42 +0000208 /// CPUsers - Keep track of all of the machine instructions that use various
209 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000210 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000211
Evan Chengc99ef082007-02-09 20:54:44 +0000212 /// CPEntry - One per constant pool entry, keeping the machine instruction
213 /// pointer, the constpool index, and the number of CPUser's which
214 /// reference this entry.
215 struct CPEntry {
216 MachineInstr *CPEMI;
217 unsigned CPI;
218 unsigned RefCount;
219 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
220 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
221 };
222
223 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000224 /// instructions. For each original constpool index (i.e. those that
225 /// existed upon entry to this pass), it keeps a vector of entries.
226 /// Original elements are cloned as we go along; the clones are
227 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000228 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000229
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000230 /// ImmBranch - One per immediate branch, keeping the machine instruction
231 /// pointer, conditional or unconditional, the max displacement,
232 /// and (if isCond is true) the corresponding unconditional branch
233 /// opcode.
234 struct ImmBranch {
235 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000236 unsigned MaxDisp : 31;
237 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000238 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000239 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
240 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000241 };
242
Evan Cheng2706f972007-05-16 05:14:06 +0000243 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000244 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000245 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000246
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000247 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
248 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000249 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000250
Evan Cheng5657c012009-07-29 02:18:14 +0000251 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
252 SmallVector<MachineInstr*, 4> T2JumpTables;
253
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000254 /// HasFarJump - True if any far jump instruction has been emitted during
255 /// the branch fix up pass.
256 bool HasFarJump;
257
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000258 MachineFunction *MF;
259 MachineConstantPool *MCP;
Chris Lattner20628752010-07-22 21:27:00 +0000260 const ARMInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000261 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000262 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000263 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000264 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000265 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000266 public:
Devang Patel19974732007-05-03 01:11:54 +0000267 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000268 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000269
Evan Cheng5657c012009-07-29 02:18:14 +0000270 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000271
272 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000273 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000274 }
Bob Wilson84945262009-05-12 17:09:30 +0000275
Evan Chenga8e29892007-01-19 07:51:42 +0000276 private:
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000277 void DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000278 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000279 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000280 void JumpTableFunctionScan();
281 void InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000282 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000283 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +0000284 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
Evan Chenged884f32007-04-03 23:39:48 +0000285 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000286 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000287 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000288 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000289 MachineBasicBlock *&NewMBB);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000290 bool HandleConstantPoolUser(unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000291 void RemoveDeadCPEMI(MachineInstr *CPEMI);
292 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000293 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000294 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
295 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000296 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000297 CPUser &U, unsigned &Growth);
Evan Chengc0dbec72007-01-31 19:57:44 +0000298 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000299 bool FixUpImmediateBr(ImmBranch &Br);
300 bool FixUpConditionalBr(ImmBranch &Br);
301 bool FixUpUnconditionalBr(ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000302 bool UndoLRSpillRestore();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000303 bool OptimizeThumb2Instructions();
304 bool OptimizeThumb2Branches();
305 bool ReorderThumb2JumpTables();
306 bool OptimizeThumb2JumpTables();
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000307 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
308 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000309
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000310 void ComputeBlockSize(MachineBasicBlock *MBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000311 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000312 void dumpBBs();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000313 void verify();
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000314
315 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
316 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
317 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
318 const CPUser &U) {
319 return OffsetIsInRange(UserOffset, TrialOffset,
320 U.MaxDisp, U.NegOk, U.IsSoImm);
321 }
Evan Chenga8e29892007-01-19 07:51:42 +0000322 };
Devang Patel19974732007-05-03 01:11:54 +0000323 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000324}
325
Dale Johannesen8593e412007-04-29 19:19:30 +0000326/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000327void ARMConstantIslands::verify() {
Evan Chengd3d9d662009-07-23 18:27:47 +0000328#ifndef NDEBUG
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000329 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000330 MBBI != E; ++MBBI) {
331 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen99486be2011-12-08 01:10:05 +0000332 unsigned Align = MBB->getAlignment();
333 unsigned MBBId = MBB->getNumber();
334 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
335 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000336 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000337 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
338 CPUser &U = CPUsers[i];
339 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000340 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
341 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
342 UserOffset - CPEOffset;
343 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000344 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000345#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000346}
347
348/// print block size and offset information - debugging
349void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000350 DEBUG({
351 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
352 const BasicBlockInfo &BBI = BBInfo[J];
353 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
354 << " kb=" << unsigned(BBI.KnownBits)
355 << " ua=" << unsigned(BBI.Unalign)
356 << " pa=" << unsigned(BBI.PostAlign)
357 << format(" size=%#x\n", BBInfo[J].Size);
358 }
359 });
Dale Johannesen8593e412007-04-29 19:19:30 +0000360}
361
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000362/// createARMConstantIslandPass - returns an instance of the constpool
363/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000364FunctionPass *llvm::createARMConstantIslandPass() {
365 return new ARMConstantIslands();
366}
367
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000368bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
369 MF = &mf;
370 MCP = mf.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000371
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000372 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000373 << MCP->getConstants().size() << " CP entries, aligned to "
374 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +0000375
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000376 TII = (const ARMInstrInfo*)MF->getTarget().getInstrInfo();
377 AFI = MF->getInfo<ARMFunctionInfo>();
378 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000379
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000380 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000381 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000382 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000383
384 HasFarJump = false;
385
Evan Chenga8e29892007-01-19 07:51:42 +0000386 // Renumber all of the machine basic blocks in the function, guaranteeing that
387 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000388 MF->RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000389
Jim Grosbach80697d12009-11-12 17:25:07 +0000390 // Try to reorder and otherwise adjust the block layout to make good use
391 // of the TB[BH] instructions.
392 bool MadeChange = false;
393 if (isThumb2 && AdjustJumpTableBlocks) {
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000394 JumpTableFunctionScan();
395 MadeChange |= ReorderThumb2JumpTables();
Jim Grosbach80697d12009-11-12 17:25:07 +0000396 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000397 T2JumpTables.clear();
398 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000399 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +0000400 }
401
Evan Chengd26b14c2009-07-31 18:28:05 +0000402 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000403 // This is so we can keep exact track of where the alignment padding goes.
404
Chris Lattner7d7dab02010-01-27 23:37:36 +0000405 // ARM and Thumb2 functions need to be 4-byte aligned.
406 if (!isThumb1)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000407 MF->EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000408
Evan Chenga8e29892007-01-19 07:51:42 +0000409 // Perform the initial placement of the constant pool entries. To start with,
410 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000411 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000412 if (!MCP->isEmpty())
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000413 DoInitialPlacement(CPEMIs);
Bob Wilson84945262009-05-12 17:09:30 +0000414
Evan Chenga8e29892007-01-19 07:51:42 +0000415 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000416 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000417
Evan Chenga8e29892007-01-19 07:51:42 +0000418 // Do the initial scan of the function, building up information about the
419 // sizes of each block, the location of all the water, and finding all of the
420 // constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000421 InitialFunctionScan(CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000422 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000423 DEBUG(dumpBBs());
424
Bob Wilson84945262009-05-12 17:09:30 +0000425
Evan Chenged884f32007-04-03 23:39:48 +0000426 /// Remove dead constant pool entries.
Bill Wendlingcd080242010-12-18 01:53:06 +0000427 MadeChange |= RemoveUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000428
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000429 // Iteratively place constant pool entries and fix up branches until there
430 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000431 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000432 while (true) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000433 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000434 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000435 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000436 CPChange |= HandleConstantPoolUser(i);
Evan Chengb6879b22009-08-07 07:35:21 +0000437 if (CPChange && ++NoCPIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000438 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000439 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000440
Bob Wilsonb9239532009-10-15 20:49:47 +0000441 // Clear NewWaterList now. If we split a block for branches, it should
442 // appear as "new water" for the next iteration of constant pool placement.
443 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000444
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000445 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Chengb6879b22009-08-07 07:35:21 +0000446 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000447 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000448 BRChange |= FixUpImmediateBr(ImmBranches[i]);
Evan Chengb6879b22009-08-07 07:35:21 +0000449 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen169db152012-01-09 22:16:24 +0000450 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000451 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000452
453 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000454 break;
455 MadeChange = true;
456 }
Evan Chenged884f32007-04-03 23:39:48 +0000457
Evan Chenga1efbbd2009-08-14 00:32:16 +0000458 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000459 if (isThumb2 && !STI->prefers32BitThumb())
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000460 MadeChange |= OptimizeThumb2Instructions();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000461
Dale Johannesen8593e412007-04-29 19:19:30 +0000462 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000463 verify();
Dale Johannesen8593e412007-04-29 19:19:30 +0000464
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000465 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
466 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000467 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000468 MadeChange |= UndoLRSpillRestore();
469
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000470 // Save the mapping between original and cloned constpool entries.
471 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
472 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
473 const CPEntry & CPE = CPEntries[i][j];
474 AFI->recordCPEClone(i, CPE.CPI);
475 }
476 }
477
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +0000478 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Chengb1c857b2010-07-22 02:09:47 +0000479
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000480 BBInfo.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000481 WaterList.clear();
482 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000483 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000484 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000485 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000486 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000487
488 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000489}
490
491/// DoInitialPlacement - Perform the initial placement of the constant pool
492/// entries. To start with, we put them all at the end of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000493void
494ARMConstantIslands::DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000495 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000496 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
497 MF->push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000498
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000499 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000500 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000501
502 // Mark the basic block as required by the const-pool.
503 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
504 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
505
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000506 // The function needs to be as aligned as the basic blocks. The linker may
507 // move functions around based on their alignment.
508 MF->EnsureAlignment(BB->getAlignment());
509
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000510 // Order the entries in BB by descending alignment. That ensures correct
511 // alignment of all entries as long as BB is sufficiently aligned. Keep
512 // track of the insertion point for each alignment. We are going to bucket
513 // sort the entries as they are created.
514 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +0000515
Evan Chenga8e29892007-01-19 07:51:42 +0000516 // Add all of the constants from the constant pool to the end block, use an
517 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesen5e46dcb2011-12-14 18:49:13 +0000518 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000519
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000520 const TargetData &TD = *MF->getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000521 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000522 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000523 assert(Size >= 4 && "Too small constant pool entry");
524 unsigned Align = CPs[i].getAlignment();
525 assert(isPowerOf2_32(Align) && "Invalid alignment");
526 // Verify that all constant pool entries are a multiple of their alignment.
527 // If not, we would have to pad them out so that instructions stay aligned.
528 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
529
530 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
531 unsigned LogAlign = Log2_32(Align);
532 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Chenga8e29892007-01-19 07:51:42 +0000533 MachineInstr *CPEMI =
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000534 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000535 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000536 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000537
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000538 // Ensure that future entries with higher alignment get inserted before
539 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesenb076fb72011-12-16 23:00:05 +0000540 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000541 if (InsPoint[a] == InsAt)
542 InsPoint[a] = CPEMI;
543
Evan Chengc99ef082007-02-09 20:54:44 +0000544 // Add a new CPEntry, but no corresponding CPUser yet.
545 std::vector<CPEntry> CPEs;
546 CPEs.push_back(CPEntry(CPEMI, i));
547 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000548 ++NumCPEs;
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000549 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000550 }
Jakob Stoklund Olesenb813f922011-12-12 16:49:37 +0000551 DEBUG(BB->dump());
Evan Chenga8e29892007-01-19 07:51:42 +0000552}
553
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000554/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000555/// into the block immediately after it.
556static bool BBHasFallthrough(MachineBasicBlock *MBB) {
557 // Get the next machine basic block in the function.
558 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000559 // Can't fall off end of function.
560 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000561 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000562
Chris Lattner7896c9f2009-12-03 00:50:42 +0000563 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000564 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
565 E = MBB->succ_end(); I != E; ++I)
566 if (*I == NextBB)
567 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000568
Evan Chenga8e29892007-01-19 07:51:42 +0000569 return false;
570}
571
Evan Chengc99ef082007-02-09 20:54:44 +0000572/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
573/// look up the corresponding CPEntry.
574ARMConstantIslands::CPEntry
575*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
576 const MachineInstr *CPEMI) {
577 std::vector<CPEntry> &CPEs = CPEntries[CPI];
578 // Number of entries per constpool index should be small, just do a
579 // linear search.
580 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
581 if (CPEs[i].CPEMI == CPEMI)
582 return &CPEs[i];
583 }
584 return NULL;
585}
586
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000587/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesenbd1ec172011-12-12 19:25:51 +0000588/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +0000589unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
590 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
591
592 // Everything is 4-byte aligned unless AlignConstantIslands is set.
593 if (!AlignConstantIslands)
594 return 2;
595
596 unsigned CPI = CPEMI->getOperand(1).getIndex();
597 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
598 unsigned Align = MCP->getConstants()[CPI].getAlignment();
599 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
600 return Log2_32(Align);
601}
602
Jim Grosbach80697d12009-11-12 17:25:07 +0000603/// JumpTableFunctionScan - Do a scan of the function, building up
604/// information about the sizes of each block and the locations of all
605/// the jump tables.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000606void ARMConstantIslands::JumpTableFunctionScan() {
607 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach80697d12009-11-12 17:25:07 +0000608 MBBI != E; ++MBBI) {
609 MachineBasicBlock &MBB = *MBBI;
610
Jim Grosbach80697d12009-11-12 17:25:07 +0000611 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000612 I != E; ++I)
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000613 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach08cbda52009-11-16 18:58:52 +0000614 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000615 }
616}
617
Evan Chenga8e29892007-01-19 07:51:42 +0000618/// InitialFunctionScan - Do the initial scan of the function, building up
619/// information about the sizes of each block, the location of all the water,
620/// and finding all of the constant pool users.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000621void ARMConstantIslands::
622InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000623 BBInfo.clear();
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000624 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000625
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000626 // First thing, compute the size of all basic blocks, and see if the function
627 // has any inline assembly in it. If so, we have to be conservative about
628 // alignment assumptions, as we don't know for sure the size of any
629 // instructions in the inline assembly.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000630 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000631 ComputeBlockSize(I);
632
633 // The known bits of the entry block offset are determined by the function
634 // alignment.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000635 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000636
637 // Compute block offsets and known bits.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000638 AdjustBBOffsetsAfter(MF->begin());
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000639
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000640 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000641 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Chenga8e29892007-01-19 07:51:42 +0000642 MBBI != E; ++MBBI) {
643 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000644
Evan Chenga8e29892007-01-19 07:51:42 +0000645 // If this block doesn't fall through into the next MBB, then this is
646 // 'water' that a constant pool island could be placed.
647 if (!BBHasFallthrough(&MBB))
648 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000649
Evan Chenga8e29892007-01-19 07:51:42 +0000650 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
651 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000652 if (I->isDebugValue())
653 continue;
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000654
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000655 int Opc = I->getOpcode();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000656 if (I->isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000657 bool isCond = false;
658 unsigned Bits = 0;
659 unsigned Scale = 1;
660 int UOpc = Opc;
661 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000662 default:
663 continue; // Ignore other JT branches
Evan Cheng5657c012009-07-29 02:18:14 +0000664 case ARM::t2BR_JT:
665 T2JumpTables.push_back(I);
666 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000667 case ARM::Bcc:
668 isCond = true;
669 UOpc = ARM::B;
670 // Fallthrough
671 case ARM::B:
672 Bits = 24;
673 Scale = 4;
674 break;
675 case ARM::tBcc:
676 isCond = true;
677 UOpc = ARM::tB;
678 Bits = 8;
679 Scale = 2;
680 break;
681 case ARM::tB:
682 Bits = 11;
683 Scale = 2;
684 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000685 case ARM::t2Bcc:
686 isCond = true;
687 UOpc = ARM::t2B;
688 Bits = 20;
689 Scale = 2;
690 break;
691 case ARM::t2B:
692 Bits = 24;
693 Scale = 2;
694 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000695 }
Evan Chengb43216e2007-02-01 10:16:15 +0000696
697 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000698 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000699 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000700 }
701
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000702 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
703 PushPopMIs.push_back(I);
704
Evan Chengd3d9d662009-07-23 18:27:47 +0000705 if (Opc == ARM::CONSTPOOL_ENTRY)
706 continue;
707
Evan Chenga8e29892007-01-19 07:51:42 +0000708 // Scan the instructions for constant pool operands.
709 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000710 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000711 // We found one. The addressing mode tells us the max displacement
712 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000713
Evan Chenga8e29892007-01-19 07:51:42 +0000714 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000715 unsigned Bits = 0;
716 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000717 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000718 bool IsSoImm = false;
719
720 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000721 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000722 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000723 break;
724
725 // Taking the address of a CP entry.
726 case ARM::LEApcrel:
727 // This takes a SoImm, which is 8 bit immediate rotated. We'll
728 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000729 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000730 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000731 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000732 Scale = 4;
733 NegOk = true;
734 IsSoImm = true;
735 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000736 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000737 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000738 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000739 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000740 case ARM::tLEApcrel:
741 Bits = 8;
742 Scale = 4;
743 break;
744
Jim Grosbach3e556122010-10-26 22:37:02 +0000745 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000746 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000747 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000748 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000749 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000750 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000751
752 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000753 Bits = 8;
754 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000755 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000756
Jim Grosbache5165492009-11-09 00:11:35 +0000757 case ARM::VLDRD:
758 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000759 Bits = 8;
760 Scale = 4; // +-(offset_8*4)
761 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000762 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000763 }
Evan Chengb43216e2007-02-01 10:16:15 +0000764
Evan Chenga8e29892007-01-19 07:51:42 +0000765 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000766 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000767 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000768 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000769 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000770
771 // Increment corresponding CPEntry reference count.
772 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
773 assert(CPE && "Cannot find a corresponding CPEntry!");
774 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000775
Evan Chenga8e29892007-01-19 07:51:42 +0000776 // Instructions can only use one CP entry, don't bother scanning the
777 // rest of the operands.
778 break;
779 }
780 }
Evan Chenga8e29892007-01-19 07:51:42 +0000781 }
782}
783
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000784/// ComputeBlockSize - Compute the size and some alignment information for MBB.
785/// This function updates BBInfo directly.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000786void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000787 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
788 BBI.Size = 0;
789 BBI.Unalign = 0;
790 BBI.PostAlign = 0;
791
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000792 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
793 ++I) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000794 BBI.Size += TII->GetInstSizeInBytes(I);
795 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
796 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +0000797 if (I->isInlineAsm())
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000798 BBI.Unalign = isThumb ? 1 : 2;
799 }
800
801 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000802 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000803 BBI.PostAlign = 2;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000804 MBB->getParent()->EnsureAlignment(2);
805 }
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000806}
807
Evan Chenga8e29892007-01-19 07:51:42 +0000808/// GetOffsetOf - Return the current offset of the specified machine instruction
809/// from the start of the function. This offset changes as stuff is moved
810/// around inside the function.
811unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
812 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000813
Evan Chenga8e29892007-01-19 07:51:42 +0000814 // The offset is composed of two things: the sum of the sizes of all MBB's
815 // before this instruction's block, and the offset from the start of the block
816 // it is in.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000817 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Chenga8e29892007-01-19 07:51:42 +0000818
819 // Sum instructions before MI in MBB.
820 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
821 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
822 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000823 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000824 }
825}
826
827/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
828/// ID.
829static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
830 const MachineBasicBlock *RHS) {
831 return LHS->getNumber() < RHS->getNumber();
832}
833
834/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
835/// machine function, it upsets all of the block numbers. Renumber the blocks
836/// and update the arrays that parallel this numbering.
837void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000838 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000839 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000840
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000841 // Insert an entry into BBInfo to align it properly with the (newly
Evan Chenga8e29892007-01-19 07:51:42 +0000842 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000843 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson84945262009-05-12 17:09:30 +0000844
845 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000846 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000847 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000848 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
849 CompareMBBNumbers);
850 WaterList.insert(IP, NewBB);
851}
852
853
854/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000855/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000856/// account for this change and returns the newly created block.
857MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000858 MachineBasicBlock *OrigBB = MI->getParent();
859
860 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000861 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000862 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000863 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000864 MF->insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000865
Evan Chenga8e29892007-01-19 07:51:42 +0000866 // Splice the instructions starting with MI over to NewBB.
867 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000868
Evan Chenga8e29892007-01-19 07:51:42 +0000869 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000870 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000871 // There doesn't seem to be meaningful DebugInfo available; this doesn't
872 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000873 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson51f6a7a2011-09-09 21:48:23 +0000874 if (!isThumb)
875 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
876 else
877 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
878 .addImm(ARMCC::AL).addReg(0);
Dan Gohmanfe601042010-06-22 15:08:57 +0000879 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000880
Evan Chenga8e29892007-01-19 07:51:42 +0000881 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesene80fba02011-12-06 00:51:12 +0000882 NewBB->transferSuccessors(OrigBB);
Bob Wilson84945262009-05-12 17:09:30 +0000883
Evan Chenga8e29892007-01-19 07:51:42 +0000884 // OrigBB branches to NewBB.
885 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000886
Evan Chenga8e29892007-01-19 07:51:42 +0000887 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000888 // This is almost the same as UpdateForInsertedWaterBlock, except that
889 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +0000890 MF->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000891
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000892 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000893 // renumbered) block numbers.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +0000894 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen99c49a42007-02-25 00:47:03 +0000895
Bob Wilson84945262009-05-12 17:09:30 +0000896 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000897 // available water after it (but not if it's already there, which happens
898 // when splitting before a conditional branch that is followed by an
899 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000900 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000901 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
902 CompareMBBNumbers);
903 MachineBasicBlock* WaterBB = *IP;
904 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000905 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000906 else
907 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000908 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000909
Dale Johannesen8086d582010-07-23 22:50:23 +0000910 // Figure out how large the OrigBB is. As the first half of the original
911 // block, it cannot contain a tablejump. The size includes
912 // the new jump we added. (It should be possible to do this without
913 // recounting everything, but it's very confusing, and this is rarely
914 // executed.)
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000915 ComputeBlockSize(OrigBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000916
Dale Johannesen8086d582010-07-23 22:50:23 +0000917 // Figure out how large the NewMBB is. As the second half of the original
918 // block, it may contain a tablejump.
Jakob Stoklund Olesena26811e2011-12-07 04:17:35 +0000919 ComputeBlockSize(NewBB);
Dale Johannesen8086d582010-07-23 22:50:23 +0000920
Dale Johannesen99c49a42007-02-25 00:47:03 +0000921 // All BBOffsets following these blocks must be modified.
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +0000922 AdjustBBOffsetsAfter(OrigBB);
Evan Cheng0c615842007-01-31 02:22:22 +0000923
924 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000925}
926
Dale Johannesen8593e412007-04-29 19:19:30 +0000927/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000928/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000929/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000930bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000931 unsigned TrialOffset, unsigned MaxDisp,
932 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000933 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
934 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000935 // Effectively, the valid range of displacements is 2 bytes smaller for such
936 // references.
Jakob Stoklund Olesenf9aabb82011-12-16 19:10:00 +0000937 if (isThumb && UserOffset%4 !=0)
Dale Johannesen8593e412007-04-29 19:19:30 +0000938 UserOffset -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000939
Dale Johannesen99c49a42007-02-25 00:47:03 +0000940 if (UserOffset <= TrialOffset) {
941 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000942 if (TrialOffset - UserOffset <= MaxDisp)
943 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000944 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000945 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000946 if (UserOffset - TrialOffset <= MaxDisp)
947 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000948 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000949 }
950 return false;
951}
952
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000953/// WaterIsInRange - Returns true if a CPE placed after the specified
954/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000955///
956/// Compute how much the function will grow by inserting a CPE after Water.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000957bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000958 MachineBasicBlock* Water, CPUser &U,
959 unsigned &Growth) {
960 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
961 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
962 unsigned NextBlockOffset, NextBlockAlignment;
963 MachineFunction::const_iterator NextBlock = Water;
964 if (++NextBlock == MF->end()) {
965 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
966 NextBlockAlignment = 0;
967 } else {
968 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
969 NextBlockAlignment = NextBlock->getAlignment();
970 }
971 unsigned Size = U.CPEMI->getOperand(2).getImm();
972 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000973
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +0000974 // The CPE may be able to hide in the alignment padding before the next
975 // block. It may also cause more padding to be required if it is more aligned
976 // that the next block.
977 if (CPEEnd > NextBlockOffset) {
978 Growth = CPEEnd - NextBlockOffset;
979 // Compute the padding that would go at the end of the CPE to align the next
980 // block.
981 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
982
983 // If the CPE is to be inserted before the instruction, that will raise
984 // the offset of the instruction. Also account for unknown alignment padding
985 // in blocks between CPE and the user.
986 if (CPEOffset < UserOffset)
987 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
988 } else
989 // CPE fits in existing padding.
990 Growth = 0;
Dale Johannesend959aa42007-04-02 20:31:06 +0000991
Jakob Stoklund Olesen493ad6b2011-12-09 19:44:39 +0000992 return OffsetIsInRange(UserOffset, CPEOffset, U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000993}
994
995/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000996/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000997bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000998 MachineInstr *CPEMI, unsigned MaxDisp,
999 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001000 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jakob Stoklund Olesene6f9e9d2011-12-08 01:22:39 +00001001 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +00001002
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001003 if (DoDump) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001004 DEBUG({
1005 unsigned Block = MI->getParent()->getNumber();
1006 const BasicBlockInfo &BBI = BBInfo[Block];
1007 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1008 << " max delta=" << MaxDisp
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001009 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001010 << " in BB#" << Block << ": "
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001011 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1012 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1013 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001014 });
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001015 }
Evan Chengc0dbec72007-01-31 19:57:44 +00001016
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001017 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +00001018}
1019
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001020#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001021/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1022/// unconditionally branches to its only successor.
1023static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1024 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1025 return false;
1026
1027 MachineBasicBlock *Succ = *MBB->succ_begin();
1028 MachineBasicBlock *Pred = *MBB->pred_begin();
1029 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001030 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1031 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +00001032 return PredMI->getOperand(0).getMBB() == Succ;
1033 return false;
1034}
Evan Chengd1e7d9a2009-01-28 00:53:34 +00001035#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +00001036
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001037void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001038 unsigned BBNum = BB->getNumber();
1039 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001040 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen85528212011-12-12 19:25:54 +00001041 // Include the alignment of the current block.
1042 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1043 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1044 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001045
Jakob Stoklund Olesen59ecaae2012-01-06 21:40:15 +00001046 // This is where block i begins. Stop if the offset is already correct,
1047 // and we have updated 2 blocks. This is the maximum number of blocks
1048 // changed before calling this function.
1049 if (i > BBNum + 2 &&
1050 BBInfo[i].Offset == Offset &&
1051 BBInfo[i].KnownBits == KnownBits)
1052 break;
1053
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001054 BBInfo[i].Offset = Offset;
1055 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen8593e412007-04-29 19:19:30 +00001056 }
Dale Johannesen99c49a42007-02-25 00:47:03 +00001057}
1058
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001059/// DecrementOldEntry - find the constant pool entry with index CPI
1060/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +00001061/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001062/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +00001063
Evan Chenged884f32007-04-03 23:39:48 +00001064bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +00001065 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +00001066 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1067 assert(CPE && "Unexpected!");
1068 if (--CPE->RefCount == 0) {
1069 RemoveDeadCPEMI(CPEMI);
1070 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +00001071 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001072 return true;
1073 }
1074 return false;
1075}
1076
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001077/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1078/// if not, see if an in-range clone of the CPE is in range, and if so,
1079/// change the data structures so the user references the clone. Returns:
1080/// 0 = no existing entry found
1081/// 1 = entry found, and there were no code insertions or deletions
1082/// 2 = entry found, and there were code insertions or deletions
1083int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1084{
1085 MachineInstr *UserMI = U.MI;
1086 MachineInstr *CPEMI = U.CPEMI;
1087
1088 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001089 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001090 DEBUG(dbgs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001091 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001092 }
1093
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001094 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001095 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001096 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1097 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1098 // We already tried this one
1099 if (CPEs[i].CPEMI == CPEMI)
1100 continue;
1101 // Removing CPEs can leave empty entries, skip
1102 if (CPEs[i].CPEMI == NULL)
1103 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001104 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001105 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattner893e1c92009-08-23 06:49:22 +00001106 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001107 // Point the CPUser node to the replacement
1108 U.CPEMI = CPEs[i].CPEMI;
1109 // Change the CPI in the instruction operand to refer to the clone.
1110 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001111 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001112 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001113 break;
1114 }
1115 // Adjust the refcount of the clone...
1116 CPEs[i].RefCount++;
1117 // ...and the original. If we didn't remove the old entry, none of the
1118 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001119 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001120 }
1121 }
1122 return 0;
1123}
1124
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001125/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1126/// the specific unconditional branch instruction.
1127static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001128 switch (Opc) {
1129 case ARM::tB:
1130 return ((1<<10)-1)*2;
1131 case ARM::t2B:
1132 return ((1<<23)-1)*2;
1133 default:
1134 break;
1135 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001136
David Goodwin5e47a9a2009-06-30 18:04:13 +00001137 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001138}
1139
Bob Wilsonb9239532009-10-15 20:49:47 +00001140/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001141/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001142/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001143/// is set to the WaterList entry. For Thumb, prefer water that will not
1144/// introduce padding to water that will. To ensure that this pass
1145/// terminates, the CPE location for a particular CPUser is only allowed to
1146/// move to a lower address, so search backward from the end of the list and
1147/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001148bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001149 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001150 if (WaterList.empty())
1151 return false;
1152
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001153 unsigned BestGrowth = ~0u;
1154 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1155 --IP) {
Bob Wilson3b757352009-10-12 19:04:03 +00001156 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001157 // Check if water is in range and is either at a lower address than the
1158 // current "high water mark" or a new water block that was created since
1159 // the previous iteration by inserting an unconditional branch. In the
1160 // latter case, we want to allow resetting the high water mark back to
1161 // this new water since we haven't seen it before. Inserting branches
1162 // should be relatively uncommon and when it does happen, we want to be
1163 // sure to take advantage of it for all the CPEs near that block, so that
1164 // we don't insert more branches than necessary.
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001165 unsigned Growth;
1166 if (WaterIsInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilsonb9239532009-10-15 20:49:47 +00001167 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001168 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1169 // This is the least amount of required padding seen so far.
1170 BestGrowth = Growth;
1171 WaterIter = IP;
1172 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1173 << " Growth=" << Growth << '\n');
1174
1175 // Keep looking unless it is perfect.
1176 if (BestGrowth == 0)
Bob Wilson3b757352009-10-12 19:04:03 +00001177 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001178 }
Bob Wilson3b757352009-10-12 19:04:03 +00001179 if (IP == B)
1180 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001181 }
Jakob Stoklund Olesen2e290242011-12-13 00:44:30 +00001182 return BestGrowth != ~0u;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001183}
1184
Bob Wilson84945262009-05-12 17:09:30 +00001185/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001186/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1187/// block is used if in range, and the conditional branch munged so control
1188/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001189/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001190/// block following which the new island can be inserted (the WaterList
1191/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001192void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001193 unsigned UserOffset,
1194 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001195 CPUser &U = CPUsers[CPUserIndex];
1196 MachineInstr *UserMI = U.MI;
1197 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001198 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001199 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen77caaf02011-12-10 02:55:10 +00001200 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001201
Bob Wilson36fa5322009-10-15 05:10:36 +00001202 // If the block does not end in an unconditional branch already, and if the
1203 // end of the block is within range, make new water there. (The addition
1204 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1205 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001206 // inside OffsetIsInRange.
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001207 if (BBHasFallthrough(UserMBB)) {
1208 // Size of branch to insert.
1209 unsigned Delta = isThumb1 ? 2 : 4;
1210 // End of UserBlock after adding a branch.
1211 unsigned UserBlockEnd = UserBBI.postOffset() + Delta;
1212 // Compute the offset where the CPE will begin.
1213 unsigned CPEOffset = WorstCaseAlign(UserBlockEnd, CPELogAlign,
1214 UserBBI.postKnownBits());
Dale Johannesen8593e412007-04-29 19:19:30 +00001215
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001216 if (OffsetIsInRange(UserOffset, CPEOffset, U)) {
1217 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1218 << format(", expected CPE offset %#x\n", CPEOffset));
1219 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1220 // Add an unconditional branch from UserMBB to fallthrough block. Record
1221 // it for branch lengthening; this new branch will not get out of range,
1222 // but if the preceding conditional branch is out of range, the targets
1223 // will be exchanged, and the altered branch may be out of range, so the
1224 // machinery has to know about it.
1225 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1226 if (!isThumb)
1227 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1228 else
1229 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1230 .addImm(ARMCC::AL).addReg(0);
1231 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1232 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1233 MaxDisp, false, UncondBr));
1234 BBInfo[UserMBB->getNumber()].Size += Delta;
1235 AdjustBBOffsetsAfter(UserMBB);
1236 return;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001237 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001238 }
Jakob Stoklund Olesen299b0592011-12-14 23:48:54 +00001239
1240 // What a big block. Find a place within the block to split it. This is a
1241 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1242 // entries are 4 bytes: if instruction I references island CPE, and
1243 // instruction I+1 references CPE', it will not work well to put CPE as far
1244 // forward as possible, since then CPE' cannot immediately follow it (that
1245 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1246 // need to create a new island. So, we make a first guess, then walk through
1247 // the instructions between the one currently being looked at and the
1248 // possible insertion point, and make sure any other instructions that
1249 // reference CPEs will be able to use the same island area; if not, we back
1250 // up the insertion point.
1251
1252 // Try to split the block so it's fully aligned. Compute the latest split
1253 // point where we can add a 4-byte branch instruction, and then
1254 // WorstCaseAlign to LogAlign.
1255 unsigned LogAlign = MF->getAlignment();
1256 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1257 unsigned KnownBits = UserBBI.internalKnownBits();
1258 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1259 unsigned BaseInsertOffset = UserOffset + U.MaxDisp;
1260 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1261 BaseInsertOffset));
1262
1263 // Account for alignment and unknown padding.
1264 BaseInsertOffset &= ~((1u << LogAlign) - 1);
1265 BaseInsertOffset -= UPad;
1266
1267 // The 4 in the following is for the unconditional branch we'll be inserting
1268 // (allows for long branch on Thumb1). Alignment of the island is handled
1269 // inside OffsetIsInRange.
1270 BaseInsertOffset -= 4;
1271
1272 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1273 << " la=" << LogAlign
1274 << " kb=" << KnownBits
1275 << " up=" << UPad << '\n');
1276
1277 // This could point off the end of the block if we've already got constant
1278 // pool entries following this block; only the last one is in the water list.
1279 // Back past any possible branches (allow for a conditional and a maximally
1280 // long unconditional).
1281 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1282 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1283 (isThumb1 ? 6 : 8);
1284 unsigned EndInsertOffset =
1285 WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1286 CPEMI->getOperand(2).getImm();
1287 MachineBasicBlock::iterator MI = UserMI;
1288 ++MI;
1289 unsigned CPUIndex = CPUserIndex+1;
1290 unsigned NumCPUsers = CPUsers.size();
1291 MachineInstr *LastIT = 0;
1292 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1293 Offset < BaseInsertOffset;
1294 Offset += TII->GetInstSizeInBytes(MI),
1295 MI = llvm::next(MI)) {
1296 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1297 CPUser &U = CPUsers[CPUIndex];
1298 if (!OffsetIsInRange(Offset, EndInsertOffset, U)) {
1299 // Shift intertion point by one unit of alignment so it is within reach.
1300 BaseInsertOffset -= 1u << LogAlign;
1301 EndInsertOffset -= 1u << LogAlign;
1302 }
1303 // This is overly conservative, as we don't account for CPEMIs being
1304 // reused within the block, but it doesn't matter much. Also assume CPEs
1305 // are added in order with alignment padding. We may eventually be able
1306 // to pack the aligned CPEs better.
1307 EndInsertOffset = RoundUpToAlignment(EndInsertOffset,
1308 1u << getCPELogAlign(U.CPEMI)) +
1309 U.CPEMI->getOperand(2).getImm();
1310 CPUIndex++;
1311 }
1312
1313 // Remember the last IT instruction.
1314 if (MI->getOpcode() == ARM::t2IT)
1315 LastIT = MI;
1316 }
1317
1318 --MI;
1319
1320 // Avoid splitting an IT block.
1321 if (LastIT) {
1322 unsigned PredReg = 0;
1323 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1324 if (CC != ARMCC::AL)
1325 MI = LastIT;
1326 }
1327 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001328}
1329
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001330/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001331/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001332/// place in-range. Return true if we changed any addresses (thus must run
1333/// another pass of branch lengthening), false otherwise.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001334bool ARMConstantIslands::HandleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001335 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001336 MachineInstr *UserMI = U.MI;
1337 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001338 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001339 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001340 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001341 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001342 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001343
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001344 // See if the current entry is within range, or there is a clone of it
1345 // in range.
1346 int result = LookForExistingCPEntry(U, UserOffset);
1347 if (result==1) return false;
1348 else if (result==2) return true;
1349
1350 // No existing clone of this CPE is within range.
1351 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001352 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001353
Bob Wilsonf98032e2009-10-12 21:23:15 +00001354 // Look for water where we can place this CPE.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001355 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilsonb9239532009-10-15 20:49:47 +00001356 MachineBasicBlock *NewMBB;
1357 water_iterator IP;
1358 if (LookForWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001359 DEBUG(dbgs() << "Found water in range\n");
Bob Wilsonb9239532009-10-15 20:49:47 +00001360 MachineBasicBlock *WaterBB = *IP;
1361
1362 // If the original WaterList entry was "new water" on this iteration,
1363 // propagate that to the new island. This is just keeping NewWaterList
1364 // updated to match the WaterList, which will be updated below.
1365 if (NewWaterList.count(WaterBB)) {
1366 NewWaterList.erase(WaterBB);
1367 NewWaterList.insert(NewIsland);
1368 }
1369 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001370 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001371
1372 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001373 // No water found.
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001374 DEBUG(dbgs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001375 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001376
1377 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1378 // called while handling branches so that the water will be seen on the
1379 // next iteration for constant pools, but in this context, we don't want
1380 // it. Check for this so it will be removed from the WaterList.
1381 // Also remove any entry from NewWaterList.
1382 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1383 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1384 if (IP != WaterList.end())
1385 NewWaterList.erase(WaterBB);
1386
1387 // We are adding new water. Update NewWaterList.
1388 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001389 }
1390
Bob Wilsonb9239532009-10-15 20:49:47 +00001391 // Remove the original WaterList entry; we want subsequent insertions in
1392 // this vicinity to go after the one we're about to insert. This
1393 // considerably reduces the number of times we have to move the same CPE
1394 // more than once and is also important to ensure the algorithm terminates.
1395 if (IP != WaterList.end())
1396 WaterList.erase(IP);
1397
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001398 // Okay, we know we can put an island before NewMBB now, do it!
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001399 MF->insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001400
1401 // Update internal data structures to account for the newly inserted MBB.
1402 UpdateForInsertedWaterBlock(NewIsland);
1403
1404 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001405 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001406
1407 // Now that we have an island to add the CPE to, clone the original CPE and
1408 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001409 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001410 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001411 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001412 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001413 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001414
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001415 // Mark the basic block as aligned as required by the const-pool entry.
1416 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen3e572ac2011-12-06 01:43:02 +00001417
Evan Chenga8e29892007-01-19 07:51:42 +00001418 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001419 BBInfo[NewIsland->getNumber()].Size += Size;
Jakob Stoklund Olesen540c6d92011-12-08 00:55:02 +00001420 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
Bob Wilson84945262009-05-12 17:09:30 +00001421
Evan Chenga8e29892007-01-19 07:51:42 +00001422 // Finally, change the CPI in the instruction operand to be ID.
1423 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001424 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001425 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001426 break;
1427 }
Bob Wilson84945262009-05-12 17:09:30 +00001428
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001429 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesen2d5023b2011-12-10 02:55:06 +00001430 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson84945262009-05-12 17:09:30 +00001431
Evan Chenga8e29892007-01-19 07:51:42 +00001432 return true;
1433}
1434
Evan Chenged884f32007-04-03 23:39:48 +00001435/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1436/// sizes and offsets of impacted basic blocks.
1437void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1438 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001439 unsigned Size = CPEMI->getOperand(2).getImm();
1440 CPEMI->eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001441 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen8593e412007-04-29 19:19:30 +00001442 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001443 if (CPEBB->empty()) {
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001444 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen305e5fe2011-12-06 21:55:35 +00001445
1446 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1447 CPEBB->setAlignment(0);
Jakob Stoklund Olesencca33a32011-12-12 18:45:45 +00001448 } else
1449 // Entries are sorted by descending alignment, so realign from the front.
1450 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1451
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001452 AdjustBBOffsetsAfter(CPEBB);
Dale Johannesen8593e412007-04-29 19:19:30 +00001453 // An island has only one predecessor BB and one successor BB. Check if
1454 // this BB's predecessor jumps directly to this BB's successor. This
1455 // shouldn't happen currently.
1456 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1457 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001458}
1459
1460/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1461/// are zero.
1462bool ARMConstantIslands::RemoveUnusedCPEntries() {
1463 unsigned MadeChange = false;
1464 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1465 std::vector<CPEntry> &CPEs = CPEntries[i];
1466 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1467 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1468 RemoveDeadCPEMI(CPEs[j].CPEMI);
1469 CPEs[j].CPEMI = NULL;
1470 MadeChange = true;
1471 }
1472 }
Bob Wilson84945262009-05-12 17:09:30 +00001473 }
Evan Chenged884f32007-04-03 23:39:48 +00001474 return MadeChange;
1475}
1476
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001477/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001478/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001479bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1480 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001481 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001482 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001483 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng43aeab62007-01-26 20:38:26 +00001484
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001485 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattner705e07f2009-08-23 03:41:05 +00001486 << " from BB#" << MI->getParent()->getNumber()
1487 << " max delta=" << MaxDisp
1488 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1489 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001490
Dale Johannesen8593e412007-04-29 19:19:30 +00001491 if (BrOffset <= DestOffset) {
1492 // Branch before the Dest.
1493 if (DestOffset-BrOffset <= MaxDisp)
1494 return true;
1495 } else {
1496 if (BrOffset-DestOffset <= MaxDisp)
1497 return true;
1498 }
1499 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001500}
1501
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001502/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1503/// away to fit in its displacement field.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001504bool ARMConstantIslands::FixUpImmediateBr(ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001505 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001506 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001507
Evan Chengc0dbec72007-01-31 19:57:44 +00001508 // Check to see if the DestBB is already in-range.
1509 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001510 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001511
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001512 if (!Br.isCond)
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001513 return FixUpUnconditionalBr(Br);
1514 return FixUpConditionalBr(Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001515}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001516
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001517/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1518/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001519/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001520/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001521bool
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001522ARMConstantIslands::FixUpUnconditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001523 MachineInstr *MI = Br.MI;
1524 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001525 if (!isThumb1)
1526 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001527
1528 // Use BL to implement far jump.
1529 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001530 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001531 BBInfo[MBB->getNumber()].Size += 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001532 AdjustBBOffsetsAfter(MBB);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001533 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001534 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001535
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001536 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001537
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001538 return true;
1539}
1540
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001541/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001542/// far away to fit in its displacement field. It is converted to an inverse
1543/// conditional branch + an unconditional branch to the destination.
1544bool
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001545ARMConstantIslands::FixUpConditionalBr(ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001546 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001547 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001548
Bob Wilson39bf0512009-05-12 17:35:29 +00001549 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001550 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001551 // blt L1
1552 // =>
1553 // bge L2
1554 // b L1
1555 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001556 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001557 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001558 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001559
1560 // If the branch is at the end of its MBB and that has a fall-through block,
1561 // direct the updated conditional branch to the fall-through block. Otherwise,
1562 // split the MBB before the next instruction.
1563 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001564 MachineInstr *BMI = &MBB->back();
1565 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001566
Dan Gohmanfe601042010-06-22 15:08:57 +00001567 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001568 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001569 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001570 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001571 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001572 // condition and swap destinations:
1573 // beq L1
1574 // b L2
1575 // =>
1576 // bne L2
1577 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001578 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001579 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001580 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattner705e07f2009-08-23 03:41:05 +00001581 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001582 BMI->getOperand(0).setMBB(DestBB);
1583 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001584 MI->getOperand(1).setImm(CC);
1585 return true;
1586 }
1587 }
1588 }
1589
1590 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001591 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001592 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001593 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001594 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001595 BBInfo[MBB->getNumber()].Size -= delta;
Evan Chengdd353b82007-01-26 02:02:39 +00001596 MBB->back().eraseFromParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001597 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001598 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001599 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001600
Jakob Stoklund Olesen3c4615e2011-12-09 18:20:35 +00001601 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattner893e1c92009-08-23 06:49:22 +00001602 << " also invert condition and change dest. to BB#"
1603 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001604
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001605 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001606 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001607 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001608 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001609 Br.MI = &MBB->back();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001610 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Andersoncd4338f2011-09-09 23:05:14 +00001611 if (isThumb)
1612 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1613 .addImm(ARMCC::AL).addReg(0);
1614 else
1615 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001616 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001617 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001618 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001619
1620 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001621 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001622 MI->eraseFromParent();
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001623 AdjustBBOffsetsAfter(MBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001624 return true;
1625}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001626
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001627/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001628/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1629/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001630bool ARMConstantIslands::UndoLRSpillRestore() {
1631 bool MadeChange = false;
1632 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1633 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001634 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001635 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001636 MI->getOperand(2).getReg() == ARM::PC &&
1637 MI->getNumExplicitOperands() == 3) {
Jim Grosbach25e6d482011-07-08 21:50:04 +00001638 // Create the new insn and copy the predicate from the old.
1639 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1640 .addOperand(MI->getOperand(0))
1641 .addOperand(MI->getOperand(1));
Evan Cheng44bec522007-05-15 01:29:07 +00001642 MI->eraseFromParent();
1643 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001644 }
1645 }
1646 return MadeChange;
1647}
Evan Cheng5657c012009-07-29 02:18:14 +00001648
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001649bool ARMConstantIslands::OptimizeThumb2Instructions() {
Evan Chenga1efbbd2009-08-14 00:32:16 +00001650 bool MadeChange = false;
1651
1652 // Shrink ADR and LDR from constantpool.
1653 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1654 CPUser &U = CPUsers[i];
1655 unsigned Opcode = U.MI->getOpcode();
1656 unsigned NewOpc = 0;
1657 unsigned Scale = 1;
1658 unsigned Bits = 0;
1659 switch (Opcode) {
1660 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001661 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001662 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1663 NewOpc = ARM::tLEApcrel;
1664 Bits = 8;
1665 Scale = 4;
1666 }
1667 break;
1668 case ARM::t2LDRpci:
1669 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1670 NewOpc = ARM::tLDRpci;
1671 Bits = 8;
1672 Scale = 4;
1673 }
1674 break;
1675 }
1676
1677 if (!NewOpc)
1678 continue;
1679
1680 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1681 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1682 // FIXME: Check if offset is multiple of scale if scale is not 4.
1683 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1684 U.MI->setDesc(TII->get(NewOpc));
1685 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001686 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001687 AdjustBBOffsetsAfter(MBB);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001688 ++NumT2CPShrunk;
1689 MadeChange = true;
1690 }
1691 }
1692
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001693 MadeChange |= OptimizeThumb2Branches();
1694 MadeChange |= OptimizeThumb2JumpTables();
Evan Chenga1efbbd2009-08-14 00:32:16 +00001695 return MadeChange;
1696}
1697
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001698bool ARMConstantIslands::OptimizeThumb2Branches() {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001699 bool MadeChange = false;
1700
1701 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1702 ImmBranch &Br = ImmBranches[i];
1703 unsigned Opcode = Br.MI->getOpcode();
1704 unsigned NewOpc = 0;
1705 unsigned Scale = 1;
1706 unsigned Bits = 0;
1707 switch (Opcode) {
1708 default: break;
1709 case ARM::t2B:
1710 NewOpc = ARM::tB;
1711 Bits = 11;
1712 Scale = 2;
1713 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001714 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001715 NewOpc = ARM::tBcc;
1716 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001717 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001718 break;
1719 }
Evan Chengde17fb62009-10-31 23:46:45 +00001720 }
1721 if (NewOpc) {
1722 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1723 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1724 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1725 Br.MI->setDesc(TII->get(NewOpc));
1726 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001727 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001728 AdjustBBOffsetsAfter(MBB);
Evan Chengde17fb62009-10-31 23:46:45 +00001729 ++NumT2BrShrunk;
1730 MadeChange = true;
1731 }
1732 }
1733
1734 Opcode = Br.MI->getOpcode();
1735 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001736 continue;
1737
Evan Chengde17fb62009-10-31 23:46:45 +00001738 NewOpc = 0;
1739 unsigned PredReg = 0;
1740 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1741 if (Pred == ARMCC::EQ)
1742 NewOpc = ARM::tCBZ;
1743 else if (Pred == ARMCC::NE)
1744 NewOpc = ARM::tCBNZ;
1745 if (!NewOpc)
1746 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001747 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001748 // Check if the distance is within 126. Subtract starting offset by 2
1749 // because the cmp will be eliminated.
1750 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001751 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Chengde17fb62009-10-31 23:46:45 +00001752 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001753 MachineBasicBlock::iterator CmpMI = Br.MI;
1754 if (CmpMI != Br.MI->getParent()->begin()) {
1755 --CmpMI;
1756 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1757 unsigned Reg = CmpMI->getOperand(0).getReg();
1758 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1759 if (Pred == ARMCC::AL &&
1760 CmpMI->getOperand(1).getImm() == 0 &&
1761 isARMLowRegister(Reg)) {
1762 MachineBasicBlock *MBB = Br.MI->getParent();
1763 MachineInstr *NewBR =
1764 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1765 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1766 CmpMI->eraseFromParent();
1767 Br.MI->eraseFromParent();
1768 Br.MI = NewBR;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001769 BBInfo[MBB->getNumber()].Size -= 2;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001770 AdjustBBOffsetsAfter(MBB);
Evan Cheng0539c152011-04-01 22:09:28 +00001771 ++NumCBZ;
1772 MadeChange = true;
1773 }
Evan Chengde17fb62009-10-31 23:46:45 +00001774 }
1775 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001776 }
1777 }
1778
1779 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001780}
1781
Evan Chenga1efbbd2009-08-14 00:32:16 +00001782/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1783/// jumptables when it's possible.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001784bool ARMConstantIslands::OptimizeThumb2JumpTables() {
Evan Cheng5657c012009-07-29 02:18:14 +00001785 bool MadeChange = false;
1786
1787 // FIXME: After the tables are shrunk, can we get rid some of the
1788 // constantpool tables?
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001789 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001790 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001791
Evan Cheng5657c012009-07-29 02:18:14 +00001792 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1793 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1794 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001795 const MCInstrDesc &MCID = MI->getDesc();
1796 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001797 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001798 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1799 unsigned JTI = JTOP.getIndex();
1800 assert(JTI < JT.size());
1801
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001802 bool ByteOk = true;
1803 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001804 unsigned JTOffset = GetOffsetOf(MI) + 4;
1805 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001806 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1807 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001808 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng8770f742009-07-29 23:20:20 +00001809 // Negative offset is not ok. FIXME: We should change BB layout to make
1810 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001811 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001812 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001813 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001814 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001815 HalfWordOk = false;
1816 if (!ByteOk && !HalfWordOk)
1817 break;
1818 }
1819
1820 if (ByteOk || HalfWordOk) {
1821 MachineBasicBlock *MBB = MI->getParent();
1822 unsigned BaseReg = MI->getOperand(0).getReg();
1823 bool BaseRegKill = MI->getOperand(0).isKill();
1824 if (!BaseRegKill)
1825 continue;
1826 unsigned IdxReg = MI->getOperand(1).getReg();
1827 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001828
1829 // Scan backwards to find the instruction that defines the base
1830 // register. Due to post-RA scheduling, we can't count on it
1831 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001832 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001833 MachineBasicBlock::iterator B = MBB->begin();
1834 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1835 --PrevI;
1836
1837 // If for some reason we didn't find it, we can't do anything, so
1838 // just skip this one.
1839 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001840 continue;
1841
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001842 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001843 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001844 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001845 // Make sure it only defines the base register and kills any uses
1846 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001847 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1848 const MachineOperand &MO = AddrMI->getOperand(k);
1849 if (!MO.isReg() || !MO.getReg())
1850 continue;
1851 if (MO.isDef() && MO.getReg() != BaseReg) {
1852 OptOk = false;
1853 break;
1854 }
1855 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1856 OptOk = false;
1857 break;
1858 }
1859 }
1860 if (!OptOk)
1861 continue;
1862
Owen Anderson6b8719f2010-12-13 22:51:08 +00001863 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001864 // that gave us the initial base register definition.
1865 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1866 ;
1867
Owen Anderson6b8719f2010-12-13 22:51:08 +00001868 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001869 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001870 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001871 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001872 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001873 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001874 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001875
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001876 if (!OptOk)
1877 continue;
1878
Jim Grosbachd092a872010-11-29 21:28:32 +00001879 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001880 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1881 .addReg(IdxReg, getKillRegState(IdxRegKill))
1882 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1883 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1884 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1885 // is 2-byte aligned. For now, asm printer will fix it up.
1886 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1887 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1888 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1889 OrigSize += TII->GetInstSizeInBytes(MI);
1890
1891 AddrMI->eraseFromParent();
1892 LeaMI->eraseFromParent();
1893 MI->eraseFromParent();
1894
1895 int delta = OrigSize - NewSize;
Jakob Stoklund Olesena3f331b2011-12-07 01:08:25 +00001896 BBInfo[MBB->getNumber()].Size -= delta;
Jakob Stoklund Olesen2fe71c52011-12-07 05:17:30 +00001897 AdjustBBOffsetsAfter(MBB);
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001898
1899 ++NumTBs;
1900 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001901 }
1902 }
1903
1904 return MadeChange;
1905}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001906
Jim Grosbach9249efe2009-11-16 18:55:47 +00001907/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1908/// jump tables always branch forwards, since that's what tbb and tbh need.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001909bool ARMConstantIslands::ReorderThumb2JumpTables() {
Jim Grosbach80697d12009-11-12 17:25:07 +00001910 bool MadeChange = false;
1911
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001912 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001913 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001914
Jim Grosbach80697d12009-11-12 17:25:07 +00001915 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1916 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1917 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001918 const MCInstrDesc &MCID = MI->getDesc();
1919 unsigned NumOps = MCID.getNumOperands();
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001920 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001921 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1922 unsigned JTI = JTOP.getIndex();
1923 assert(JTI < JT.size());
1924
1925 // We prefer if target blocks for the jump table come after the jump
1926 // instruction so we can use TB[BH]. Loop through the target blocks
1927 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001928 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001929 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1930 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1931 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001932 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001933
Jim Grosbach08cbda52009-11-16 18:58:52 +00001934 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001935 // The destination precedes the switch. Try to move the block forward
1936 // so we have a positive offset.
1937 MachineBasicBlock *NewBB =
1938 AdjustJTTargetBlockForward(MBB, MI->getParent());
1939 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001940 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001941 MadeChange = true;
1942 }
1943 }
1944 }
1945
1946 return MadeChange;
1947}
1948
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001949MachineBasicBlock *ARMConstantIslands::
1950AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1951{
Jim Grosbach03e2d442010-07-07 22:53:35 +00001952 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001953 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001954 // table that branches back to the actual target. This is a very simple
1955 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001956 MachineBasicBlock *TBB = 0, *FBB = 0;
1957 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001958 SmallVector<MachineOperand, 4> CondPrior;
1959 MachineFunction::iterator BBi = BB;
1960 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001961
Jim Grosbachca215e72009-11-16 17:10:56 +00001962 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001963 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001964
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001965 // If the block ends in an unconditional branch, move it. The prior block
1966 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001967 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001968 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001969 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001970 BB->moveAfter(JTBB);
1971 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001972 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001973 // Update numbering to account for the block being moved.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001974 MF->RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001975 ++NumJTMoved;
1976 return NULL;
1977 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001978
1979 // Create a new MBB for the code after the jump BB.
1980 MachineBasicBlock *NewBB =
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001981 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001982 MachineFunction::iterator MBBI = JTBB; ++MBBI;
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001983 MF->insert(MBBI, NewBB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001984
1985 // Add an unconditional branch from NewBB to BB.
1986 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1987 // correspond directly to anything in the source.
1988 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson51f6a7a2011-09-09 21:48:23 +00001989 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1990 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001991
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001992 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesendbf350a2011-12-12 18:16:53 +00001993 MF->RenumberBlocks(NewBB);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001994
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001995 // Update the CFG.
1996 NewBB->addSuccessor(BB);
1997 JTBB->removeSuccessor(BB);
1998 JTBB->addSuccessor(NewBB);
1999
Jim Grosbach80697d12009-11-12 17:25:07 +00002000 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00002001 return NewBB;
2002}