blob: 13d8b74014c5989d930d19173153239f080e48f4 [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
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"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.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
Evan Chenga8e29892007-01-19 07:51:42 +0000168 const TargetInstrInfo *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;
Dan Gohmanae73dc12008-09-04 17:05:41 +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
Evan Cheng5657c012009-07-29 02:18:14 +0000275 TII = MF.getTarget().getInstrInfo();
276 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 Chengf1bbb952008-11-08 00:51:41 +0000319 AFI->initConstPoolEntryUId(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();
Bob Wilson84945262009-05-12 17:09:30 +0000326
Evan Chenged884f32007-04-03 23:39:48 +0000327 /// Remove dead constant pool entries.
328 RemoveUnusedCPEntries();
329
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000330 // Iteratively place constant pool entries and fix up branches until there
331 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000332 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000333 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000334 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000335 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000336 CPChange |= HandleConstantPoolUser(MF, i);
337 if (CPChange && ++NoCPIters > 30)
338 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000339 DEBUG(dumpBBs());
Bob Wilsonb9239532009-10-15 20:49:47 +0000340
341 // Clear NewWaterList now. If we split a block for branches, it should
342 // appear as "new water" for the next iteration of constant pool placement.
343 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000344
345 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000346 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000347 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
348 if (BRChange && ++NoBRIters > 30)
349 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000350 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000351
352 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000353 break;
354 MadeChange = true;
355 }
Evan Chenged884f32007-04-03 23:39:48 +0000356
Evan Chenga1efbbd2009-08-14 00:32:16 +0000357 // Shrink 32-bit Thumb2 branch, load, and store instructions.
358 if (isThumb2)
359 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000360
Dale Johannesen8593e412007-04-29 19:19:30 +0000361 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000362 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000363
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000364 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
365 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000366 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000367 MadeChange |= UndoLRSpillRestore();
368
Evan Chenga8e29892007-01-19 07:51:42 +0000369 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000370 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000371 WaterList.clear();
372 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000373 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000374 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000375 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000376 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000377
378 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000379}
380
381/// DoInitialPlacement - Perform the initial placement of the constant pool
382/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000383void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000384 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000385 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000386 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
387 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000388
Evan Chenga8e29892007-01-19 07:51:42 +0000389 // Add all of the constants from the constant pool to the end block, use an
390 // identity mapping of CPI's to CPE's.
391 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000392 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000393
Evan Cheng5657c012009-07-29 02:18:14 +0000394 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000395 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000396 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000397 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
398 // we would have to pad them out or something so that instructions stay
399 // aligned.
400 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
401 MachineInstr *CPEMI =
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000402 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
403 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000404 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000405
406 // Add a new CPEntry, but no corresponding CPUser yet.
407 std::vector<CPEntry> CPEs;
408 CPEs.push_back(CPEntry(CPEMI, i));
409 CPEntries.push_back(CPEs);
410 NumCPEs++;
Chris Lattner893e1c92009-08-23 06:49:22 +0000411 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
412 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000413 }
414}
415
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000416/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000417/// into the block immediately after it.
418static bool BBHasFallthrough(MachineBasicBlock *MBB) {
419 // Get the next machine basic block in the function.
420 MachineFunction::iterator MBBI = MBB;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000421 if (llvm::next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
Evan Chenga8e29892007-01-19 07:51:42 +0000422 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000423
Chris Lattner7896c9f2009-12-03 00:50:42 +0000424 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000425 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
426 E = MBB->succ_end(); I != E; ++I)
427 if (*I == NextBB)
428 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000429
Evan Chenga8e29892007-01-19 07:51:42 +0000430 return false;
431}
432
Evan Chengc99ef082007-02-09 20:54:44 +0000433/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
434/// look up the corresponding CPEntry.
435ARMConstantIslands::CPEntry
436*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
437 const MachineInstr *CPEMI) {
438 std::vector<CPEntry> &CPEs = CPEntries[CPI];
439 // Number of entries per constpool index should be small, just do a
440 // linear search.
441 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
442 if (CPEs[i].CPEMI == CPEMI)
443 return &CPEs[i];
444 }
445 return NULL;
446}
447
Jim Grosbach80697d12009-11-12 17:25:07 +0000448/// JumpTableFunctionScan - Do a scan of the function, building up
449/// information about the sizes of each block and the locations of all
450/// the jump tables.
451void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
Jim Grosbach80697d12009-11-12 17:25:07 +0000452 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
453 MBBI != E; ++MBBI) {
454 MachineBasicBlock &MBB = *MBBI;
455
Jim Grosbach80697d12009-11-12 17:25:07 +0000456 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000457 I != E; ++I)
458 if (I->getDesc().isBranch() && I->getOpcode() == ARM::t2BR_JT)
459 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000460 }
461}
462
Evan Chenga8e29892007-01-19 07:51:42 +0000463/// InitialFunctionScan - Do the initial scan of the function, building up
464/// information about the sizes of each block, the location of all the water,
465/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000466void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000467 const std::vector<MachineInstr*> &CPEMIs) {
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000468 // First thing, see if the function has any inline assembly in it. If so,
469 // we have to be conservative about alignment assumptions, as we don't
470 // know for sure the size of any instructions in the inline assembly.
471 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
472 MBBI != E; ++MBBI) {
473 MachineBasicBlock &MBB = *MBBI;
474 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
475 I != E; ++I)
476 if (I->getOpcode() == ARM::INLINEASM)
477 HasInlineAsm = true;
478 }
479
480 // Now go back through the instructions and build up our data structures
Dale Johannesen99c49a42007-02-25 00:47:03 +0000481 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000482 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000483 MBBI != E; ++MBBI) {
484 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000485
Evan Chenga8e29892007-01-19 07:51:42 +0000486 // If this block doesn't fall through into the next MBB, then this is
487 // 'water' that a constant pool island could be placed.
488 if (!BBHasFallthrough(&MBB))
489 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000490
Evan Chenga8e29892007-01-19 07:51:42 +0000491 unsigned MBBSize = 0;
492 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
493 I != E; ++I) {
494 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000495 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000496
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000497 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000498 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000499 bool isCond = false;
500 unsigned Bits = 0;
501 unsigned Scale = 1;
502 int UOpc = Opc;
503 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000504 default:
505 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000506 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000507 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000508 // be right, functions containing these must be 4-byte aligned.
Chris Lattner7d7dab02010-01-27 23:37:36 +0000509 MF.EnsureAlignment(2U);
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000510 if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
Evan Cheng5657c012009-07-29 02:18:14 +0000511 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000512 MBBSize += 2; // padding
513 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000514 case ARM::t2BR_JT:
515 T2JumpTables.push_back(I);
516 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000517 case ARM::Bcc:
518 isCond = true;
519 UOpc = ARM::B;
520 // Fallthrough
521 case ARM::B:
522 Bits = 24;
523 Scale = 4;
524 break;
525 case ARM::tBcc:
526 isCond = true;
527 UOpc = ARM::tB;
528 Bits = 8;
529 Scale = 2;
530 break;
531 case ARM::tB:
532 Bits = 11;
533 Scale = 2;
534 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000535 case ARM::t2Bcc:
536 isCond = true;
537 UOpc = ARM::t2B;
538 Bits = 20;
539 Scale = 2;
540 break;
541 case ARM::t2B:
542 Bits = 24;
543 Scale = 2;
544 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000545 }
Evan Chengb43216e2007-02-01 10:16:15 +0000546
547 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000548 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000549 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000550 }
551
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000552 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
553 PushPopMIs.push_back(I);
554
Evan Chengd3d9d662009-07-23 18:27:47 +0000555 if (Opc == ARM::CONSTPOOL_ENTRY)
556 continue;
557
Evan Chenga8e29892007-01-19 07:51:42 +0000558 // Scan the instructions for constant pool operands.
559 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000560 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000561 // We found one. The addressing mode tells us the max displacement
562 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000563
Evan Chenga8e29892007-01-19 07:51:42 +0000564 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000565 unsigned Bits = 0;
566 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000567 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000568 bool IsSoImm = false;
569
570 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000571 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000572 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000573 break;
574
575 // Taking the address of a CP entry.
576 case ARM::LEApcrel:
577 // This takes a SoImm, which is 8 bit immediate rotated. We'll
578 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000579 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000580 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000581 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000582 Scale = 4;
583 NegOk = true;
584 IsSoImm = true;
585 break;
586 case ARM::t2LEApcrel:
587 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000588 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000589 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000590 case ARM::tLEApcrel:
591 Bits = 8;
592 Scale = 4;
593 break;
594
595 case ARM::LDR:
596 case ARM::LDRcp:
597 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000598 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000599 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000600 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000601
602 case ARM::tLDRpci:
603 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000604 Bits = 8;
605 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000606 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000607
Jim Grosbache5165492009-11-09 00:11:35 +0000608 case ARM::VLDRD:
609 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000610 Bits = 8;
611 Scale = 4; // +-(offset_8*4)
612 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000613 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000614 }
Evan Chengb43216e2007-02-01 10:16:15 +0000615
Evan Chenga8e29892007-01-19 07:51:42 +0000616 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000617 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000618 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000619 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000620 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000621
622 // Increment corresponding CPEntry reference count.
623 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
624 assert(CPE && "Cannot find a corresponding CPEntry!");
625 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000626
Evan Chenga8e29892007-01-19 07:51:42 +0000627 // Instructions can only use one CP entry, don't bother scanning the
628 // rest of the operands.
629 break;
630 }
631 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000632
Dale Johannesen8593e412007-04-29 19:19:30 +0000633 // In thumb mode, if this block is a constpool island, we may need padding
634 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000635 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000636 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000637 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000638 ((Offset%4) != 0 || HasInlineAsm))
Evan Cheng2021abe2007-02-01 01:09:47 +0000639 MBBSize += 2;
640
Evan Chenga8e29892007-01-19 07:51:42 +0000641 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000642 BBOffsets.push_back(Offset);
643 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000644 }
645}
646
Evan Chenga8e29892007-01-19 07:51:42 +0000647/// GetOffsetOf - Return the current offset of the specified machine instruction
648/// from the start of the function. This offset changes as stuff is moved
649/// around inside the function.
650unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
651 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000652
Evan Chenga8e29892007-01-19 07:51:42 +0000653 // The offset is composed of two things: the sum of the sizes of all MBB's
654 // before this instruction's block, and the offset from the start of the block
655 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000656 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000657
Dale Johannesen8593e412007-04-29 19:19:30 +0000658 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
659 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000660 if (isThumb &&
661 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000662 (Offset%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +0000663 Offset += 2;
664
Evan Chenga8e29892007-01-19 07:51:42 +0000665 // Sum instructions before MI in MBB.
666 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
667 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
668 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000669 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000670 }
671}
672
673/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
674/// ID.
675static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
676 const MachineBasicBlock *RHS) {
677 return LHS->getNumber() < RHS->getNumber();
678}
679
680/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
681/// machine function, it upsets all of the block numbers. Renumber the blocks
682/// and update the arrays that parallel this numbering.
683void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
684 // Renumber the MBB's to keep them consequtive.
685 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000686
Evan Chenga8e29892007-01-19 07:51:42 +0000687 // Insert a size into BBSizes to align it properly with the (newly
688 // renumbered) block numbers.
689 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000690
691 // Likewise for BBOffsets.
692 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000693
694 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000695 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000696 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000697 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
698 CompareMBBNumbers);
699 WaterList.insert(IP, NewBB);
700}
701
702
703/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000704/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000705/// account for this change and returns the newly created block.
706MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000707 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000708 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000709
710 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000711 MachineBasicBlock *NewBB =
712 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000713 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000714 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000715
Evan Chenga8e29892007-01-19 07:51:42 +0000716 // Splice the instructions starting with MI over to NewBB.
717 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000718
Evan Chenga8e29892007-01-19 07:51:42 +0000719 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000720 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000721 // There doesn't seem to be meaningful DebugInfo available; this doesn't
722 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000723 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000724 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000725 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000726
Evan Chenga8e29892007-01-19 07:51:42 +0000727 // Update the CFG. All succs of OrigBB are now succs of NewBB.
728 while (!OrigBB->succ_empty()) {
729 MachineBasicBlock *Succ = *OrigBB->succ_begin();
730 OrigBB->removeSuccessor(Succ);
731 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000732
Evan Chenga8e29892007-01-19 07:51:42 +0000733 // This pass should be run after register allocation, so there should be no
734 // PHI nodes to update.
Chris Lattner518bb532010-02-09 19:54:29 +0000735 assert((Succ->empty() || !Succ->begin()->isPHI())
Evan Chenga8e29892007-01-19 07:51:42 +0000736 && "PHI nodes should be eliminated by now!");
737 }
Bob Wilson84945262009-05-12 17:09:30 +0000738
Evan Chenga8e29892007-01-19 07:51:42 +0000739 // OrigBB branches to NewBB.
740 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000741
Evan Chenga8e29892007-01-19 07:51:42 +0000742 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000743 // This is almost the same as UpdateForInsertedWaterBlock, except that
744 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000745 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000746
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000747 // Insert a size into BBSizes to align it properly with the (newly
748 // renumbered) block numbers.
749 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000750
Dale Johannesen99c49a42007-02-25 00:47:03 +0000751 // Likewise for BBOffsets.
752 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
753
Bob Wilson84945262009-05-12 17:09:30 +0000754 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000755 // available water after it (but not if it's already there, which happens
756 // when splitting before a conditional branch that is followed by an
757 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000758 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000759 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
760 CompareMBBNumbers);
761 MachineBasicBlock* WaterBB = *IP;
762 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000763 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000764 else
765 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000766 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000767
Dale Johannesen8593e412007-04-29 19:19:30 +0000768 // Figure out how large the first NewMBB is. (It cannot
769 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000770 unsigned NewBBSize = 0;
771 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
772 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000773 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000774
Dale Johannesen99c49a42007-02-25 00:47:03 +0000775 unsigned OrigBBI = OrigBB->getNumber();
776 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000777 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000778 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000779
Evan Chenga8e29892007-01-19 07:51:42 +0000780 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000781 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000782 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000783 BBSizes[OrigBBI] -= NewBBSize - delta;
784
785 // ...and adjust BBOffsets for NewBB accordingly.
786 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
787
788 // All BBOffsets following these blocks must be modified.
789 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000790
791 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000792}
793
Dale Johannesen8593e412007-04-29 19:19:30 +0000794/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000795/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000796/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000797bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000798 unsigned TrialOffset, unsigned MaxDisp,
799 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000800 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
801 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000802 // Effectively, the valid range of displacements is 2 bytes smaller for such
803 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000804 unsigned TotalAdj = 0;
805 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000806 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000807 TotalAdj = 2;
808 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000809 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000810 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000811 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000812 TotalAdj += 2;
813 }
814
815 // In Thumb2 mode, later branch adjustments can shift instructions up and
816 // cause alignment change. In the worst case scenario this can cause the
817 // user's effective address to be subtracted by 2 and the CPE's address to
818 // be plus 2.
819 if (isThumb2 && TotalAdj != 4)
820 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000821
Dale Johannesen99c49a42007-02-25 00:47:03 +0000822 if (UserOffset <= TrialOffset) {
823 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000824 if (TrialOffset - UserOffset <= MaxDisp)
825 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000826 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000827 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000828 if (UserOffset - TrialOffset <= MaxDisp)
829 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000830 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000831 }
832 return false;
833}
834
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000835/// WaterIsInRange - Returns true if a CPE placed after the specified
836/// Water (a basic block) will be in range for the specific MI.
837
838bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000839 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000840 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000841 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000842 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000843
Dale Johannesend959aa42007-04-02 20:31:06 +0000844 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000845 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000846 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000847 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000848
Evan Chengd3d9d662009-07-23 18:27:47 +0000849 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000850}
851
852/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000853/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000854bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000855 MachineInstr *CPEMI, unsigned MaxDisp,
856 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000857 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000858 assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000859
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000860 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000861 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
862 << " max delta=" << MaxDisp
863 << " insn address=" << UserOffset
864 << " CPE address=" << CPEOffset
865 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000866 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000867
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000868 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000869}
870
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000871#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000872/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
873/// unconditionally branches to its only successor.
874static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
875 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
876 return false;
877
878 MachineBasicBlock *Succ = *MBB->succ_begin();
879 MachineBasicBlock *Pred = *MBB->pred_begin();
880 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000881 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
882 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000883 return PredMI->getOperand(0).getMBB() == Succ;
884 return false;
885}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000886#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000887
Bob Wilson84945262009-05-12 17:09:30 +0000888void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000889 int delta) {
Chris Lattner7896c9f2009-12-03 00:50:42 +0000890 MachineFunction::iterator MBBI = BB; MBBI = llvm::next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000891 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
892 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000893 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000894 // If some existing blocks have padding, adjust the padding as needed, a
895 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000896 if (!isThumb)
897 continue;
898 MachineBasicBlock *MBB = MBBI;
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000899 if (!MBB->empty() && !HasInlineAsm) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000900 // Constant pool entries require padding.
901 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000902 unsigned OldOffset = BBOffsets[i] - delta;
903 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000904 // add new padding
905 BBSizes[i] += 2;
906 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000907 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000908 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000909 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000910 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000911 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000912 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000913 // Thumb1 jump tables require padding. They should be at the end;
914 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000915 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000916 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000917 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
918 unsigned OldMIOffset = NewMIOffset - delta;
919 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000920 // remove existing padding
921 BBSizes[i] -= 2;
922 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000923 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000924 // add new padding
925 BBSizes[i] += 2;
926 delta += 2;
927 }
928 }
929 if (delta==0)
930 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000931 }
Chris Lattner7896c9f2009-12-03 00:50:42 +0000932 MBBI = llvm::next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000933 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000934}
935
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000936/// DecrementOldEntry - find the constant pool entry with index CPI
937/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000938/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000939/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000940
Evan Chenged884f32007-04-03 23:39:48 +0000941bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000942 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000943 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
944 assert(CPE && "Unexpected!");
945 if (--CPE->RefCount == 0) {
946 RemoveDeadCPEMI(CPEMI);
947 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000948 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000949 return true;
950 }
951 return false;
952}
953
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000954/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
955/// if not, see if an in-range clone of the CPE is in range, and if so,
956/// change the data structures so the user references the clone. Returns:
957/// 0 = no existing entry found
958/// 1 = entry found, and there were no code insertions or deletions
959/// 2 = entry found, and there were code insertions or deletions
960int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
961{
962 MachineInstr *UserMI = U.MI;
963 MachineInstr *CPEMI = U.CPEMI;
964
965 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000966 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000967 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000968 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000969 }
970
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000971 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000972 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000973 std::vector<CPEntry> &CPEs = CPEntries[CPI];
974 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
975 // We already tried this one
976 if (CPEs[i].CPEMI == CPEMI)
977 continue;
978 // Removing CPEs can leave empty entries, skip
979 if (CPEs[i].CPEMI == NULL)
980 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000981 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000982 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
983 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000984 // Point the CPUser node to the replacement
985 U.CPEMI = CPEs[i].CPEMI;
986 // Change the CPI in the instruction operand to refer to the clone.
987 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000988 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000989 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000990 break;
991 }
992 // Adjust the refcount of the clone...
993 CPEs[i].RefCount++;
994 // ...and the original. If we didn't remove the old entry, none of the
995 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000996 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000997 }
998 }
999 return 0;
1000}
1001
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001002/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1003/// the specific unconditional branch instruction.
1004static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001005 switch (Opc) {
1006 case ARM::tB:
1007 return ((1<<10)-1)*2;
1008 case ARM::t2B:
1009 return ((1<<23)-1)*2;
1010 default:
1011 break;
1012 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001013
David Goodwin5e47a9a2009-06-30 18:04:13 +00001014 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001015}
1016
Bob Wilsonb9239532009-10-15 20:49:47 +00001017/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001018/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001019/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001020/// is set to the WaterList entry. For Thumb, prefer water that will not
1021/// introduce padding to water that will. To ensure that this pass
1022/// terminates, the CPE location for a particular CPUser is only allowed to
1023/// move to a lower address, so search backward from the end of the list and
1024/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001025bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001026 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001027 if (WaterList.empty())
1028 return false;
1029
Bob Wilson32c50e82009-10-12 20:45:53 +00001030 bool FoundWaterThatWouldPad = false;
1031 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001032 for (water_iterator IP = prior(WaterList.end()),
1033 B = WaterList.begin();; --IP) {
1034 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001035 // Check if water is in range and is either at a lower address than the
1036 // current "high water mark" or a new water block that was created since
1037 // the previous iteration by inserting an unconditional branch. In the
1038 // latter case, we want to allow resetting the high water mark back to
1039 // this new water since we haven't seen it before. Inserting branches
1040 // should be relatively uncommon and when it does happen, we want to be
1041 // sure to take advantage of it for all the CPEs near that block, so that
1042 // we don't insert more branches than necessary.
1043 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1044 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1045 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001046 unsigned WBBId = WaterBB->getNumber();
1047 if (isThumb &&
1048 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
1049 // This is valid Water, but would introduce padding. Remember
1050 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001051 if (!FoundWaterThatWouldPad) {
1052 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001053 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001054 }
Bob Wilson3b757352009-10-12 19:04:03 +00001055 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001056 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001057 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001058 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001059 }
Bob Wilson3b757352009-10-12 19:04:03 +00001060 if (IP == B)
1061 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001062 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001063 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001064 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001065 return true;
1066 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001067 return false;
1068}
1069
Bob Wilson84945262009-05-12 17:09:30 +00001070/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001071/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1072/// block is used if in range, and the conditional branch munged so control
1073/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001074/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001075/// block following which the new island can be inserted (the WaterList
1076/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001077void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001078 unsigned UserOffset,
1079 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001080 CPUser &U = CPUsers[CPUserIndex];
1081 MachineInstr *UserMI = U.MI;
1082 MachineInstr *CPEMI = U.CPEMI;
1083 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001084 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001085 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001086 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001087
Bob Wilson36fa5322009-10-15 05:10:36 +00001088 // If the block does not end in an unconditional branch already, and if the
1089 // end of the block is within range, make new water there. (The addition
1090 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1091 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001092 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001093 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001094 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1095 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001096 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001097 if (&UserMBB->back() == UserMI)
1098 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001099 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001100 // Add an unconditional branch from UserMBB to fallthrough block.
1101 // Record it for branch lengthening; this new branch will not get out of
1102 // range, but if the preceding conditional branch is out of range, the
1103 // targets will be exchanged, and the altered branch may be out of
1104 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001105 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001106 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001107 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001108 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001109 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001110 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001111 BBSizes[UserMBB->getNumber()] += delta;
1112 AdjustBBOffsetsAfter(UserMBB, delta);
1113 } else {
1114 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001115 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001116 // and constant pool entries are 4 bytes: if instruction I references
1117 // island CPE, and instruction I+1 references CPE', it will
1118 // not work well to put CPE as far forward as possible, since then
1119 // CPE' cannot immediately follow it (that location is 2 bytes
1120 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001121 // a new island. So, we make a first guess, then walk through the
1122 // instructions between the one currently being looked at and the
1123 // possible insertion point, and make sure any other instructions
1124 // that reference CPEs will be able to use the same island area;
1125 // if not, we back up the insertion point.
1126
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001127 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001128 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001129 // island is handled inside OffsetIsInRange.
1130 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001131 // This could point off the end of the block if we've already got
1132 // constant pool entries following this block; only the last one is
1133 // in the water list. Back past any possible branches (allow for a
1134 // conditional and a maximally long unconditional).
1135 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001136 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001137 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001138 unsigned EndInsertOffset = BaseInsertOffset +
1139 CPEMI->getOperand(2).getImm();
1140 MachineBasicBlock::iterator MI = UserMI;
1141 ++MI;
1142 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001143 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001144 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001145 Offset += TII->GetInstSizeInBytes(MI),
Chris Lattner7896c9f2009-12-03 00:50:42 +00001146 MI = llvm::next(MI)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001147 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001148 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001149 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001150 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1151 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1152 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001153 }
1154 // This is overly conservative, as we don't account for CPEMIs
1155 // being reused within the block, but it doesn't matter much.
1156 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1157 CPUIndex++;
1158 }
1159 }
Chris Lattner893e1c92009-08-23 06:49:22 +00001160 DEBUG(errs() << "Split in middle of big block\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001161 NewMBB = SplitBlockBeforeInstr(prior(MI));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001162 }
1163}
1164
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001165/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001166/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001167/// place in-range. Return true if we changed any addresses (thus must run
1168/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001169bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001170 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001171 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001172 MachineInstr *UserMI = U.MI;
1173 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001174 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001175 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001176 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001177 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001178 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001179
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001180 // See if the current entry is within range, or there is a clone of it
1181 // in range.
1182 int result = LookForExistingCPEntry(U, UserOffset);
1183 if (result==1) return false;
1184 else if (result==2) return true;
1185
1186 // No existing clone of this CPE is within range.
1187 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001188 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001189
Bob Wilsonf98032e2009-10-12 21:23:15 +00001190 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001191 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1192 MachineBasicBlock *NewMBB;
1193 water_iterator IP;
1194 if (LookForWater(U, UserOffset, IP)) {
1195 DEBUG(errs() << "found water in range\n");
1196 MachineBasicBlock *WaterBB = *IP;
1197
1198 // If the original WaterList entry was "new water" on this iteration,
1199 // propagate that to the new island. This is just keeping NewWaterList
1200 // updated to match the WaterList, which will be updated below.
1201 if (NewWaterList.count(WaterBB)) {
1202 NewWaterList.erase(WaterBB);
1203 NewWaterList.insert(NewIsland);
1204 }
1205 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001206 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001207
1208 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001209 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001210 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001211 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001212
1213 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1214 // called while handling branches so that the water will be seen on the
1215 // next iteration for constant pools, but in this context, we don't want
1216 // it. Check for this so it will be removed from the WaterList.
1217 // Also remove any entry from NewWaterList.
1218 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1219 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1220 if (IP != WaterList.end())
1221 NewWaterList.erase(WaterBB);
1222
1223 // We are adding new water. Update NewWaterList.
1224 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001225 }
1226
Bob Wilsonb9239532009-10-15 20:49:47 +00001227 // Remove the original WaterList entry; we want subsequent insertions in
1228 // this vicinity to go after the one we're about to insert. This
1229 // considerably reduces the number of times we have to move the same CPE
1230 // more than once and is also important to ensure the algorithm terminates.
1231 if (IP != WaterList.end())
1232 WaterList.erase(IP);
1233
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001234 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001235 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001236
1237 // Update internal data structures to account for the newly inserted MBB.
1238 UpdateForInsertedWaterBlock(NewIsland);
1239
1240 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001241 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001242
1243 // Now that we have an island to add the CPE to, clone the original CPE and
1244 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001245 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001246 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001247 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001248 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001249 NumCPEs++;
1250
Dale Johannesen8593e412007-04-29 19:19:30 +00001251 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001252 // Compensate for .align 2 in thumb mode.
Jim Grosbach4d8e90a2009-11-19 23:10:28 +00001253 if (isThumb && (BBOffsets[NewIsland->getNumber()]%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +00001254 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001255 // Increase the size of the island block to account for the new entry.
1256 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001257 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001258
Evan Chenga8e29892007-01-19 07:51:42 +00001259 // Finally, change the CPI in the instruction operand to be ID.
1260 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001261 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001262 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001263 break;
1264 }
Bob Wilson84945262009-05-12 17:09:30 +00001265
Chris Lattner705e07f2009-08-23 03:41:05 +00001266 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1267 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001268
Evan Chenga8e29892007-01-19 07:51:42 +00001269 return true;
1270}
1271
Evan Chenged884f32007-04-03 23:39:48 +00001272/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1273/// sizes and offsets of impacted basic blocks.
1274void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1275 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001276 unsigned Size = CPEMI->getOperand(2).getImm();
1277 CPEMI->eraseFromParent();
1278 BBSizes[CPEBB->getNumber()] -= Size;
1279 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001280 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001281 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001282 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001283 // empty, so fix this.
1284 // All succeeding offsets have the current size value added in, fix this.
1285 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001286 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001287 BBSizes[CPEBB->getNumber()] = 0;
1288 }
Evan Chenged884f32007-04-03 23:39:48 +00001289 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001290 AdjustBBOffsetsAfter(CPEBB, -Size);
1291 // An island has only one predecessor BB and one successor BB. Check if
1292 // this BB's predecessor jumps directly to this BB's successor. This
1293 // shouldn't happen currently.
1294 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1295 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001296}
1297
1298/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1299/// are zero.
1300bool ARMConstantIslands::RemoveUnusedCPEntries() {
1301 unsigned MadeChange = false;
1302 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1303 std::vector<CPEntry> &CPEs = CPEntries[i];
1304 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1305 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1306 RemoveDeadCPEMI(CPEs[j].CPEMI);
1307 CPEs[j].CPEMI = NULL;
1308 MadeChange = true;
1309 }
1310 }
Bob Wilson84945262009-05-12 17:09:30 +00001311 }
Evan Chenged884f32007-04-03 23:39:48 +00001312 return MadeChange;
1313}
1314
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001315/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001316/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001317bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1318 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001319 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001320 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001321 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001322
Chris Lattner705e07f2009-08-23 03:41:05 +00001323 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1324 << " from BB#" << MI->getParent()->getNumber()
1325 << " max delta=" << MaxDisp
1326 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1327 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001328
Dale Johannesen8593e412007-04-29 19:19:30 +00001329 if (BrOffset <= DestOffset) {
1330 // Branch before the Dest.
1331 if (DestOffset-BrOffset <= MaxDisp)
1332 return true;
1333 } else {
1334 if (BrOffset-DestOffset <= MaxDisp)
1335 return true;
1336 }
1337 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001338}
1339
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001340/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1341/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001342bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001343 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001344 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001345
Evan Chengc0dbec72007-01-31 19:57:44 +00001346 // Check to see if the DestBB is already in-range.
1347 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001348 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001349
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001350 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001351 return FixUpUnconditionalBr(MF, Br);
1352 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001353}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001354
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001355/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1356/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001357/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001358/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001359bool
Evan Cheng5657c012009-07-29 02:18:14 +00001360ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001361 MachineInstr *MI = Br.MI;
1362 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001363 if (!isThumb1)
1364 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001365
1366 // Use BL to implement far jump.
1367 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001368 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001369 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001370 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001371 HasFarJump = true;
1372 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001373
Chris Lattner705e07f2009-08-23 03:41:05 +00001374 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001375
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001376 return true;
1377}
1378
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001379/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001380/// far away to fit in its displacement field. It is converted to an inverse
1381/// conditional branch + an unconditional branch to the destination.
1382bool
Evan Cheng5657c012009-07-29 02:18:14 +00001383ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001384 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001385 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001386
Bob Wilson39bf0512009-05-12 17:35:29 +00001387 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001388 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001389 // blt L1
1390 // =>
1391 // bge L2
1392 // b L1
1393 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001394 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001395 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001396 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001397
1398 // If the branch is at the end of its MBB and that has a fall-through block,
1399 // direct the updated conditional branch to the fall-through block. Otherwise,
1400 // split the MBB before the next instruction.
1401 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001402 MachineInstr *BMI = &MBB->back();
1403 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001404
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001405 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001406 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001407 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001408 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001409 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001410 // condition and swap destinations:
1411 // beq L1
1412 // b L2
1413 // =>
1414 // bne L2
1415 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001416 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001417 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001418 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1419 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001420 BMI->getOperand(0).setMBB(DestBB);
1421 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001422 MI->getOperand(1).setImm(CC);
1423 return true;
1424 }
1425 }
1426 }
1427
1428 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001429 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001430 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001431 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001432 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001433 BBSizes[MBB->getNumber()] -= delta;
Chris Lattner7896c9f2009-12-03 00:50:42 +00001434 MachineBasicBlock* SplitBB = llvm::next(MachineFunction::iterator(MBB));
Dale Johannesen8593e412007-04-29 19:19:30 +00001435 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001436 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001437 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001438 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001439 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001440
Chris Lattner893e1c92009-08-23 06:49:22 +00001441 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1442 << " also invert condition and change dest. to BB#"
1443 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001444
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001445 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001446 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001447 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001448 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001449 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001450 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001451 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001452 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001453 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001454 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001455
1456 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001457 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001458 MI->eraseFromParent();
1459
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001460 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001461 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001462 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001463 return true;
1464}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001465
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001466/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001467/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1468/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001469bool ARMConstantIslands::UndoLRSpillRestore() {
1470 bool MadeChange = false;
1471 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1472 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001473 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001474 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001475 MI->getOperand(2).getReg() == ARM::PC &&
1476 MI->getNumExplicitOperands() == 3) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001477 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001478 MI->eraseFromParent();
1479 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001480 }
1481 }
1482 return MadeChange;
1483}
Evan Cheng5657c012009-07-29 02:18:14 +00001484
Evan Chenga1efbbd2009-08-14 00:32:16 +00001485bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1486 bool MadeChange = false;
1487
1488 // Shrink ADR and LDR from constantpool.
1489 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1490 CPUser &U = CPUsers[i];
1491 unsigned Opcode = U.MI->getOpcode();
1492 unsigned NewOpc = 0;
1493 unsigned Scale = 1;
1494 unsigned Bits = 0;
1495 switch (Opcode) {
1496 default: break;
1497 case ARM::t2LEApcrel:
1498 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1499 NewOpc = ARM::tLEApcrel;
1500 Bits = 8;
1501 Scale = 4;
1502 }
1503 break;
1504 case ARM::t2LDRpci:
1505 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1506 NewOpc = ARM::tLDRpci;
1507 Bits = 8;
1508 Scale = 4;
1509 }
1510 break;
1511 }
1512
1513 if (!NewOpc)
1514 continue;
1515
1516 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1517 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1518 // FIXME: Check if offset is multiple of scale if scale is not 4.
1519 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1520 U.MI->setDesc(TII->get(NewOpc));
1521 MachineBasicBlock *MBB = U.MI->getParent();
1522 BBSizes[MBB->getNumber()] -= 2;
1523 AdjustBBOffsetsAfter(MBB, -2);
1524 ++NumT2CPShrunk;
1525 MadeChange = true;
1526 }
1527 }
1528
Evan Chenga1efbbd2009-08-14 00:32:16 +00001529 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001530 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001531 return MadeChange;
1532}
1533
1534bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001535 bool MadeChange = false;
1536
1537 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1538 ImmBranch &Br = ImmBranches[i];
1539 unsigned Opcode = Br.MI->getOpcode();
1540 unsigned NewOpc = 0;
1541 unsigned Scale = 1;
1542 unsigned Bits = 0;
1543 switch (Opcode) {
1544 default: break;
1545 case ARM::t2B:
1546 NewOpc = ARM::tB;
1547 Bits = 11;
1548 Scale = 2;
1549 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001550 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001551 NewOpc = ARM::tBcc;
1552 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001553 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001554 break;
1555 }
Evan Chengde17fb62009-10-31 23:46:45 +00001556 }
1557 if (NewOpc) {
1558 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1559 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1560 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1561 Br.MI->setDesc(TII->get(NewOpc));
1562 MachineBasicBlock *MBB = Br.MI->getParent();
1563 BBSizes[MBB->getNumber()] -= 2;
1564 AdjustBBOffsetsAfter(MBB, -2);
1565 ++NumT2BrShrunk;
1566 MadeChange = true;
1567 }
1568 }
1569
1570 Opcode = Br.MI->getOpcode();
1571 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001572 continue;
1573
Evan Chengde17fb62009-10-31 23:46:45 +00001574 NewOpc = 0;
1575 unsigned PredReg = 0;
1576 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1577 if (Pred == ARMCC::EQ)
1578 NewOpc = ARM::tCBZ;
1579 else if (Pred == ARMCC::NE)
1580 NewOpc = ARM::tCBNZ;
1581 if (!NewOpc)
1582 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001583 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001584 // Check if the distance is within 126. Subtract starting offset by 2
1585 // because the cmp will be eliminated.
1586 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1587 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1588 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1589 MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
1590 if (CmpMI->getOpcode() == ARM::tCMPzi8) {
1591 unsigned Reg = CmpMI->getOperand(0).getReg();
1592 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1593 if (Pred == ARMCC::AL &&
1594 CmpMI->getOperand(1).getImm() == 0 &&
1595 isARMLowRegister(Reg)) {
1596 MachineBasicBlock *MBB = Br.MI->getParent();
1597 MachineInstr *NewBR =
1598 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1599 .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1600 CmpMI->eraseFromParent();
1601 Br.MI->eraseFromParent();
1602 Br.MI = NewBR;
1603 BBSizes[MBB->getNumber()] -= 2;
1604 AdjustBBOffsetsAfter(MBB, -2);
1605 ++NumCBZ;
1606 MadeChange = true;
1607 }
1608 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001609 }
1610 }
1611
1612 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001613}
1614
Evan Chenga1efbbd2009-08-14 00:32:16 +00001615/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1616/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001617bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1618 bool MadeChange = false;
1619
1620 // FIXME: After the tables are shrunk, can we get rid some of the
1621 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001622 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001623 if (MJTI == 0) return false;
1624
Evan Cheng5657c012009-07-29 02:18:14 +00001625 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1626 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1627 MachineInstr *MI = T2JumpTables[i];
1628 const TargetInstrDesc &TID = MI->getDesc();
1629 unsigned NumOps = TID.getNumOperands();
1630 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1631 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1632 unsigned JTI = JTOP.getIndex();
1633 assert(JTI < JT.size());
1634
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001635 bool ByteOk = true;
1636 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001637 unsigned JTOffset = GetOffsetOf(MI) + 4;
1638 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001639 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1640 MachineBasicBlock *MBB = JTBBs[j];
1641 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001642 // Negative offset is not ok. FIXME: We should change BB layout to make
1643 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001644 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001645 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001646 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001647 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001648 HalfWordOk = false;
1649 if (!ByteOk && !HalfWordOk)
1650 break;
1651 }
1652
1653 if (ByteOk || HalfWordOk) {
1654 MachineBasicBlock *MBB = MI->getParent();
1655 unsigned BaseReg = MI->getOperand(0).getReg();
1656 bool BaseRegKill = MI->getOperand(0).isKill();
1657 if (!BaseRegKill)
1658 continue;
1659 unsigned IdxReg = MI->getOperand(1).getReg();
1660 bool IdxRegKill = MI->getOperand(1).isKill();
1661 MachineBasicBlock::iterator PrevI = MI;
1662 if (PrevI == MBB->begin())
1663 continue;
1664
1665 MachineInstr *AddrMI = --PrevI;
1666 bool OptOk = true;
1667 // Examine the instruction that calculate the jumptable entry address.
1668 // If it's not the one just before the t2BR_JT, we won't delete it, then
1669 // it's not worth doing the optimization.
1670 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1671 const MachineOperand &MO = AddrMI->getOperand(k);
1672 if (!MO.isReg() || !MO.getReg())
1673 continue;
1674 if (MO.isDef() && MO.getReg() != BaseReg) {
1675 OptOk = false;
1676 break;
1677 }
1678 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1679 OptOk = false;
1680 break;
1681 }
1682 }
1683 if (!OptOk)
1684 continue;
1685
Evan Chenga1efbbd2009-08-14 00:32:16 +00001686 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1687 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001688 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001689 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1690 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001691 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001692 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001693
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001694 if (!OptOk)
1695 continue;
1696
1697 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1698 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1699 .addReg(IdxReg, getKillRegState(IdxRegKill))
1700 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1701 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1702 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1703 // is 2-byte aligned. For now, asm printer will fix it up.
1704 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1705 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1706 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1707 OrigSize += TII->GetInstSizeInBytes(MI);
1708
1709 AddrMI->eraseFromParent();
1710 LeaMI->eraseFromParent();
1711 MI->eraseFromParent();
1712
1713 int delta = OrigSize - NewSize;
1714 BBSizes[MBB->getNumber()] -= delta;
1715 AdjustBBOffsetsAfter(MBB, -delta);
1716
1717 ++NumTBs;
1718 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001719 }
1720 }
1721
1722 return MadeChange;
1723}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001724
Jim Grosbach9249efe2009-11-16 18:55:47 +00001725/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1726/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach80697d12009-11-12 17:25:07 +00001727bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1728 bool MadeChange = false;
1729
1730 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001731 if (MJTI == 0) return false;
1732
Jim Grosbach80697d12009-11-12 17:25:07 +00001733 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1734 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1735 MachineInstr *MI = T2JumpTables[i];
1736 const TargetInstrDesc &TID = MI->getDesc();
1737 unsigned NumOps = TID.getNumOperands();
1738 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1739 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1740 unsigned JTI = JTOP.getIndex();
1741 assert(JTI < JT.size());
1742
1743 // We prefer if target blocks for the jump table come after the jump
1744 // instruction so we can use TB[BH]. Loop through the target blocks
1745 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001746 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001747 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1748 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1749 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001750 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001751
Jim Grosbach08cbda52009-11-16 18:58:52 +00001752 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001753 // The destination precedes the switch. Try to move the block forward
1754 // so we have a positive offset.
1755 MachineBasicBlock *NewBB =
1756 AdjustJTTargetBlockForward(MBB, MI->getParent());
1757 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001758 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001759 MadeChange = true;
1760 }
1761 }
1762 }
1763
1764 return MadeChange;
1765}
1766
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001767MachineBasicBlock *ARMConstantIslands::
1768AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1769{
1770 MachineFunction &MF = *BB->getParent();
1771
Jim Grosbach08cbda52009-11-16 18:58:52 +00001772 // If it's the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001773 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001774 // table that branches back to the actual target. This is a very simple
1775 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001776 MachineBasicBlock *TBB = 0, *FBB = 0;
1777 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001778 SmallVector<MachineOperand, 4> CondPrior;
1779 MachineFunction::iterator BBi = BB;
1780 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001781
Jim Grosbachca215e72009-11-16 17:10:56 +00001782 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001783 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001784
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001785 // If the block ends in an unconditional branch, move it. The prior block
1786 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001787 // and make sure we're not trying to move the entry block of the function.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001788 if (!B && Cond.empty() && BB != MF.begin() &&
1789 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001790 BB->moveAfter(JTBB);
1791 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001792 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001793 // Update numbering to account for the block being moved.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001794 MF.RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001795 ++NumJTMoved;
1796 return NULL;
1797 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001798
1799 // Create a new MBB for the code after the jump BB.
1800 MachineBasicBlock *NewBB =
1801 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1802 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1803 MF.insert(MBBI, NewBB);
1804
1805 // Add an unconditional branch from NewBB to BB.
1806 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1807 // correspond directly to anything in the source.
1808 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001809 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001810
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001811 // Update internal data structures to account for the newly inserted MBB.
1812 MF.RenumberBlocks(NewBB);
1813
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001814 // Update the CFG.
1815 NewBB->addSuccessor(BB);
1816 JTBB->removeSuccessor(BB);
1817 JTBB->addSuccessor(NewBB);
1818
Jim Grosbach80697d12009-11-12 17:25:07 +00001819 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001820 return NewBB;
1821}