blob: 309caee42b95a2cfcaf76c60cd68478870ae9f07 [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 Chengd3d9d662009-07-23 18:27:47 +000018#include "ARMAddressingModes.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000019#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000020#include "ARMInstrInfo.h"
Evan Cheng719510a2010-08-12 20:30:05 +000021#include "Thumb2InstrInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000022#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000029#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000031#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000034#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000035#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000036using namespace llvm;
37
Evan Chenga1efbbd2009-08-14 00:32:16 +000038STATISTIC(NumCPEs, "Number of constpool entries");
39STATISTIC(NumSplit, "Number of uncond branches inserted");
40STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42STATISTIC(NumTBs, "Number of table branches generated");
43STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000044STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000045STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000046STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000047STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000048
49
50static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000051AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000052 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000053
54namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000055 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000056 /// requires constant pool entries to be scattered among the instructions
57 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000058 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000059 /// special instructions.
60 ///
61 /// The terminology used in this pass includes:
62 /// Islands - Clumps of constants placed in the function.
63 /// Water - Potential places where an island could be formed.
64 /// CPE - A constant pool entry that has been placed somewhere, which
65 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000066 class ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000067 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000068 /// by MBB Number. The two-byte pads required for Thumb alignment are
69 /// counted as part of the following block (i.e., the offset and size for
70 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000071 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000072
Dale Johannesen99c49a42007-02-25 00:47:03 +000073 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000074 /// The two-byte pads required for Thumb alignment are counted as part of
75 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000076 std::vector<unsigned> BBOffsets;
77
Evan Chenga8e29892007-01-19 07:51:42 +000078 /// WaterList - A sorted list of basic blocks where islands could be placed
79 /// (i.e. blocks that don't fall through to the following block, due
80 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000081 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000082
Bob Wilsonb9239532009-10-15 20:49:47 +000083 /// NewWaterList - The subset of WaterList that was created since the
84 /// previous iteration by inserting unconditional branches.
85 SmallSet<MachineBasicBlock*, 4> NewWaterList;
86
Bob Wilson034de5f2009-10-12 18:52:13 +000087 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
88
Evan Chenga8e29892007-01-19 07:51:42 +000089 /// CPUser - One user of a constant pool, keeping the machine instruction
90 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +000091 /// allowed from the instruction to the CP. The HighWaterMark records the
92 /// highest basic block where a new CPEntry can be placed. To ensure this
93 /// pass terminates, the CP entries are initially placed at the end of the
94 /// function and then move monotonically to lower addresses. The
95 /// exception to this rule is when the current CP entry for a particular
96 /// CPUser is out of range, but there is another CP entry for the same
97 /// constant value in range. We want to use the existing in-range CP
98 /// entry, but if it later moves out of range, the search for new water
99 /// should resume where it left off. The HighWaterMark is used to record
100 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000101 struct CPUser {
102 MachineInstr *MI;
103 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000104 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000105 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000106 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000107 bool IsSoImm;
108 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
109 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000110 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
111 HighWaterMark = CPEMI->getParent();
112 }
Evan Chenga8e29892007-01-19 07:51:42 +0000113 };
Bob Wilson84945262009-05-12 17:09:30 +0000114
Evan Chenga8e29892007-01-19 07:51:42 +0000115 /// CPUsers - Keep track of all of the machine instructions that use various
116 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000117 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000118
Evan Chengc99ef082007-02-09 20:54:44 +0000119 /// CPEntry - One per constant pool entry, keeping the machine instruction
120 /// pointer, the constpool index, and the number of CPUser's which
121 /// reference this entry.
122 struct CPEntry {
123 MachineInstr *CPEMI;
124 unsigned CPI;
125 unsigned RefCount;
126 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
127 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
128 };
129
130 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000131 /// instructions. For each original constpool index (i.e. those that
132 /// existed upon entry to this pass), it keeps a vector of entries.
133 /// Original elements are cloned as we go along; the clones are
134 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000135 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000136
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000137 /// ImmBranch - One per immediate branch, keeping the machine instruction
138 /// pointer, conditional or unconditional, the max displacement,
139 /// and (if isCond is true) the corresponding unconditional branch
140 /// opcode.
141 struct ImmBranch {
142 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000143 unsigned MaxDisp : 31;
144 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000145 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000146 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
147 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000148 };
149
Evan Cheng2706f972007-05-16 05:14:06 +0000150 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000151 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000152 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000153
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000154 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
155 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000156 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000157
Evan Cheng5657c012009-07-29 02:18:14 +0000158 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
159 SmallVector<MachineInstr*, 4> T2JumpTables;
160
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000161 /// HasFarJump - True if any far jump instruction has been emitted during
162 /// the branch fix up pass.
163 bool HasFarJump;
164
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000165 /// HasInlineAsm - True if the function contains inline assembly.
166 bool HasInlineAsm;
167
Chris Lattner20628752010-07-22 21:27:00 +0000168 const ARMInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000169 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000170 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000171 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000172 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000173 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000174 public:
Devang Patel19974732007-05-03 01:11:54 +0000175 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000176 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000177
Evan Cheng5657c012009-07-29 02:18:14 +0000178 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000179
180 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000181 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000182 }
Bob Wilson84945262009-05-12 17:09:30 +0000183
Evan Chenga8e29892007-01-19 07:51:42 +0000184 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000185 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000186 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000187 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jim Grosbach80697d12009-11-12 17:25:07 +0000188 void JumpTableFunctionScan(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000189 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000190 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000191 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000192 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000193 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000194 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000195 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000196 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000197 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000198 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000199 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000200 void RemoveDeadCPEMI(MachineInstr *CPEMI);
201 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000202 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000203 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
204 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000205 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000206 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000207 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000208 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000209 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000210 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
211 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
212 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000213 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000214 bool OptimizeThumb2Instructions(MachineFunction &MF);
215 bool OptimizeThumb2Branches(MachineFunction &MF);
Jim Grosbach80697d12009-11-12 17:25:07 +0000216 bool ReorderThumb2JumpTables(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000217 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000218 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
219 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000220
Evan Chenga8e29892007-01-19 07:51:42 +0000221 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000222 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000223 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000224 };
Devang Patel19974732007-05-03 01:11:54 +0000225 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000226}
227
Dale Johannesen8593e412007-04-29 19:19:30 +0000228/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000229void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000230 assert(BBOffsets.size() == BBSizes.size());
231 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
232 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000233 if (!isThumb)
234 return;
235#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000236 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000237 MBBI != E; ++MBBI) {
238 MachineBasicBlock *MBB = MBBI;
239 if (!MBB->empty() &&
240 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
241 unsigned MBBId = MBB->getNumber();
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000242 assert(HasInlineAsm ||
243 (BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
Evan Chengd3d9d662009-07-23 18:27:47 +0000244 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000245 }
246 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000247 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
248 CPUser &U = CPUsers[i];
249 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000250 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
251 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
252 UserOffset - CPEOffset;
253 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000254 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000255#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000256}
257
258/// print block size and offset information - debugging
259void ARMConstantIslands::dumpBBs() {
260 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000261 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
262 << " size " << BBSizes[J] << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000263 }
264}
265
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000266/// createARMConstantIslandPass - returns an instance of the constpool
267/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000268FunctionPass *llvm::createARMConstantIslandPass() {
269 return new ARMConstantIslands();
270}
271
Evan Cheng5657c012009-07-29 02:18:14 +0000272bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
273 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000274
Chris Lattner20628752010-07-22 21:27:00 +0000275 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
Evan Cheng5657c012009-07-29 02:18:14 +0000276 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000277 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
278
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000279 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000280 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000281 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000282
283 HasFarJump = false;
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000284 HasInlineAsm = false;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000285
Evan Chenga8e29892007-01-19 07:51:42 +0000286 // Renumber all of the machine basic blocks in the function, guaranteeing that
287 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000288 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000289
Jim Grosbach80697d12009-11-12 17:25:07 +0000290 // Try to reorder and otherwise adjust the block layout to make good use
291 // of the TB[BH] instructions.
292 bool MadeChange = false;
293 if (isThumb2 && AdjustJumpTableBlocks) {
294 JumpTableFunctionScan(MF);
295 MadeChange |= ReorderThumb2JumpTables(MF);
296 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000297 T2JumpTables.clear();
298 // Blocks may have shifted around. Keep the numbering up to date.
299 MF.RenumberBlocks();
300 }
301
Evan Chengd26b14c2009-07-31 18:28:05 +0000302 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000303 // This is so we can keep exact track of where the alignment padding goes.
304
Chris Lattner7d7dab02010-01-27 23:37:36 +0000305 // ARM and Thumb2 functions need to be 4-byte aligned.
306 if (!isThumb1)
307 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000308
Evan Chenga8e29892007-01-19 07:51:42 +0000309 // Perform the initial placement of the constant pool entries. To start with,
310 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000311 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000312 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000313 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000314 if (isThumb1)
Chris Lattner7d7dab02010-01-27 23:37:36 +0000315 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000316 }
Bob Wilson84945262009-05-12 17:09:30 +0000317
Evan Chenga8e29892007-01-19 07:51:42 +0000318 /// The next UID to take is the first unused one.
Evan Cheng5de5d4b2011-01-17 08:03:18 +0000319 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000320
Evan Chenga8e29892007-01-19 07:51:42 +0000321 // Do the initial scan of the function, building up information about the
322 // sizes of each block, the location of all the water, and finding all of the
323 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000324 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000325 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000326 DEBUG(dumpBBs());
327
Bob Wilson84945262009-05-12 17:09:30 +0000328
Evan Chenged884f32007-04-03 23:39:48 +0000329 /// Remove dead constant pool entries.
Bill Wendlingcd080242010-12-18 01:53:06 +0000330 MadeChange |= RemoveUnusedCPEntries();
Evan Chenged884f32007-04-03 23:39:48 +0000331
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000332 // Iteratively place constant pool entries and fix up branches until there
333 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000334 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000335 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000336 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000337 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000338 CPChange |= HandleConstantPoolUser(MF, i);
339 if (CPChange && ++NoCPIters > 30)
340 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000341 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000342
Bob Wilsonb9239532009-10-15 20:49:47 +0000343 // Clear NewWaterList now. If we split a block for branches, it should
344 // appear as "new water" for the next iteration of constant pool placement.
345 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000346
347 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000348 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000349 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
350 if (BRChange && ++NoBRIters > 30)
351 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000352 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000353
354 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000355 break;
356 MadeChange = true;
357 }
Evan Chenged884f32007-04-03 23:39:48 +0000358
Evan Chenga1efbbd2009-08-14 00:32:16 +0000359 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000360 if (isThumb2 && !STI->prefers32BitThumb())
Evan Chenga1efbbd2009-08-14 00:32:16 +0000361 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000362
Dale Johannesen8593e412007-04-29 19:19:30 +0000363 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000364 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000365
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000366 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
367 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000368 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000369 MadeChange |= UndoLRSpillRestore();
370
Anton Korobeynikov98b928e2011-01-30 22:07:39 +0000371 // Save the mapping between original and cloned constpool entries.
372 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
373 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
374 const CPEntry & CPE = CPEntries[i][j];
375 AFI->recordCPEClone(i, CPE.CPI);
376 }
377 }
378
Evan Chengb1c857b2010-07-22 02:09:47 +0000379 DEBUG(errs() << '\n'; dumpBBs());
380
Evan Chenga8e29892007-01-19 07:51:42 +0000381 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000382 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000383 WaterList.clear();
384 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000385 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000386 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000387 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000388 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000389
390 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000391}
392
393/// DoInitialPlacement - Perform the initial placement of the constant pool
394/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000395void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000396 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000397 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000398 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
399 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000400
Evan Chenga8e29892007-01-19 07:51:42 +0000401 // Add all of the constants from the constant pool to the end block, use an
402 // identity mapping of CPI's to CPE's.
403 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000404 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000405
Evan Cheng5657c012009-07-29 02:18:14 +0000406 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000407 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000408 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000409 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
410 // we would have to pad them out or something so that instructions stay
411 // aligned.
412 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
413 MachineInstr *CPEMI =
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000414 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
415 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000416 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000417
418 // Add a new CPEntry, but no corresponding CPUser yet.
419 std::vector<CPEntry> CPEs;
420 CPEs.push_back(CPEntry(CPEMI, i));
421 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000422 ++NumCPEs;
Chris Lattner893e1c92009-08-23 06:49:22 +0000423 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
424 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000425 }
426}
427
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000428/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000429/// into the block immediately after it.
430static bool BBHasFallthrough(MachineBasicBlock *MBB) {
431 // Get the next machine basic block in the function.
432 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000433 // Can't fall off end of function.
434 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000435 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000436
Chris Lattner7896c9f2009-12-03 00:50:42 +0000437 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000438 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
439 E = MBB->succ_end(); I != E; ++I)
440 if (*I == NextBB)
441 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000442
Evan Chenga8e29892007-01-19 07:51:42 +0000443 return false;
444}
445
Evan Chengc99ef082007-02-09 20:54:44 +0000446/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
447/// look up the corresponding CPEntry.
448ARMConstantIslands::CPEntry
449*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
450 const MachineInstr *CPEMI) {
451 std::vector<CPEntry> &CPEs = CPEntries[CPI];
452 // Number of entries per constpool index should be small, just do a
453 // linear search.
454 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
455 if (CPEs[i].CPEMI == CPEMI)
456 return &CPEs[i];
457 }
458 return NULL;
459}
460
Jim Grosbach80697d12009-11-12 17:25:07 +0000461/// JumpTableFunctionScan - Do a scan of the function, building up
462/// information about the sizes of each block and the locations of all
463/// the jump tables.
464void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
Jim Grosbach80697d12009-11-12 17:25:07 +0000465 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
466 MBBI != E; ++MBBI) {
467 MachineBasicBlock &MBB = *MBBI;
468
Jim Grosbach80697d12009-11-12 17:25:07 +0000469 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000470 I != E; ++I)
471 if (I->getDesc().isBranch() && I->getOpcode() == ARM::t2BR_JT)
472 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000473 }
474}
475
Evan Chenga8e29892007-01-19 07:51:42 +0000476/// InitialFunctionScan - Do the initial scan of the function, building up
477/// information about the sizes of each block, the location of all the water,
478/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000479void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000480 const std::vector<MachineInstr*> &CPEMIs) {
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000481 // First thing, see if the function has any inline assembly in it. If so,
482 // we have to be conservative about alignment assumptions, as we don't
483 // know for sure the size of any instructions in the inline assembly.
484 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
485 MBBI != E; ++MBBI) {
486 MachineBasicBlock &MBB = *MBBI;
487 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
488 I != E; ++I)
489 if (I->getOpcode() == ARM::INLINEASM)
490 HasInlineAsm = true;
491 }
492
Bill Wendling9a4d2e42010-12-21 01:54:40 +0000493 // Now go back through the instructions and build up our data structures.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000494 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000495 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000496 MBBI != E; ++MBBI) {
497 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000498
Evan Chenga8e29892007-01-19 07:51:42 +0000499 // If this block doesn't fall through into the next MBB, then this is
500 // 'water' that a constant pool island could be placed.
501 if (!BBHasFallthrough(&MBB))
502 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000503
Evan Chenga8e29892007-01-19 07:51:42 +0000504 unsigned MBBSize = 0;
505 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
506 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000507 if (I->isDebugValue())
508 continue;
Evan Chenga8e29892007-01-19 07:51:42 +0000509 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000510 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000511
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000512 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000513 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000514 bool isCond = false;
515 unsigned Bits = 0;
516 unsigned Scale = 1;
517 int UOpc = Opc;
518 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000519 default:
520 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000521 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000522 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000523 // be right, functions containing these must be 4-byte aligned.
Evan Chengb1c857b2010-07-22 02:09:47 +0000524 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
525 // table entries. So this code checks whether offset of tBR_JTr + 2
Dale Johannesen8086d582010-07-23 22:50:23 +0000526 // is aligned. That is held in Offset+MBBSize, which already has
527 // 2 added in for the size of the mov pc instruction.
Chris Lattner7d7dab02010-01-27 23:37:36 +0000528 MF.EnsureAlignment(2U);
Dale Johannesen8086d582010-07-23 22:50:23 +0000529 if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
Evan Cheng5657c012009-07-29 02:18:14 +0000530 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000531 MBBSize += 2; // padding
532 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000533 case ARM::t2BR_JT:
534 T2JumpTables.push_back(I);
535 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000536 case ARM::Bcc:
537 isCond = true;
538 UOpc = ARM::B;
539 // Fallthrough
540 case ARM::B:
541 Bits = 24;
542 Scale = 4;
543 break;
544 case ARM::tBcc:
545 isCond = true;
546 UOpc = ARM::tB;
547 Bits = 8;
548 Scale = 2;
549 break;
550 case ARM::tB:
551 Bits = 11;
552 Scale = 2;
553 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000554 case ARM::t2Bcc:
555 isCond = true;
556 UOpc = ARM::t2B;
557 Bits = 20;
558 Scale = 2;
559 break;
560 case ARM::t2B:
561 Bits = 24;
562 Scale = 2;
563 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000564 }
Evan Chengb43216e2007-02-01 10:16:15 +0000565
566 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000567 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000568 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000569 }
570
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000571 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
572 PushPopMIs.push_back(I);
573
Evan Chengd3d9d662009-07-23 18:27:47 +0000574 if (Opc == ARM::CONSTPOOL_ENTRY)
575 continue;
576
Evan Chenga8e29892007-01-19 07:51:42 +0000577 // Scan the instructions for constant pool operands.
578 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000579 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000580 // We found one. The addressing mode tells us the max displacement
581 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000582
Evan Chenga8e29892007-01-19 07:51:42 +0000583 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000584 unsigned Bits = 0;
585 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000586 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000587 bool IsSoImm = false;
588
589 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000590 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000591 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000592 break;
593
594 // Taking the address of a CP entry.
595 case ARM::LEApcrel:
596 // This takes a SoImm, which is 8 bit immediate rotated. We'll
597 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000598 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000599 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000600 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000601 Scale = 4;
602 NegOk = true;
603 IsSoImm = true;
604 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000605 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000606 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000607 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000608 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000609 case ARM::tLEApcrel:
610 Bits = 8;
611 Scale = 4;
612 break;
613
Jim Grosbach3e556122010-10-26 22:37:02 +0000614 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000615 case ARM::LDRcp:
Owen Anderson971b83b2011-02-08 22:39:40 +0000616 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000617 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000618 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000619 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000620
621 case ARM::tLDRpci:
Evan Chengb43216e2007-02-01 10:16:15 +0000622 Bits = 8;
623 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000624 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000625
Jim Grosbache5165492009-11-09 00:11:35 +0000626 case ARM::VLDRD:
627 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000628 Bits = 8;
629 Scale = 4; // +-(offset_8*4)
630 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000631 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000632 }
Evan Chengb43216e2007-02-01 10:16:15 +0000633
Evan Chenga8e29892007-01-19 07:51:42 +0000634 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000635 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000636 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000637 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000638 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000639
640 // Increment corresponding CPEntry reference count.
641 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
642 assert(CPE && "Cannot find a corresponding CPEntry!");
643 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000644
Evan Chenga8e29892007-01-19 07:51:42 +0000645 // Instructions can only use one CP entry, don't bother scanning the
646 // rest of the operands.
647 break;
648 }
649 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000650
Dale Johannesen8593e412007-04-29 19:19:30 +0000651 // In thumb mode, if this block is a constpool island, we may need padding
652 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000653 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000654 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000655 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000656 ((Offset%4) != 0 || HasInlineAsm))
Evan Cheng2021abe2007-02-01 01:09:47 +0000657 MBBSize += 2;
658
Evan Chenga8e29892007-01-19 07:51:42 +0000659 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000660 BBOffsets.push_back(Offset);
661 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000662 }
663}
664
Evan Chenga8e29892007-01-19 07:51:42 +0000665/// GetOffsetOf - Return the current offset of the specified machine instruction
666/// from the start of the function. This offset changes as stuff is moved
667/// around inside the function.
668unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
669 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000670
Evan Chenga8e29892007-01-19 07:51:42 +0000671 // The offset is composed of two things: the sum of the sizes of all MBB's
672 // before this instruction's block, and the offset from the start of the block
673 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000674 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000675
Dale Johannesen8593e412007-04-29 19:19:30 +0000676 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
677 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000678 if (isThumb &&
679 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000680 (Offset%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +0000681 Offset += 2;
682
Evan Chenga8e29892007-01-19 07:51:42 +0000683 // Sum instructions before MI in MBB.
684 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
685 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
686 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000687 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000688 }
689}
690
691/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
692/// ID.
693static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
694 const MachineBasicBlock *RHS) {
695 return LHS->getNumber() < RHS->getNumber();
696}
697
698/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
699/// machine function, it upsets all of the block numbers. Renumber the blocks
700/// and update the arrays that parallel this numbering.
701void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sandsab4c3662011-02-15 09:23:02 +0000702 // Renumber the MBB's to keep them consecutive.
Evan Chenga8e29892007-01-19 07:51:42 +0000703 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000704
Evan Chenga8e29892007-01-19 07:51:42 +0000705 // Insert a size into BBSizes to align it properly with the (newly
706 // renumbered) block numbers.
707 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000708
709 // Likewise for BBOffsets.
710 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000711
712 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000713 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000714 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000715 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
716 CompareMBBNumbers);
717 WaterList.insert(IP, NewBB);
718}
719
720
721/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000722/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000723/// account for this change and returns the newly created block.
724MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000725 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000726 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000727
728 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000729 MachineBasicBlock *NewBB =
730 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000731 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000732 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000733
Evan Chenga8e29892007-01-19 07:51:42 +0000734 // Splice the instructions starting with MI over to NewBB.
735 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000736
Evan Chenga8e29892007-01-19 07:51:42 +0000737 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000738 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000739 // There doesn't seem to be meaningful DebugInfo available; this doesn't
740 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000741 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000742 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
Dan Gohmanfe601042010-06-22 15:08:57 +0000743 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000744
Evan Chenga8e29892007-01-19 07:51:42 +0000745 // Update the CFG. All succs of OrigBB are now succs of NewBB.
746 while (!OrigBB->succ_empty()) {
747 MachineBasicBlock *Succ = *OrigBB->succ_begin();
748 OrigBB->removeSuccessor(Succ);
749 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000750
Evan Chenga8e29892007-01-19 07:51:42 +0000751 // This pass should be run after register allocation, so there should be no
752 // PHI nodes to update.
Chris Lattner518bb532010-02-09 19:54:29 +0000753 assert((Succ->empty() || !Succ->begin()->isPHI())
Evan Chenga8e29892007-01-19 07:51:42 +0000754 && "PHI nodes should be eliminated by now!");
755 }
Bob Wilson84945262009-05-12 17:09:30 +0000756
Evan Chenga8e29892007-01-19 07:51:42 +0000757 // OrigBB branches to NewBB.
758 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000759
Evan Chenga8e29892007-01-19 07:51:42 +0000760 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000761 // This is almost the same as UpdateForInsertedWaterBlock, except that
762 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000763 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000764
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000765 // Insert a size into BBSizes to align it properly with the (newly
766 // renumbered) block numbers.
767 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000768
Dale Johannesen99c49a42007-02-25 00:47:03 +0000769 // Likewise for BBOffsets.
770 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
771
Bob Wilson84945262009-05-12 17:09:30 +0000772 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000773 // available water after it (but not if it's already there, which happens
774 // when splitting before a conditional branch that is followed by an
775 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000776 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000777 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
778 CompareMBBNumbers);
779 MachineBasicBlock* WaterBB = *IP;
780 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000781 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000782 else
783 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000784 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000785
Dale Johannesen99c49a42007-02-25 00:47:03 +0000786 unsigned OrigBBI = OrigBB->getNumber();
787 unsigned NewBBI = NewBB->getNumber();
Bob Wilson84945262009-05-12 17:09:30 +0000788
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000789 int delta = isThumb1 ? 2 : 4;
Dale Johannesen8086d582010-07-23 22:50:23 +0000790
791 // Figure out how large the OrigBB is. As the first half of the original
792 // block, it cannot contain a tablejump. The size includes
793 // the new jump we added. (It should be possible to do this without
794 // recounting everything, but it's very confusing, and this is rarely
795 // executed.)
796 unsigned OrigBBSize = 0;
797 for (MachineBasicBlock::iterator I = OrigBB->begin(), E = OrigBB->end();
798 I != E; ++I)
799 OrigBBSize += TII->GetInstSizeInBytes(I);
800 BBSizes[OrigBBI] = OrigBBSize;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000801
802 // ...and adjust BBOffsets for NewBB accordingly.
803 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
804
Dale Johannesen8086d582010-07-23 22:50:23 +0000805 // Figure out how large the NewMBB is. As the second half of the original
806 // block, it may contain a tablejump.
807 unsigned NewBBSize = 0;
808 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
809 I != E; ++I)
810 NewBBSize += TII->GetInstSizeInBytes(I);
811 // Set the size of NewBB in BBSizes. It does not include any padding now.
812 BBSizes[NewBBI] = NewBBSize;
813
814 MachineInstr* ThumbJTMI = prior(NewBB->end());
815 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
816 // We've added another 2-byte instruction before this tablejump, which
817 // means we will always need padding if we didn't before, and vice versa.
818
819 // The original offset of the jump instruction was:
820 unsigned OrigOffset = BBOffsets[OrigBBI] + BBSizes[OrigBBI] - delta;
821 if (OrigOffset%4 == 0) {
822 // We had padding before and now we don't. No net change in code size.
823 delta = 0;
824 } else {
825 // We didn't have padding before and now we do.
826 BBSizes[NewBBI] += 2;
827 delta = 4;
828 }
829 }
830
Dale Johannesen99c49a42007-02-25 00:47:03 +0000831 // All BBOffsets following these blocks must be modified.
Dale Johannesen8086d582010-07-23 22:50:23 +0000832 if (delta)
833 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000834
835 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000836}
837
Dale Johannesen8593e412007-04-29 19:19:30 +0000838/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000839/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000840/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000841bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000842 unsigned TrialOffset, unsigned MaxDisp,
843 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000844 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
845 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000846 // Effectively, the valid range of displacements is 2 bytes smaller for such
847 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000848 unsigned TotalAdj = 0;
849 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000850 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000851 TotalAdj = 2;
852 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000853 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000854 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000855 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000856 TotalAdj += 2;
857 }
858
859 // In Thumb2 mode, later branch adjustments can shift instructions up and
860 // cause alignment change. In the worst case scenario this can cause the
861 // user's effective address to be subtracted by 2 and the CPE's address to
862 // be plus 2.
863 if (isThumb2 && TotalAdj != 4)
864 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000865
Dale Johannesen99c49a42007-02-25 00:47:03 +0000866 if (UserOffset <= TrialOffset) {
867 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000868 if (TrialOffset - UserOffset <= MaxDisp)
869 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000870 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000871 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000872 if (UserOffset - TrialOffset <= MaxDisp)
873 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000874 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000875 }
876 return false;
877}
878
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000879/// WaterIsInRange - Returns true if a CPE placed after the specified
880/// Water (a basic block) will be in range for the specific MI.
881
882bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000883 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000884 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000885 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000886 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000887
Dale Johannesend959aa42007-04-02 20:31:06 +0000888 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000889 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000890 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000891 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000892
Evan Chengd3d9d662009-07-23 18:27:47 +0000893 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000894}
895
896/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000897/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000898bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000899 MachineInstr *CPEMI, unsigned MaxDisp,
900 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000901 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000902 assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000903
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000904 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000905 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
906 << " max delta=" << MaxDisp
907 << " insn address=" << UserOffset
908 << " CPE address=" << CPEOffset
909 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000910 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000911
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000912 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000913}
914
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000915#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000916/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
917/// unconditionally branches to its only successor.
918static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
919 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
920 return false;
921
922 MachineBasicBlock *Succ = *MBB->succ_begin();
923 MachineBasicBlock *Pred = *MBB->pred_begin();
924 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000925 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
926 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000927 return PredMI->getOperand(0).getMBB() == Succ;
928 return false;
929}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000930#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000931
Bob Wilson84945262009-05-12 17:09:30 +0000932void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000933 int delta) {
Chris Lattner7896c9f2009-12-03 00:50:42 +0000934 MachineFunction::iterator MBBI = BB; MBBI = llvm::next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000935 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
936 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000937 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000938 // If some existing blocks have padding, adjust the padding as needed, a
939 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000940 if (!isThumb)
941 continue;
942 MachineBasicBlock *MBB = MBBI;
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000943 if (!MBB->empty() && !HasInlineAsm) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000944 // Constant pool entries require padding.
945 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000946 unsigned OldOffset = BBOffsets[i] - delta;
947 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000948 // add new padding
949 BBSizes[i] += 2;
950 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000951 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000952 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000953 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000954 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000955 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000956 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000957 // Thumb1 jump tables require padding. They should be at the end;
958 // following unconditional branches are removed by AnalyzeBranch.
Evan Chengb1c857b2010-07-22 02:09:47 +0000959 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
Dale Johannesen8086d582010-07-23 22:50:23 +0000960 // table entries. So this code checks whether offset of tBR_JTr
961 // is aligned; if it is, the offset of the jump table following the
962 // instruction will not be aligned, and we need padding.
Evan Cheng78947622009-07-24 18:20:44 +0000963 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000964 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Dale Johannesen8086d582010-07-23 22:50:23 +0000965 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
Evan Cheng4a8ea212009-08-11 07:36:14 +0000966 unsigned OldMIOffset = NewMIOffset - delta;
967 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000968 // remove existing padding
969 BBSizes[i] -= 2;
970 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000971 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000972 // add new padding
973 BBSizes[i] += 2;
974 delta += 2;
975 }
976 }
977 if (delta==0)
978 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000979 }
Chris Lattner7896c9f2009-12-03 00:50:42 +0000980 MBBI = llvm::next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000981 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000982}
983
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000984/// DecrementOldEntry - find the constant pool entry with index CPI
985/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000986/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000987/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000988
Evan Chenged884f32007-04-03 23:39:48 +0000989bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000990 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000991 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
992 assert(CPE && "Unexpected!");
993 if (--CPE->RefCount == 0) {
994 RemoveDeadCPEMI(CPEMI);
995 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +0000996 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000997 return true;
998 }
999 return false;
1000}
1001
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001002/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1003/// if not, see if an in-range clone of the CPE is in range, and if so,
1004/// change the data structures so the user references the clone. Returns:
1005/// 0 = no existing entry found
1006/// 1 = entry found, and there were no code insertions or deletions
1007/// 2 = entry found, and there were code insertions or deletions
1008int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1009{
1010 MachineInstr *UserMI = U.MI;
1011 MachineInstr *CPEMI = U.CPEMI;
1012
1013 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001014 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001015 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001016 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001017 }
1018
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001019 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001020 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001021 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1022 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1023 // We already tried this one
1024 if (CPEs[i].CPEMI == CPEMI)
1025 continue;
1026 // Removing CPEs can leave empty entries, skip
1027 if (CPEs[i].CPEMI == NULL)
1028 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001029 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001030 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1031 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001032 // Point the CPUser node to the replacement
1033 U.CPEMI = CPEs[i].CPEMI;
1034 // Change the CPI in the instruction operand to refer to the clone.
1035 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001036 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001037 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001038 break;
1039 }
1040 // Adjust the refcount of the clone...
1041 CPEs[i].RefCount++;
1042 // ...and the original. If we didn't remove the old entry, none of the
1043 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001044 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001045 }
1046 }
1047 return 0;
1048}
1049
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001050/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1051/// the specific unconditional branch instruction.
1052static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001053 switch (Opc) {
1054 case ARM::tB:
1055 return ((1<<10)-1)*2;
1056 case ARM::t2B:
1057 return ((1<<23)-1)*2;
1058 default:
1059 break;
1060 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001061
David Goodwin5e47a9a2009-06-30 18:04:13 +00001062 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001063}
1064
Bob Wilsonb9239532009-10-15 20:49:47 +00001065/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001066/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001067/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001068/// is set to the WaterList entry. For Thumb, prefer water that will not
1069/// introduce padding to water that will. To ensure that this pass
1070/// terminates, the CPE location for a particular CPUser is only allowed to
1071/// move to a lower address, so search backward from the end of the list and
1072/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001073bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001074 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001075 if (WaterList.empty())
1076 return false;
1077
Bob Wilson32c50e82009-10-12 20:45:53 +00001078 bool FoundWaterThatWouldPad = false;
1079 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001080 for (water_iterator IP = prior(WaterList.end()),
1081 B = WaterList.begin();; --IP) {
1082 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001083 // Check if water is in range and is either at a lower address than the
1084 // current "high water mark" or a new water block that was created since
1085 // the previous iteration by inserting an unconditional branch. In the
1086 // latter case, we want to allow resetting the high water mark back to
1087 // this new water since we haven't seen it before. Inserting branches
1088 // should be relatively uncommon and when it does happen, we want to be
1089 // sure to take advantage of it for all the CPEs near that block, so that
1090 // we don't insert more branches than necessary.
1091 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1092 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1093 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001094 unsigned WBBId = WaterBB->getNumber();
1095 if (isThumb &&
1096 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
1097 // This is valid Water, but would introduce padding. Remember
1098 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001099 if (!FoundWaterThatWouldPad) {
1100 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001101 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001102 }
Bob Wilson3b757352009-10-12 19:04:03 +00001103 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001104 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001105 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001106 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001107 }
Bob Wilson3b757352009-10-12 19:04:03 +00001108 if (IP == B)
1109 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001110 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001111 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001112 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001113 return true;
1114 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001115 return false;
1116}
1117
Bob Wilson84945262009-05-12 17:09:30 +00001118/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001119/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1120/// block is used if in range, and the conditional branch munged so control
1121/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001122/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001123/// block following which the new island can be inserted (the WaterList
1124/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001125void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001126 unsigned UserOffset,
1127 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001128 CPUser &U = CPUsers[CPUserIndex];
1129 MachineInstr *UserMI = U.MI;
1130 MachineInstr *CPEMI = U.CPEMI;
1131 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001132 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001133 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001134 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001135
Bob Wilson36fa5322009-10-15 05:10:36 +00001136 // If the block does not end in an unconditional branch already, and if the
1137 // end of the block is within range, make new water there. (The addition
1138 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1139 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001140 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001141 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001142 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1143 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001144 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001145 if (&UserMBB->back() == UserMI)
1146 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001147 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001148 // Add an unconditional branch from UserMBB to fallthrough block.
1149 // Record it for branch lengthening; this new branch will not get out of
1150 // range, but if the preceding conditional branch is out of range, the
1151 // targets will be exchanged, and the altered branch may be out of
1152 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001153 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001154 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001155 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001156 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001157 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001158 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001159 BBSizes[UserMBB->getNumber()] += delta;
1160 AdjustBBOffsetsAfter(UserMBB, delta);
1161 } else {
1162 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001163 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001164 // and constant pool entries are 4 bytes: if instruction I references
1165 // island CPE, and instruction I+1 references CPE', it will
1166 // not work well to put CPE as far forward as possible, since then
1167 // CPE' cannot immediately follow it (that location is 2 bytes
1168 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001169 // a new island. So, we make a first guess, then walk through the
1170 // instructions between the one currently being looked at and the
1171 // possible insertion point, and make sure any other instructions
1172 // that reference CPEs will be able to use the same island area;
1173 // if not, we back up the insertion point.
1174
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001175 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001176 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001177 // island is handled inside OffsetIsInRange.
1178 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001179 // This could point off the end of the block if we've already got
1180 // constant pool entries following this block; only the last one is
1181 // in the water list. Back past any possible branches (allow for a
1182 // conditional and a maximally long unconditional).
1183 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001184 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001185 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001186 unsigned EndInsertOffset = BaseInsertOffset +
1187 CPEMI->getOperand(2).getImm();
1188 MachineBasicBlock::iterator MI = UserMI;
1189 ++MI;
1190 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001191 unsigned NumCPUsers = CPUsers.size();
1192 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001193 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001194 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001195 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001196 MI = llvm::next(MI)) {
1197 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001198 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001199 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001200 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1201 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1202 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001203 }
1204 // This is overly conservative, as we don't account for CPEMIs
1205 // being reused within the block, but it doesn't matter much.
1206 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1207 CPUIndex++;
1208 }
Evan Cheng719510a2010-08-12 20:30:05 +00001209
1210 // Remember the last IT instruction.
1211 if (MI->getOpcode() == ARM::t2IT)
1212 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001213 }
Evan Cheng719510a2010-08-12 20:30:05 +00001214
Chris Lattner893e1c92009-08-23 06:49:22 +00001215 DEBUG(errs() << "Split in middle of big block\n");
Evan Cheng719510a2010-08-12 20:30:05 +00001216 --MI;
1217
1218 // Avoid splitting an IT block.
1219 if (LastIT) {
1220 unsigned PredReg = 0;
1221 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1222 if (CC != ARMCC::AL)
1223 MI = LastIT;
1224 }
1225 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001226 }
1227}
1228
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001229/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001230/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001231/// place in-range. Return true if we changed any addresses (thus must run
1232/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001233bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001234 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001235 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001236 MachineInstr *UserMI = U.MI;
1237 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001238 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001239 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001240 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001241 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001242 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001243
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001244 // See if the current entry is within range, or there is a clone of it
1245 // in range.
1246 int result = LookForExistingCPEntry(U, UserOffset);
1247 if (result==1) return false;
1248 else if (result==2) return true;
1249
1250 // No existing clone of this CPE is within range.
1251 // We will be generating a new clone. Get a UID for it.
Evan Cheng5de5d4b2011-01-17 08:03:18 +00001252 unsigned ID = AFI->createPICLabelUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001253
Bob Wilsonf98032e2009-10-12 21:23:15 +00001254 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001255 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1256 MachineBasicBlock *NewMBB;
1257 water_iterator IP;
1258 if (LookForWater(U, UserOffset, IP)) {
1259 DEBUG(errs() << "found water in range\n");
1260 MachineBasicBlock *WaterBB = *IP;
1261
1262 // If the original WaterList entry was "new water" on this iteration,
1263 // propagate that to the new island. This is just keeping NewWaterList
1264 // updated to match the WaterList, which will be updated below.
1265 if (NewWaterList.count(WaterBB)) {
1266 NewWaterList.erase(WaterBB);
1267 NewWaterList.insert(NewIsland);
1268 }
1269 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001270 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001271
1272 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001273 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001274 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001275 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001276
1277 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1278 // called while handling branches so that the water will be seen on the
1279 // next iteration for constant pools, but in this context, we don't want
1280 // it. Check for this so it will be removed from the WaterList.
1281 // Also remove any entry from NewWaterList.
1282 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1283 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1284 if (IP != WaterList.end())
1285 NewWaterList.erase(WaterBB);
1286
1287 // We are adding new water. Update NewWaterList.
1288 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001289 }
1290
Bob Wilsonb9239532009-10-15 20:49:47 +00001291 // Remove the original WaterList entry; we want subsequent insertions in
1292 // this vicinity to go after the one we're about to insert. This
1293 // considerably reduces the number of times we have to move the same CPE
1294 // more than once and is also important to ensure the algorithm terminates.
1295 if (IP != WaterList.end())
1296 WaterList.erase(IP);
1297
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001298 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001299 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001300
1301 // Update internal data structures to account for the newly inserted MBB.
1302 UpdateForInsertedWaterBlock(NewIsland);
1303
1304 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001305 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001306
1307 // Now that we have an island to add the CPE to, clone the original CPE and
1308 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001309 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001310 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001311 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001312 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001313 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001314
Dale Johannesen8593e412007-04-29 19:19:30 +00001315 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001316 // Compensate for .align 2 in thumb mode.
Jim Grosbach4d8e90a2009-11-19 23:10:28 +00001317 if (isThumb && (BBOffsets[NewIsland->getNumber()]%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +00001318 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001319 // Increase the size of the island block to account for the new entry.
1320 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001321 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001322
Evan Chenga8e29892007-01-19 07:51:42 +00001323 // Finally, change the CPI in the instruction operand to be ID.
1324 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001325 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001326 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001327 break;
1328 }
Bob Wilson84945262009-05-12 17:09:30 +00001329
Chris Lattner705e07f2009-08-23 03:41:05 +00001330 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1331 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001332
Evan Chenga8e29892007-01-19 07:51:42 +00001333 return true;
1334}
1335
Evan Chenged884f32007-04-03 23:39:48 +00001336/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1337/// sizes and offsets of impacted basic blocks.
1338void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1339 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001340 unsigned Size = CPEMI->getOperand(2).getImm();
1341 CPEMI->eraseFromParent();
1342 BBSizes[CPEBB->getNumber()] -= Size;
1343 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001344 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001345 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001346 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001347 // empty, so fix this.
1348 // All succeeding offsets have the current size value added in, fix this.
1349 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001350 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001351 BBSizes[CPEBB->getNumber()] = 0;
1352 }
Evan Chenged884f32007-04-03 23:39:48 +00001353 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001354 AdjustBBOffsetsAfter(CPEBB, -Size);
1355 // An island has only one predecessor BB and one successor BB. Check if
1356 // this BB's predecessor jumps directly to this BB's successor. This
1357 // shouldn't happen currently.
1358 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1359 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001360}
1361
1362/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1363/// are zero.
1364bool ARMConstantIslands::RemoveUnusedCPEntries() {
1365 unsigned MadeChange = false;
1366 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1367 std::vector<CPEntry> &CPEs = CPEntries[i];
1368 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1369 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1370 RemoveDeadCPEMI(CPEs[j].CPEMI);
1371 CPEs[j].CPEMI = NULL;
1372 MadeChange = true;
1373 }
1374 }
Bob Wilson84945262009-05-12 17:09:30 +00001375 }
Evan Chenged884f32007-04-03 23:39:48 +00001376 return MadeChange;
1377}
1378
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001379/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001380/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001381bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1382 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001383 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001384 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001385 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001386
Chris Lattner705e07f2009-08-23 03:41:05 +00001387 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1388 << " from BB#" << MI->getParent()->getNumber()
1389 << " max delta=" << MaxDisp
1390 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1391 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001392
Dale Johannesen8593e412007-04-29 19:19:30 +00001393 if (BrOffset <= DestOffset) {
1394 // Branch before the Dest.
1395 if (DestOffset-BrOffset <= MaxDisp)
1396 return true;
1397 } else {
1398 if (BrOffset-DestOffset <= MaxDisp)
1399 return true;
1400 }
1401 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001402}
1403
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001404/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1405/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001406bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001407 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001408 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001409
Evan Chengc0dbec72007-01-31 19:57:44 +00001410 // Check to see if the DestBB is already in-range.
1411 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001412 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001413
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001414 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001415 return FixUpUnconditionalBr(MF, Br);
1416 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001417}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001418
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001419/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1420/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001421/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001422/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001423bool
Evan Cheng5657c012009-07-29 02:18:14 +00001424ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001425 MachineInstr *MI = Br.MI;
1426 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001427 if (!isThumb1)
1428 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001429
1430 // Use BL to implement far jump.
1431 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001432 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001433 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001434 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001435 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001436 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001437
Chris Lattner705e07f2009-08-23 03:41:05 +00001438 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001439
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001440 return true;
1441}
1442
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001443/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001444/// far away to fit in its displacement field. It is converted to an inverse
1445/// conditional branch + an unconditional branch to the destination.
1446bool
Evan Cheng5657c012009-07-29 02:18:14 +00001447ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001448 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001449 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001450
Bob Wilson39bf0512009-05-12 17:35:29 +00001451 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001452 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001453 // blt L1
1454 // =>
1455 // bge L2
1456 // b L1
1457 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001458 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001459 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001460 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001461
1462 // If the branch is at the end of its MBB and that has a fall-through block,
1463 // direct the updated conditional branch to the fall-through block. Otherwise,
1464 // split the MBB before the next instruction.
1465 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001466 MachineInstr *BMI = &MBB->back();
1467 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001468
Dan Gohmanfe601042010-06-22 15:08:57 +00001469 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001470 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001471 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001472 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001473 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001474 // condition and swap destinations:
1475 // beq L1
1476 // b L2
1477 // =>
1478 // bne L2
1479 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001480 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001481 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001482 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1483 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001484 BMI->getOperand(0).setMBB(DestBB);
1485 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001486 MI->getOperand(1).setImm(CC);
1487 return true;
1488 }
1489 }
1490 }
1491
1492 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001493 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001494 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001495 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001496 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001497 BBSizes[MBB->getNumber()] -= delta;
Chris Lattner7896c9f2009-12-03 00:50:42 +00001498 MachineBasicBlock* SplitBB = llvm::next(MachineFunction::iterator(MBB));
Dale Johannesen8593e412007-04-29 19:19:30 +00001499 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001500 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001501 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001502 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001503 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001504
Chris Lattner893e1c92009-08-23 06:49:22 +00001505 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1506 << " also invert condition and change dest. to BB#"
1507 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001508
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001509 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001510 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001511 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001512 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001513 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001514 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001515 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001516 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001517 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001518 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001519
1520 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001521 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001522 MI->eraseFromParent();
1523
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001524 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001525 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001526 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001527 return true;
1528}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001529
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001530/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001531/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1532/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001533bool ARMConstantIslands::UndoLRSpillRestore() {
1534 bool MadeChange = false;
1535 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1536 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001537 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001538 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001539 MI->getOperand(2).getReg() == ARM::PC &&
1540 MI->getNumExplicitOperands() == 3) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001541 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001542 MI->eraseFromParent();
1543 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001544 }
1545 }
1546 return MadeChange;
1547}
Evan Cheng5657c012009-07-29 02:18:14 +00001548
Evan Chenga1efbbd2009-08-14 00:32:16 +00001549bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1550 bool MadeChange = false;
1551
1552 // Shrink ADR and LDR from constantpool.
1553 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1554 CPUser &U = CPUsers[i];
1555 unsigned Opcode = U.MI->getOpcode();
1556 unsigned NewOpc = 0;
1557 unsigned Scale = 1;
1558 unsigned Bits = 0;
1559 switch (Opcode) {
1560 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001561 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001562 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1563 NewOpc = ARM::tLEApcrel;
1564 Bits = 8;
1565 Scale = 4;
1566 }
1567 break;
1568 case ARM::t2LDRpci:
1569 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1570 NewOpc = ARM::tLDRpci;
1571 Bits = 8;
1572 Scale = 4;
1573 }
1574 break;
1575 }
1576
1577 if (!NewOpc)
1578 continue;
1579
1580 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1581 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1582 // FIXME: Check if offset is multiple of scale if scale is not 4.
1583 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1584 U.MI->setDesc(TII->get(NewOpc));
1585 MachineBasicBlock *MBB = U.MI->getParent();
1586 BBSizes[MBB->getNumber()] -= 2;
1587 AdjustBBOffsetsAfter(MBB, -2);
1588 ++NumT2CPShrunk;
1589 MadeChange = true;
1590 }
1591 }
1592
Evan Chenga1efbbd2009-08-14 00:32:16 +00001593 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001594 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001595 return MadeChange;
1596}
1597
1598bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001599 bool MadeChange = false;
1600
1601 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1602 ImmBranch &Br = ImmBranches[i];
1603 unsigned Opcode = Br.MI->getOpcode();
1604 unsigned NewOpc = 0;
1605 unsigned Scale = 1;
1606 unsigned Bits = 0;
1607 switch (Opcode) {
1608 default: break;
1609 case ARM::t2B:
1610 NewOpc = ARM::tB;
1611 Bits = 11;
1612 Scale = 2;
1613 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001614 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001615 NewOpc = ARM::tBcc;
1616 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001617 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001618 break;
1619 }
Evan Chengde17fb62009-10-31 23:46:45 +00001620 }
1621 if (NewOpc) {
1622 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1623 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1624 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1625 Br.MI->setDesc(TII->get(NewOpc));
1626 MachineBasicBlock *MBB = Br.MI->getParent();
1627 BBSizes[MBB->getNumber()] -= 2;
1628 AdjustBBOffsetsAfter(MBB, -2);
1629 ++NumT2BrShrunk;
1630 MadeChange = true;
1631 }
1632 }
1633
1634 Opcode = Br.MI->getOpcode();
1635 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001636 continue;
1637
Evan Chengde17fb62009-10-31 23:46:45 +00001638 NewOpc = 0;
1639 unsigned PredReg = 0;
1640 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1641 if (Pred == ARMCC::EQ)
1642 NewOpc = ARM::tCBZ;
1643 else if (Pred == ARMCC::NE)
1644 NewOpc = ARM::tCBNZ;
1645 if (!NewOpc)
1646 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001647 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001648 // Check if the distance is within 126. Subtract starting offset by 2
1649 // because the cmp will be eliminated.
1650 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1651 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1652 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng0539c152011-04-01 22:09:28 +00001653 MachineBasicBlock::iterator CmpMI = Br.MI;
1654 if (CmpMI != Br.MI->getParent()->begin()) {
1655 --CmpMI;
1656 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1657 unsigned Reg = CmpMI->getOperand(0).getReg();
1658 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1659 if (Pred == ARMCC::AL &&
1660 CmpMI->getOperand(1).getImm() == 0 &&
1661 isARMLowRegister(Reg)) {
1662 MachineBasicBlock *MBB = Br.MI->getParent();
1663 MachineInstr *NewBR =
1664 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1665 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1666 CmpMI->eraseFromParent();
1667 Br.MI->eraseFromParent();
1668 Br.MI = NewBR;
1669 BBSizes[MBB->getNumber()] -= 2;
1670 AdjustBBOffsetsAfter(MBB, -2);
1671 ++NumCBZ;
1672 MadeChange = true;
1673 }
Evan Chengde17fb62009-10-31 23:46:45 +00001674 }
1675 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001676 }
1677 }
1678
1679 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001680}
1681
Evan Chenga1efbbd2009-08-14 00:32:16 +00001682/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1683/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001684bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1685 bool MadeChange = false;
1686
1687 // FIXME: After the tables are shrunk, can we get rid some of the
1688 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001689 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001690 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001691
Evan Cheng5657c012009-07-29 02:18:14 +00001692 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1693 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1694 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001695 const MCInstrDesc &MCID = MI->getDesc();
1696 unsigned NumOps = MCID.getNumOperands();
1697 unsigned JTOpIdx = NumOps - (MCID.isPredicable() ? 3 : 2);
Evan Cheng5657c012009-07-29 02:18:14 +00001698 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1699 unsigned JTI = JTOP.getIndex();
1700 assert(JTI < JT.size());
1701
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001702 bool ByteOk = true;
1703 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001704 unsigned JTOffset = GetOffsetOf(MI) + 4;
1705 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001706 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1707 MachineBasicBlock *MBB = JTBBs[j];
1708 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001709 // Negative offset is not ok. FIXME: We should change BB layout to make
1710 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001711 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001712 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001713 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001714 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001715 HalfWordOk = false;
1716 if (!ByteOk && !HalfWordOk)
1717 break;
1718 }
1719
1720 if (ByteOk || HalfWordOk) {
1721 MachineBasicBlock *MBB = MI->getParent();
1722 unsigned BaseReg = MI->getOperand(0).getReg();
1723 bool BaseRegKill = MI->getOperand(0).isKill();
1724 if (!BaseRegKill)
1725 continue;
1726 unsigned IdxReg = MI->getOperand(1).getReg();
1727 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001728
1729 // Scan backwards to find the instruction that defines the base
1730 // register. Due to post-RA scheduling, we can't count on it
1731 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001732 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001733 MachineBasicBlock::iterator B = MBB->begin();
1734 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1735 --PrevI;
1736
1737 // If for some reason we didn't find it, we can't do anything, so
1738 // just skip this one.
1739 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001740 continue;
1741
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001742 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001743 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001744 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001745 // Make sure it only defines the base register and kills any uses
1746 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001747 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1748 const MachineOperand &MO = AddrMI->getOperand(k);
1749 if (!MO.isReg() || !MO.getReg())
1750 continue;
1751 if (MO.isDef() && MO.getReg() != BaseReg) {
1752 OptOk = false;
1753 break;
1754 }
1755 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1756 OptOk = false;
1757 break;
1758 }
1759 }
1760 if (!OptOk)
1761 continue;
1762
Owen Anderson6b8719f2010-12-13 22:51:08 +00001763 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001764 // that gave us the initial base register definition.
1765 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1766 ;
1767
Owen Anderson6b8719f2010-12-13 22:51:08 +00001768 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001769 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001770 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001771 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001772 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001773 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001774 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001775
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001776 if (!OptOk)
1777 continue;
1778
Jim Grosbachd092a872010-11-29 21:28:32 +00001779 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001780 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1781 .addReg(IdxReg, getKillRegState(IdxRegKill))
1782 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1783 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1784 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1785 // is 2-byte aligned. For now, asm printer will fix it up.
1786 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1787 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1788 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1789 OrigSize += TII->GetInstSizeInBytes(MI);
1790
1791 AddrMI->eraseFromParent();
1792 LeaMI->eraseFromParent();
1793 MI->eraseFromParent();
1794
1795 int delta = OrigSize - NewSize;
1796 BBSizes[MBB->getNumber()] -= delta;
1797 AdjustBBOffsetsAfter(MBB, -delta);
1798
1799 ++NumTBs;
1800 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001801 }
1802 }
1803
1804 return MadeChange;
1805}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001806
Jim Grosbach9249efe2009-11-16 18:55:47 +00001807/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1808/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach80697d12009-11-12 17:25:07 +00001809bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1810 bool MadeChange = false;
1811
1812 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001813 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001814
Jim Grosbach80697d12009-11-12 17:25:07 +00001815 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1816 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1817 MachineInstr *MI = T2JumpTables[i];
Evan Chenge837dea2011-06-28 19:10:37 +00001818 const MCInstrDesc &MCID = MI->getDesc();
1819 unsigned NumOps = MCID.getNumOperands();
1820 unsigned JTOpIdx = NumOps - (MCID.isPredicable() ? 3 : 2);
Jim Grosbach80697d12009-11-12 17:25:07 +00001821 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1822 unsigned JTI = JTOP.getIndex();
1823 assert(JTI < JT.size());
1824
1825 // We prefer if target blocks for the jump table come after the jump
1826 // instruction so we can use TB[BH]. Loop through the target blocks
1827 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001828 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001829 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1830 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1831 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001832 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001833
Jim Grosbach08cbda52009-11-16 18:58:52 +00001834 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001835 // The destination precedes the switch. Try to move the block forward
1836 // so we have a positive offset.
1837 MachineBasicBlock *NewBB =
1838 AdjustJTTargetBlockForward(MBB, MI->getParent());
1839 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001840 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001841 MadeChange = true;
1842 }
1843 }
1844 }
1845
1846 return MadeChange;
1847}
1848
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001849MachineBasicBlock *ARMConstantIslands::
1850AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1851{
1852 MachineFunction &MF = *BB->getParent();
1853
Jim Grosbach03e2d442010-07-07 22:53:35 +00001854 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001855 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001856 // table that branches back to the actual target. This is a very simple
1857 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001858 MachineBasicBlock *TBB = 0, *FBB = 0;
1859 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001860 SmallVector<MachineOperand, 4> CondPrior;
1861 MachineFunction::iterator BBi = BB;
1862 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001863
Jim Grosbachca215e72009-11-16 17:10:56 +00001864 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001865 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001866
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001867 // If the block ends in an unconditional branch, move it. The prior block
1868 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001869 // and make sure we're not trying to move the entry block of the function.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001870 if (!B && Cond.empty() && BB != MF.begin() &&
1871 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001872 BB->moveAfter(JTBB);
1873 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001874 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001875 // Update numbering to account for the block being moved.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001876 MF.RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001877 ++NumJTMoved;
1878 return NULL;
1879 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001880
1881 // Create a new MBB for the code after the jump BB.
1882 MachineBasicBlock *NewBB =
1883 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1884 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1885 MF.insert(MBBI, NewBB);
1886
1887 // Add an unconditional branch from NewBB to BB.
1888 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1889 // correspond directly to anything in the source.
1890 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001891 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001892
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001893 // Update internal data structures to account for the newly inserted MBB.
1894 MF.RenumberBlocks(NewBB);
1895
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001896 // Update the CFG.
1897 NewBB->addSuccessor(BB);
1898 JTBB->removeSuccessor(BB);
1899 JTBB->addSuccessor(NewBB);
1900
Jim Grosbach80697d12009-11-12 17:25:07 +00001901 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001902 return NewBB;
1903}