blob: aad5eb709239c9105a1c3a2f28291c8c3188fe0c [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"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Evan Chengc99ef082007-02-09 20:54:44 +000030#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000031#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/Statistic.h"
Evan Chenga8e29892007-01-19 07:51:42 +000033using namespace llvm;
34
Evan Chengc99ef082007-02-09 20:54:44 +000035STATISTIC(NumCPEs, "Number of constpool entries");
Evan Chengd1b2c1e2007-01-30 01:18:38 +000036STATISTIC(NumSplit, "Number of uncond branches inserted");
37STATISTIC(NumCBrFixed, "Number of cond branches fixed");
38STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
Evan Cheng5657c012009-07-29 02:18:14 +000039STATISTIC(NumTBs, "Number of table branches generated");
Evan Chenga8e29892007-01-19 07:51:42 +000040
41namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000042 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000043 /// requires constant pool entries to be scattered among the instructions
44 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000045 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000046 /// special instructions.
47 ///
48 /// The terminology used in this pass includes:
49 /// Islands - Clumps of constants placed in the function.
50 /// Water - Potential places where an island could be formed.
51 /// CPE - A constant pool entry that has been placed somewhere, which
52 /// tracks a list of users.
53 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000054 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000055 /// by MBB Number. The two-byte pads required for Thumb alignment are
56 /// counted as part of the following block (i.e., the offset and size for
57 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000058 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000059
Dale Johannesen99c49a42007-02-25 00:47:03 +000060 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000061 /// The two-byte pads required for Thumb alignment are counted as part of
62 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000063 std::vector<unsigned> BBOffsets;
64
Evan Chenga8e29892007-01-19 07:51:42 +000065 /// WaterList - A sorted list of basic blocks where islands could be placed
66 /// (i.e. blocks that don't fall through to the following block, due
67 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000068 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000069
Evan Chenga8e29892007-01-19 07:51:42 +000070 /// CPUser - One user of a constant pool, keeping the machine instruction
71 /// pointer, the constant pool being referenced, and the max displacement
72 /// allowed from the instruction to the CP.
73 struct CPUser {
74 MachineInstr *MI;
75 MachineInstr *CPEMI;
76 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +000077 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +000078 bool IsSoImm;
79 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
80 bool neg, bool soimm)
81 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {}
Evan Chenga8e29892007-01-19 07:51:42 +000082 };
Bob Wilson84945262009-05-12 17:09:30 +000083
Evan Chenga8e29892007-01-19 07:51:42 +000084 /// CPUsers - Keep track of all of the machine instructions that use various
85 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000086 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +000087
Evan Chengc99ef082007-02-09 20:54:44 +000088 /// CPEntry - One per constant pool entry, keeping the machine instruction
89 /// pointer, the constpool index, and the number of CPUser's which
90 /// reference this entry.
91 struct CPEntry {
92 MachineInstr *CPEMI;
93 unsigned CPI;
94 unsigned RefCount;
95 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
96 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
97 };
98
99 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000100 /// instructions. For each original constpool index (i.e. those that
101 /// existed upon entry to this pass), it keeps a vector of entries.
102 /// Original elements are cloned as we go along; the clones are
103 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000104 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000105
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000106 /// ImmBranch - One per immediate branch, keeping the machine instruction
107 /// pointer, conditional or unconditional, the max displacement,
108 /// and (if isCond is true) the corresponding unconditional branch
109 /// opcode.
110 struct ImmBranch {
111 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000112 unsigned MaxDisp : 31;
113 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000114 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000115 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
116 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000117 };
118
Evan Cheng2706f972007-05-16 05:14:06 +0000119 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000120 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000121 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000122
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000123 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
124 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000125 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000126
Evan Cheng5657c012009-07-29 02:18:14 +0000127 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
128 SmallVector<MachineInstr*, 4> T2JumpTables;
129
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000130 /// HasFarJump - True if any far jump instruction has been emitted during
131 /// the branch fix up pass.
132 bool HasFarJump;
133
Evan Chenga8e29892007-01-19 07:51:42 +0000134 const TargetInstrInfo *TII;
Dale Johannesen8593e412007-04-29 19:19:30 +0000135 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000136 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000137 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000138 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000139 public:
Devang Patel19974732007-05-03 01:11:54 +0000140 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000141 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000142
Evan Cheng5657c012009-07-29 02:18:14 +0000143 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000144
145 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000146 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000147 }
Bob Wilson84945262009-05-12 17:09:30 +0000148
Evan Chenga8e29892007-01-19 07:51:42 +0000149 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000150 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000151 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000152 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng5657c012009-07-29 02:18:14 +0000153 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000154 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000155 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000156 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000157 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000158 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000159 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilson84945262009-05-12 17:09:30 +0000160 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000161 MachineBasicBlock** NewMBB);
Bob Wilson84945262009-05-12 17:09:30 +0000162 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000163 std::vector<MachineBasicBlock*>::iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000164 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
165 MachineBasicBlock** NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000166 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000167 void RemoveDeadCPEMI(MachineInstr *CPEMI);
168 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000169 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000170 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
171 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000172 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000173 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000174 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000175 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000176 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000177 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
178 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
179 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000180 bool UndoLRSpillRestore();
Evan Cheng5657c012009-07-29 02:18:14 +0000181 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000182
Evan Chenga8e29892007-01-19 07:51:42 +0000183 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000184 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000185 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000186 };
Devang Patel19974732007-05-03 01:11:54 +0000187 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000188}
189
Dale Johannesen8593e412007-04-29 19:19:30 +0000190/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000191void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000192 assert(BBOffsets.size() == BBSizes.size());
193 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
194 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000195 if (!isThumb)
196 return;
197#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000198 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000199 MBBI != E; ++MBBI) {
200 MachineBasicBlock *MBB = MBBI;
201 if (!MBB->empty() &&
202 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
203 unsigned MBBId = MBB->getNumber();
204 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
205 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000206 }
207 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000208#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000209}
210
211/// print block size and offset information - debugging
212void ARMConstantIslands::dumpBBs() {
213 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilson84945262009-05-12 17:09:30 +0000214 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000215 " size " << BBSizes[J] << "\n";
Dale Johannesen8593e412007-04-29 19:19:30 +0000216 }
217}
218
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000219/// createARMConstantIslandPass - returns an instance of the constpool
220/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000221FunctionPass *llvm::createARMConstantIslandPass() {
222 return new ARMConstantIslands();
223}
224
Evan Cheng5657c012009-07-29 02:18:14 +0000225bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
226 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000227
Evan Cheng5657c012009-07-29 02:18:14 +0000228 TII = MF.getTarget().getInstrInfo();
229 AFI = MF.getInfo<ARMFunctionInfo>();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000230 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000231 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000232 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000233
234 HasFarJump = false;
235
Evan Chenga8e29892007-01-19 07:51:42 +0000236 // Renumber all of the machine basic blocks in the function, guaranteeing that
237 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000238 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000239
Evan Chengd3d9d662009-07-23 18:27:47 +0000240 // Thumb1 functions containing constant pools get 2-byte alignment.
241 // This is so we can keep exact track of where the alignment padding goes.
242
243 // Set default. Thumb1 function is 1-byte aligned, ARM and Thumb2 are 2-byte
244 // aligned.
245 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000246
Evan Chenga8e29892007-01-19 07:51:42 +0000247 // Perform the initial placement of the constant pool entries. To start with,
248 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000249 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000250 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000251 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000252 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000253 AFI->setAlign(2U);
254 }
Bob Wilson84945262009-05-12 17:09:30 +0000255
Evan Chenga8e29892007-01-19 07:51:42 +0000256 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000257 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000258
Evan Chenga8e29892007-01-19 07:51:42 +0000259 // Do the initial scan of the function, building up information about the
260 // sizes of each block, the location of all the water, and finding all of the
261 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000262 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000263 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000264
Evan Chenged884f32007-04-03 23:39:48 +0000265 /// Remove dead constant pool entries.
266 RemoveUnusedCPEntries();
267
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000268 // Iteratively place constant pool entries and fix up branches until there
269 // is no change.
270 bool MadeChange = false;
271 while (true) {
272 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000273 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Cheng5657c012009-07-29 02:18:14 +0000274 Change |= HandleConstantPoolUser(MF, i);
Evan Cheng82020102007-07-10 22:00:16 +0000275 DEBUG(dumpBBs());
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000276 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Cheng5657c012009-07-29 02:18:14 +0000277 Change |= FixUpImmediateBr(MF, ImmBranches[i]);
Evan Cheng82020102007-07-10 22:00:16 +0000278 DEBUG(dumpBBs());
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000279 if (!Change)
280 break;
281 MadeChange = true;
282 }
Evan Chenged884f32007-04-03 23:39:48 +0000283
Dale Johannesen8593e412007-04-29 19:19:30 +0000284 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000285 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000286
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000287 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
288 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000289 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000290 MadeChange |= UndoLRSpillRestore();
291
Evan Cheng5657c012009-07-29 02:18:14 +0000292 // Let's see if we can use tbb / tbh to do jump tables.
293 MadeChange |= OptimizeThumb2JumpTables(MF);
294
Evan Chenga8e29892007-01-19 07:51:42 +0000295 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000296 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000297 WaterList.clear();
298 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000299 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000300 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000301 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000302 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000303
304 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000305}
306
307/// DoInitialPlacement - Perform the initial placement of the constant pool
308/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000309void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000310 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000311 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000312 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
313 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000314
Evan Chenga8e29892007-01-19 07:51:42 +0000315 // Add all of the constants from the constant pool to the end block, use an
316 // identity mapping of CPI's to CPE's.
317 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000318 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000319
Evan Cheng5657c012009-07-29 02:18:14 +0000320 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000321 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000322 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000323 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
324 // we would have to pad them out or something so that instructions stay
325 // aligned.
326 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
327 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000328 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000329 .addImm(i).addConstantPoolIndex(i).addImm(Size);
330 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000331
332 // Add a new CPEntry, but no corresponding CPUser yet.
333 std::vector<CPEntry> CPEs;
334 CPEs.push_back(CPEntry(CPEMI, i));
335 CPEntries.push_back(CPEs);
336 NumCPEs++;
337 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000338 }
339}
340
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000341/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000342/// into the block immediately after it.
343static bool BBHasFallthrough(MachineBasicBlock *MBB) {
344 // Get the next machine basic block in the function.
345 MachineFunction::iterator MBBI = MBB;
346 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
347 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000348
Evan Chenga8e29892007-01-19 07:51:42 +0000349 MachineBasicBlock *NextBB = next(MBBI);
350 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
351 E = MBB->succ_end(); I != E; ++I)
352 if (*I == NextBB)
353 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000354
Evan Chenga8e29892007-01-19 07:51:42 +0000355 return false;
356}
357
Evan Chengc99ef082007-02-09 20:54:44 +0000358/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
359/// look up the corresponding CPEntry.
360ARMConstantIslands::CPEntry
361*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
362 const MachineInstr *CPEMI) {
363 std::vector<CPEntry> &CPEs = CPEntries[CPI];
364 // Number of entries per constpool index should be small, just do a
365 // linear search.
366 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
367 if (CPEs[i].CPEMI == CPEMI)
368 return &CPEs[i];
369 }
370 return NULL;
371}
372
Evan Chenga8e29892007-01-19 07:51:42 +0000373/// InitialFunctionScan - Do the initial scan of the function, building up
374/// information about the sizes of each block, the location of all the water,
375/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000376void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000377 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000378 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000379 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000380 MBBI != E; ++MBBI) {
381 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000382
Evan Chenga8e29892007-01-19 07:51:42 +0000383 // If this block doesn't fall through into the next MBB, then this is
384 // 'water' that a constant pool island could be placed.
385 if (!BBHasFallthrough(&MBB))
386 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000387
Evan Chenga8e29892007-01-19 07:51:42 +0000388 unsigned MBBSize = 0;
389 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
390 I != E; ++I) {
391 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000392 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000393
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000394 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000395 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000396 bool isCond = false;
397 unsigned Bits = 0;
398 unsigned Scale = 1;
399 int UOpc = Opc;
400 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000401 default:
402 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000403 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000404 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000405 // be right, functions containing these must be 4-byte aligned.
406 AFI->setAlign(2U);
407 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000408 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000409 MBBSize += 2; // padding
410 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000411 case ARM::t2BR_JT:
412 T2JumpTables.push_back(I);
413 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000414 case ARM::Bcc:
415 isCond = true;
416 UOpc = ARM::B;
417 // Fallthrough
418 case ARM::B:
419 Bits = 24;
420 Scale = 4;
421 break;
422 case ARM::tBcc:
423 isCond = true;
424 UOpc = ARM::tB;
425 Bits = 8;
426 Scale = 2;
427 break;
428 case ARM::tB:
429 Bits = 11;
430 Scale = 2;
431 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000432 case ARM::t2Bcc:
433 isCond = true;
434 UOpc = ARM::t2B;
435 Bits = 20;
436 Scale = 2;
437 break;
438 case ARM::t2B:
439 Bits = 24;
440 Scale = 2;
441 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000442 }
Evan Chengb43216e2007-02-01 10:16:15 +0000443
444 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000445 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000446 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000447 }
448
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000449 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
450 PushPopMIs.push_back(I);
451
Evan Chengd3d9d662009-07-23 18:27:47 +0000452 if (Opc == ARM::CONSTPOOL_ENTRY)
453 continue;
454
Evan Chenga8e29892007-01-19 07:51:42 +0000455 // Scan the instructions for constant pool operands.
456 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000457 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000458 // We found one. The addressing mode tells us the max displacement
459 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000460
Evan Chenga8e29892007-01-19 07:51:42 +0000461 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000462 unsigned Bits = 0;
463 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000464 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000465 bool IsSoImm = false;
466
467 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000468 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000469 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000470 break;
471
472 // Taking the address of a CP entry.
473 case ARM::LEApcrel:
474 // This takes a SoImm, which is 8 bit immediate rotated. We'll
475 // pretend the maximum offset is 255 * 4. Since each instruction
476 // 4 byte wide, this is always correct. We'llc heck for other
477 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000478 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000479 Scale = 4;
480 NegOk = true;
481 IsSoImm = true;
482 break;
483 case ARM::t2LEApcrel:
484 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000485 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000486 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000487 case ARM::tLEApcrel:
488 Bits = 8;
489 Scale = 4;
490 break;
491
492 case ARM::LDR:
493 case ARM::LDRcp:
494 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000495 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000496 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000497 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000498
499 case ARM::tLDRpci:
500 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000501 Bits = 8;
502 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000503 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000504
505 case ARM::FLDD:
506 case ARM::FLDS:
507 Bits = 8;
508 Scale = 4; // +-(offset_8*4)
509 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000510 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000511 }
Evan Chengb43216e2007-02-01 10:16:15 +0000512
Evan Chenga8e29892007-01-19 07:51:42 +0000513 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000514 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000515 MachineInstr *CPEMI = CPEMIs[CPI];
Bob Wilson84945262009-05-12 17:09:30 +0000516 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000517 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000518
519 // Increment corresponding CPEntry reference count.
520 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
521 assert(CPE && "Cannot find a corresponding CPEntry!");
522 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000523
Evan Chenga8e29892007-01-19 07:51:42 +0000524 // Instructions can only use one CP entry, don't bother scanning the
525 // rest of the operands.
526 break;
527 }
528 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000529
Dale Johannesen8593e412007-04-29 19:19:30 +0000530 // In thumb mode, if this block is a constpool island, we may need padding
531 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000532 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000533 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000534 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
535 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000536 MBBSize += 2;
537
Evan Chenga8e29892007-01-19 07:51:42 +0000538 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000539 BBOffsets.push_back(Offset);
540 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000541 }
542}
543
Evan Chenga8e29892007-01-19 07:51:42 +0000544/// GetOffsetOf - Return the current offset of the specified machine instruction
545/// from the start of the function. This offset changes as stuff is moved
546/// around inside the function.
547unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
548 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000549
Evan Chenga8e29892007-01-19 07:51:42 +0000550 // The offset is composed of two things: the sum of the sizes of all MBB's
551 // before this instruction's block, and the offset from the start of the block
552 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000553 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000554
Dale Johannesen8593e412007-04-29 19:19:30 +0000555 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
556 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000557 if (isThumb &&
558 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000559 Offset%4 != 0)
560 Offset += 2;
561
Evan Chenga8e29892007-01-19 07:51:42 +0000562 // Sum instructions before MI in MBB.
563 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
564 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
565 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000566 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000567 }
568}
569
570/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
571/// ID.
572static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
573 const MachineBasicBlock *RHS) {
574 return LHS->getNumber() < RHS->getNumber();
575}
576
577/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
578/// machine function, it upsets all of the block numbers. Renumber the blocks
579/// and update the arrays that parallel this numbering.
580void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
581 // Renumber the MBB's to keep them consequtive.
582 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000583
Evan Chenga8e29892007-01-19 07:51:42 +0000584 // Insert a size into BBSizes to align it properly with the (newly
585 // renumbered) block numbers.
586 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000587
588 // Likewise for BBOffsets.
589 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000590
591 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000592 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000593 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000594 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
595 CompareMBBNumbers);
596 WaterList.insert(IP, NewBB);
597}
598
599
600/// Split the basic block containing MI into two blocks, which are joined by
601/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000602/// account for this change and returns the newly created block.
603MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000604 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000605 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000606
607 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000608 MachineBasicBlock *NewBB =
609 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000610 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000611 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000612
Evan Chenga8e29892007-01-19 07:51:42 +0000613 // Splice the instructions starting with MI over to NewBB.
614 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000615
Evan Chenga8e29892007-01-19 07:51:42 +0000616 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000617 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000618 // There doesn't seem to be meaningful DebugInfo available; this doesn't
619 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000620 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
621 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000622 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000623
Evan Chenga8e29892007-01-19 07:51:42 +0000624 // Update the CFG. All succs of OrigBB are now succs of NewBB.
625 while (!OrigBB->succ_empty()) {
626 MachineBasicBlock *Succ = *OrigBB->succ_begin();
627 OrigBB->removeSuccessor(Succ);
628 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000629
Evan Chenga8e29892007-01-19 07:51:42 +0000630 // This pass should be run after register allocation, so there should be no
631 // PHI nodes to update.
632 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
633 && "PHI nodes should be eliminated by now!");
634 }
Bob Wilson84945262009-05-12 17:09:30 +0000635
Evan Chenga8e29892007-01-19 07:51:42 +0000636 // OrigBB branches to NewBB.
637 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000638
Evan Chenga8e29892007-01-19 07:51:42 +0000639 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000640 // This is almost the same as UpdateForInsertedWaterBlock, except that
641 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000642 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000643
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000644 // Insert a size into BBSizes to align it properly with the (newly
645 // renumbered) block numbers.
646 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000647
Dale Johannesen99c49a42007-02-25 00:47:03 +0000648 // Likewise for BBOffsets.
649 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
650
Bob Wilson84945262009-05-12 17:09:30 +0000651 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000652 // available water after it (but not if it's already there, which happens
653 // when splitting before a conditional branch that is followed by an
654 // unconditional branch - in that case we want to insert NewBB).
655 std::vector<MachineBasicBlock*>::iterator IP =
656 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
657 CompareMBBNumbers);
658 MachineBasicBlock* WaterBB = *IP;
659 if (WaterBB == OrigBB)
660 WaterList.insert(next(IP), NewBB);
661 else
662 WaterList.insert(IP, OrigBB);
663
Dale Johannesen8593e412007-04-29 19:19:30 +0000664 // Figure out how large the first NewMBB is. (It cannot
665 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000666 unsigned NewBBSize = 0;
667 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
668 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000669 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000670
Dale Johannesen99c49a42007-02-25 00:47:03 +0000671 unsigned OrigBBI = OrigBB->getNumber();
672 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000673 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000674 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000675
Evan Chenga8e29892007-01-19 07:51:42 +0000676 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000677 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Chengd3d9d662009-07-23 18:27:47 +0000678 unsigned delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000679 BBSizes[OrigBBI] -= NewBBSize - delta;
680
681 // ...and adjust BBOffsets for NewBB accordingly.
682 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
683
684 // All BBOffsets following these blocks must be modified.
685 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000686
687 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000688}
689
Dale Johannesen8593e412007-04-29 19:19:30 +0000690/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000691/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000692/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000693bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000694 unsigned TrialOffset, unsigned MaxDisp,
695 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000696 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
697 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000698 // Effectively, the valid range of displacements is 2 bytes smaller for such
699 // references.
700 if (isThumb && UserOffset%4 !=0)
701 UserOffset -= 2;
702 // CPEs will be rounded up to a multiple of 4.
703 if (isThumb && TrialOffset%4 != 0)
704 TrialOffset += 2;
705
Dale Johannesen99c49a42007-02-25 00:47:03 +0000706 if (UserOffset <= TrialOffset) {
707 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000708 if (TrialOffset - UserOffset <= MaxDisp)
709 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000710 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000711 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000712 if (UserOffset - TrialOffset <= MaxDisp)
713 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000714 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000715 }
716 return false;
717}
718
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000719/// WaterIsInRange - Returns true if a CPE placed after the specified
720/// Water (a basic block) will be in range for the specific MI.
721
722bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000723 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000724 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000725 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000726 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000727
Dale Johannesend959aa42007-04-02 20:31:06 +0000728 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000729 // the offset of the instruction. (Currently applies only to ARM, so
730 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000731 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000732 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000733
Evan Chengd3d9d662009-07-23 18:27:47 +0000734 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000735}
736
737/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000738/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000739bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000740 MachineInstr *CPEMI, unsigned MaxDisp,
741 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000742 unsigned CPEOffset = GetOffsetOf(CPEMI);
743 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000744
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000745 if (DoDump) {
746 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
747 << " max delta=" << MaxDisp
748 << " insn address=" << UserOffset
749 << " CPE address=" << CPEOffset
750 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
751 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000752
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000753 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000754}
755
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000756#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000757/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
758/// unconditionally branches to its only successor.
759static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
760 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
761 return false;
762
763 MachineBasicBlock *Succ = *MBB->succ_begin();
764 MachineBasicBlock *Pred = *MBB->pred_begin();
765 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000766 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
767 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000768 return PredMI->getOperand(0).getMBB() == Succ;
769 return false;
770}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000771#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000772
Bob Wilson84945262009-05-12 17:09:30 +0000773void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000774 int delta) {
775 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000776 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
777 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000778 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000779 // If some existing blocks have padding, adjust the padding as needed, a
780 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000781 if (!isThumb)
782 continue;
783 MachineBasicBlock *MBB = MBBI;
784 if (!MBB->empty()) {
785 // Constant pool entries require padding.
786 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
787 unsigned oldOffset = BBOffsets[i] - delta;
788 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
789 // add new padding
790 BBSizes[i] += 2;
791 delta += 2;
792 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
793 // remove existing padding
794 BBSizes[i] -=2;
795 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000796 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000797 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000798 // Thumb1 jump tables require padding. They should be at the end;
799 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000800 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000801 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000802 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
803 unsigned oldMIOffset = newMIOffset - delta;
804 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
805 // remove existing padding
806 BBSizes[i] -= 2;
807 delta -= 2;
808 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
809 // add new padding
810 BBSizes[i] += 2;
811 delta += 2;
812 }
813 }
814 if (delta==0)
815 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000816 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000817 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000818 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000819}
820
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000821/// DecrementOldEntry - find the constant pool entry with index CPI
822/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000823/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000824/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000825
Evan Chenged884f32007-04-03 23:39:48 +0000826bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000827 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000828 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
829 assert(CPE && "Unexpected!");
830 if (--CPE->RefCount == 0) {
831 RemoveDeadCPEMI(CPEMI);
832 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000833 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000834 return true;
835 }
836 return false;
837}
838
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000839/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
840/// if not, see if an in-range clone of the CPE is in range, and if so,
841/// change the data structures so the user references the clone. Returns:
842/// 0 = no existing entry found
843/// 1 = entry found, and there were no code insertions or deletions
844/// 2 = entry found, and there were code insertions or deletions
845int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
846{
847 MachineInstr *UserMI = U.MI;
848 MachineInstr *CPEMI = U.CPEMI;
849
850 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000851 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Evan Cheng82020102007-07-10 22:00:16 +0000852 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000853 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000854 }
855
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000856 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000857 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000858 std::vector<CPEntry> &CPEs = CPEntries[CPI];
859 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
860 // We already tried this one
861 if (CPEs[i].CPEMI == CPEMI)
862 continue;
863 // Removing CPEs can leave empty entries, skip
864 if (CPEs[i].CPEMI == NULL)
865 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000866 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000867 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
868 // Point the CPUser node to the replacement
869 U.CPEMI = CPEs[i].CPEMI;
870 // Change the CPI in the instruction operand to refer to the clone.
871 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000872 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000873 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000874 break;
875 }
876 // Adjust the refcount of the clone...
877 CPEs[i].RefCount++;
878 // ...and the original. If we didn't remove the old entry, none of the
879 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000880 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000881 }
882 }
883 return 0;
884}
885
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000886/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
887/// the specific unconditional branch instruction.
888static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000889 switch (Opc) {
890 case ARM::tB:
891 return ((1<<10)-1)*2;
892 case ARM::t2B:
893 return ((1<<23)-1)*2;
894 default:
895 break;
896 }
897
898 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000899}
900
Dale Johannesen8593e412007-04-29 19:19:30 +0000901/// AcceptWater - Small amount of common code factored out of the following.
902
Bob Wilson84945262009-05-12 17:09:30 +0000903MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000904 std::vector<MachineBasicBlock*>::iterator IP) {
905 DOUT << "found water in range\n";
906 // Remove the original WaterList entry; we want subsequent
907 // insertions in this vicinity to go after the one we're
908 // about to insert. This considerably reduces the number
909 // of times we have to move the same CPE more than once.
910 WaterList.erase(IP);
911 // CPE goes before following block (NewMBB).
912 return next(MachineFunction::iterator(WaterBB));
913}
914
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000915/// LookForWater - look for an existing entry in the WaterList in which
916/// we can place the CPE referenced from U so it's within range of U's MI.
917/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000918/// is set to the WaterList entry.
Evan Chengd3d9d662009-07-23 18:27:47 +0000919/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
Dale Johannesen8593e412007-04-29 19:19:30 +0000920/// water that will not introduce padding to water that will; within each
921/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000922bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000923 MachineBasicBlock** NewMBB) {
924 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
925 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000926 if (!WaterList.empty()) {
927 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
Evan Chengd3d9d662009-07-23 18:27:47 +0000928 B = WaterList.begin();; --IP) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000929 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000930 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000931 unsigned WBBId = WaterBB->getNumber();
Dale Johannesen8593e412007-04-29 19:19:30 +0000932 if (isThumb &&
Evan Chengd3d9d662009-07-23 18:27:47 +0000933 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000934 // This is valid Water, but would introduce padding. Remember
935 // it in case we don't find any Water that doesn't do this.
936 if (!WaterBBThatWouldPad) {
937 WaterBBThatWouldPad = WaterBB;
938 IPThatWouldPad = IP;
939 }
940 } else {
941 *NewMBB = AcceptWater(WaterBB, IP);
942 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000943 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000944 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000945 if (IP == B)
946 break;
947 }
948 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000949 if (isThumb && WaterBBThatWouldPad) {
950 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
951 return true;
952 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000953 return false;
954}
955
Bob Wilson84945262009-05-12 17:09:30 +0000956/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000957/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
958/// block is used if in range, and the conditional branch munged so control
959/// flow is correct. Otherwise the block is split to create a hole with an
960/// unconditional branch around it. In either case *NewMBB is set to a
961/// block following which the new island can be inserted (the WaterList
962/// is not adjusted).
963
Bob Wilson84945262009-05-12 17:09:30 +0000964void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000965 unsigned UserOffset, MachineBasicBlock** NewMBB) {
966 CPUser &U = CPUsers[CPUserIndex];
967 MachineInstr *UserMI = U.MI;
968 MachineInstr *CPEMI = U.CPEMI;
969 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000970 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000971 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +0000972 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000973
974 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +0000975 // is within range, make new water there. (The addition below is
Evan Chengd3d9d662009-07-23 18:27:47 +0000976 // for the unconditional branch we will be adding: 4 bytes on ARM + Thumb2,
977 // 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +0000978 // inside OffsetIsInRange.
Bob Wilson84945262009-05-12 17:09:30 +0000979 // If the block ends in an unconditional branch already, it is water,
Dale Johannesen8593e412007-04-29 19:19:30 +0000980 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000981 if (&UserMBB->back() == UserMI ||
Evan Chengd3d9d662009-07-23 18:27:47 +0000982 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
983 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000984 DOUT << "Split at end of block\n";
985 if (&UserMBB->back() == UserMI)
986 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
987 *NewMBB = next(MachineFunction::iterator(UserMBB));
988 // Add an unconditional branch from UserMBB to fallthrough block.
989 // Record it for branch lengthening; this new branch will not get out of
990 // range, but if the preceding conditional branch is out of range, the
991 // targets will be exchanged, and the altered branch may be out of
992 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +0000993 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +0000994 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
995 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000996 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +0000997 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000998 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +0000999 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001000 BBSizes[UserMBB->getNumber()] += delta;
1001 AdjustBBOffsetsAfter(UserMBB, delta);
1002 } else {
1003 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001004 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001005 // and constant pool entries are 4 bytes: if instruction I references
1006 // island CPE, and instruction I+1 references CPE', it will
1007 // not work well to put CPE as far forward as possible, since then
1008 // CPE' cannot immediately follow it (that location is 2 bytes
1009 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001010 // a new island. So, we make a first guess, then walk through the
1011 // instructions between the one currently being looked at and the
1012 // possible insertion point, and make sure any other instructions
1013 // that reference CPEs will be able to use the same island area;
1014 // if not, we back up the insertion point.
1015
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001016 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001017 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001018 // island is handled inside OffsetIsInRange.
1019 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001020 // This could point off the end of the block if we've already got
1021 // constant pool entries following this block; only the last one is
1022 // in the water list. Back past any possible branches (allow for a
1023 // conditional and a maximally long unconditional).
1024 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001025 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001026 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001027 unsigned EndInsertOffset = BaseInsertOffset +
1028 CPEMI->getOperand(2).getImm();
1029 MachineBasicBlock::iterator MI = UserMI;
1030 ++MI;
1031 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001032 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001033 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001034 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001035 MI = next(MI)) {
1036 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001037 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001038 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001039 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1040 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1041 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001042 }
1043 // This is overly conservative, as we don't account for CPEMIs
1044 // being reused within the block, but it doesn't matter much.
1045 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1046 CPUIndex++;
1047 }
1048 }
1049 DOUT << "Split in middle of big block\n";
1050 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1051 }
1052}
1053
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001054/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001055/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001056/// place in-range. Return true if we changed any addresses (thus must run
1057/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001058bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001059 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001060 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001061 MachineInstr *UserMI = U.MI;
1062 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001063 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001064 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001065 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001066 // Compute this only once, it's expensive. The 4 or 8 is the value the
Bob Wilson39bf0512009-05-12 17:35:29 +00001067 // hardware keeps in the PC (2 insns ahead of the reference).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001068 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001069
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001070 // See if the current entry is within range, or there is a clone of it
1071 // in range.
1072 int result = LookForExistingCPEntry(U, UserOffset);
1073 if (result==1) return false;
1074 else if (result==2) return true;
1075
1076 // No existing clone of this CPE is within range.
1077 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001078 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001079
1080 // Look for water where we can place this CPE. We look for the farthest one
1081 // away that will work. Forward references only for now (although later
1082 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001083
Dale Johannesen8593e412007-04-29 19:19:30 +00001084 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001085 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001086 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001087 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001088 }
1089
1090 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001091 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1092 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001093
1094 // Update internal data structures to account for the newly inserted MBB.
1095 UpdateForInsertedWaterBlock(NewIsland);
1096
1097 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001098 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001099
1100 // Now that we have an island to add the CPE to, clone the original CPE and
1101 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001102 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1103 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001104 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001105 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001106 NumCPEs++;
1107
Dale Johannesen8593e412007-04-29 19:19:30 +00001108 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001109 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001110 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001111 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001112 // Increase the size of the island block to account for the new entry.
1113 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001114 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001115
Evan Chenga8e29892007-01-19 07:51:42 +00001116 // Finally, change the CPI in the instruction operand to be ID.
1117 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001118 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001119 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001120 break;
1121 }
Bob Wilson84945262009-05-12 17:09:30 +00001122
Evan Chengc99ef082007-02-09 20:54:44 +00001123 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilson84945262009-05-12 17:09:30 +00001124
Evan Chenga8e29892007-01-19 07:51:42 +00001125 return true;
1126}
1127
Evan Chenged884f32007-04-03 23:39:48 +00001128/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1129/// sizes and offsets of impacted basic blocks.
1130void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1131 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001132 unsigned Size = CPEMI->getOperand(2).getImm();
1133 CPEMI->eraseFromParent();
1134 BBSizes[CPEBB->getNumber()] -= Size;
1135 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001136 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001137 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001138 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001139 // empty, so fix this.
1140 // All succeeding offsets have the current size value added in, fix this.
1141 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001142 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001143 BBSizes[CPEBB->getNumber()] = 0;
1144 }
Evan Chenged884f32007-04-03 23:39:48 +00001145 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001146 AdjustBBOffsetsAfter(CPEBB, -Size);
1147 // An island has only one predecessor BB and one successor BB. Check if
1148 // this BB's predecessor jumps directly to this BB's successor. This
1149 // shouldn't happen currently.
1150 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1151 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001152}
1153
1154/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1155/// are zero.
1156bool ARMConstantIslands::RemoveUnusedCPEntries() {
1157 unsigned MadeChange = false;
1158 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1159 std::vector<CPEntry> &CPEs = CPEntries[i];
1160 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1161 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1162 RemoveDeadCPEMI(CPEs[j].CPEMI);
1163 CPEs[j].CPEMI = NULL;
1164 MadeChange = true;
1165 }
1166 }
Bob Wilson84945262009-05-12 17:09:30 +00001167 }
Evan Chenged884f32007-04-03 23:39:48 +00001168 return MadeChange;
1169}
1170
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001171/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001172/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001173bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1174 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001175 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001176 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001177 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001178
Evan Chengc99ef082007-02-09 20:54:44 +00001179 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1180 << " from BB#" << MI->getParent()->getNumber()
1181 << " max delta=" << MaxDisp
Dale Johannesen8593e412007-04-29 19:19:30 +00001182 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1183 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +00001184
Dale Johannesen8593e412007-04-29 19:19:30 +00001185 if (BrOffset <= DestOffset) {
1186 // Branch before the Dest.
1187 if (DestOffset-BrOffset <= MaxDisp)
1188 return true;
1189 } else {
1190 if (BrOffset-DestOffset <= MaxDisp)
1191 return true;
1192 }
1193 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001194}
1195
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001196/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1197/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001198bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001199 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001200 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001201
Evan Chengc0dbec72007-01-31 19:57:44 +00001202 // Check to see if the DestBB is already in-range.
1203 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001204 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001205
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001206 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001207 return FixUpUnconditionalBr(MF, Br);
1208 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001209}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001210
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001211/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1212/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001213/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001214/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001215bool
Evan Cheng5657c012009-07-29 02:18:14 +00001216ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001217 MachineInstr *MI = Br.MI;
1218 MachineBasicBlock *MBB = MI->getParent();
Evan Chengd3d9d662009-07-23 18:27:47 +00001219 assert(isThumb && !isThumb2 && "Expected a Thumb1 function!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001220
1221 // Use BL to implement far jump.
1222 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001223 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001224 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001225 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001226 HasFarJump = true;
1227 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001228
Evan Chengc99ef082007-02-09 20:54:44 +00001229 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001230
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001231 return true;
1232}
1233
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001234/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001235/// far away to fit in its displacement field. It is converted to an inverse
1236/// conditional branch + an unconditional branch to the destination.
1237bool
Evan Cheng5657c012009-07-29 02:18:14 +00001238ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001239 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001240 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001241
Bob Wilson39bf0512009-05-12 17:35:29 +00001242 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001243 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001244 // blt L1
1245 // =>
1246 // bge L2
1247 // b L1
1248 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001249 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001250 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001251 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001252
1253 // If the branch is at the end of its MBB and that has a fall-through block,
1254 // direct the updated conditional branch to the fall-through block. Otherwise,
1255 // split the MBB before the next instruction.
1256 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001257 MachineInstr *BMI = &MBB->back();
1258 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001259
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001260 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001261 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001262 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001263 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001264 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001265 // condition and swap destinations:
1266 // beq L1
1267 // b L2
1268 // =>
1269 // bne L2
1270 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001271 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001272 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001273 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001274 BMI->getOperand(0).setMBB(DestBB);
1275 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001276 MI->getOperand(1).setImm(CC);
1277 return true;
1278 }
1279 }
1280 }
1281
1282 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001283 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001284 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001285 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001286 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001287 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001288 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1289 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001290 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001291 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001292 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001293 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001294
Evan Chengc99ef082007-02-09 20:54:44 +00001295 DOUT << " Insert B to BB#" << DestBB->getNumber()
1296 << " also invert condition and change dest. to BB#"
1297 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001298
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001299 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001300 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001301 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1302 TII->get(MI->getOpcode()))
1303 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001304 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001305 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001306 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001307 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001308 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001309 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001310
1311 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001312 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001313 MI->eraseFromParent();
1314
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001315 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001316 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001317 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001318 return true;
1319}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001320
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001321/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1322/// LR / restores LR to pc.
1323bool ARMConstantIslands::UndoLRSpillRestore() {
1324 bool MadeChange = false;
1325 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1326 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001327 if (MI->getOpcode() == ARM::tPOP_RET &&
1328 MI->getOperand(0).getReg() == ARM::PC &&
1329 MI->getNumExplicitOperands() == 1) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001330 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001331 MI->eraseFromParent();
1332 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001333 }
1334 }
1335 return MadeChange;
1336}
Evan Cheng5657c012009-07-29 02:18:14 +00001337
1338bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1339 bool MadeChange = false;
1340
1341 // FIXME: After the tables are shrunk, can we get rid some of the
1342 // constantpool tables?
1343 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1344 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1345 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1346 MachineInstr *MI = T2JumpTables[i];
1347 const TargetInstrDesc &TID = MI->getDesc();
1348 unsigned NumOps = TID.getNumOperands();
1349 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1350 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1351 unsigned JTI = JTOP.getIndex();
1352 assert(JTI < JT.size());
1353
1354 bool ByteOk = true;
1355 bool HalfWordOk = true;
1356 unsigned JTOffset = GetOffsetOf(MI) + 4;
1357 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1358 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1359 MachineBasicBlock *MBB = JTBBs[j];
1360 unsigned DstOffset = BBOffsets[MBB->getNumber()];
1361 if (ByteOk && !OffsetIsInRange(JTOffset, DstOffset, (1<<8)-1, true, false))
1362 ByteOk = false;
1363 if (HalfWordOk &&
1364 !OffsetIsInRange(JTOffset, DstOffset, (1<<16)-1, true, false))
1365 HalfWordOk = false;
1366 if (!ByteOk && !HalfWordOk)
1367 break;
1368 }
1369
1370 if (ByteOk || HalfWordOk) {
1371 MachineBasicBlock *MBB = MI->getParent();
1372 unsigned BaseReg = MI->getOperand(0).getReg();
1373 bool BaseRegKill = MI->getOperand(0).isKill();
1374 if (!BaseRegKill)
1375 continue;
1376 unsigned IdxReg = MI->getOperand(1).getReg();
1377 bool IdxRegKill = MI->getOperand(1).isKill();
1378 MachineBasicBlock::iterator PrevI = MI;
1379 if (PrevI == MBB->begin())
1380 continue;
1381
1382 MachineInstr *AddrMI = --PrevI;
1383 bool OptOk = true;
1384 // Examine the instruction that calculate the jumptable entry address.
1385 // If it's not the one just before the t2BR_JT, we won't delete it, then
1386 // it's not worth doing the optimization.
1387 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1388 const MachineOperand &MO = AddrMI->getOperand(k);
1389 if (!MO.isReg() || !MO.getReg())
1390 continue;
1391 if (MO.isDef() && MO.getReg() != BaseReg) {
1392 OptOk = false;
1393 break;
1394 }
1395 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1396 OptOk = false;
1397 break;
1398 }
1399 }
1400 if (!OptOk)
1401 continue;
1402
1403 // The previous instruction should be a t2LEApcrelJT, we want to delete
1404 // it as well.
1405 MachineInstr *LeaMI = --PrevI;
1406 if (LeaMI->getOpcode() != ARM::t2LEApcrelJT ||
1407 LeaMI->getOperand(0).getReg() != BaseReg)
1408 LeaMI = 0;
1409
1410 if (OptOk) {
1411 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1412 AddDefaultPred(BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1413 .addReg(IdxReg, getKillRegState(IdxRegKill))
1414 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1415 .addImm(MI->getOperand(JTOpIdx+1).getImm()));
1416
1417 AddrMI->eraseFromParent();
1418 if (LeaMI)
1419 LeaMI->eraseFromParent();
1420 MI->eraseFromParent();
1421 ++NumTBs;
1422 MadeChange = true;
1423 }
1424 }
1425 }
1426
1427 return MadeChange;
1428}