blob: fe7593ee965fc53dbcba140e4e86e19af42f0f2b [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;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000135 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000136 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000137 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000138 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000139 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000140 public:
Devang Patel19974732007-05-03 01:11:54 +0000141 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000142 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000143
Evan Cheng5657c012009-07-29 02:18:14 +0000144 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000145
146 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000147 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000148 }
Bob Wilson84945262009-05-12 17:09:30 +0000149
Evan Chenga8e29892007-01-19 07:51:42 +0000150 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000151 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000152 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000153 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng5657c012009-07-29 02:18:14 +0000154 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000155 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000156 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000157 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000158 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000159 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000160 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilson84945262009-05-12 17:09:30 +0000161 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000162 MachineBasicBlock** NewMBB);
Bob Wilson84945262009-05-12 17:09:30 +0000163 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000164 std::vector<MachineBasicBlock*>::iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000165 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
166 MachineBasicBlock** NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000167 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000168 void RemoveDeadCPEMI(MachineInstr *CPEMI);
169 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000170 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000171 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
172 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000173 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000174 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000175 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000176 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000177 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000178 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
179 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
180 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000181 bool UndoLRSpillRestore();
Evan Cheng5657c012009-07-29 02:18:14 +0000182 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000183
Evan Chenga8e29892007-01-19 07:51:42 +0000184 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000185 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000186 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000187 };
Devang Patel19974732007-05-03 01:11:54 +0000188 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000189}
190
Dale Johannesen8593e412007-04-29 19:19:30 +0000191/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000192void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000193 assert(BBOffsets.size() == BBSizes.size());
194 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
195 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000196 if (!isThumb)
197 return;
198#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000199 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000200 MBBI != E; ++MBBI) {
201 MachineBasicBlock *MBB = MBBI;
202 if (!MBB->empty() &&
203 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
204 unsigned MBBId = MBB->getNumber();
205 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
206 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000207 }
208 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000209#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000210}
211
212/// print block size and offset information - debugging
213void ARMConstantIslands::dumpBBs() {
214 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilson84945262009-05-12 17:09:30 +0000215 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000216 " size " << BBSizes[J] << "\n";
Dale Johannesen8593e412007-04-29 19:19:30 +0000217 }
218}
219
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000220/// createARMConstantIslandPass - returns an instance of the constpool
221/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000222FunctionPass *llvm::createARMConstantIslandPass() {
223 return new ARMConstantIslands();
224}
225
Evan Cheng5657c012009-07-29 02:18:14 +0000226bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
227 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000228
Evan Cheng5657c012009-07-29 02:18:14 +0000229 TII = MF.getTarget().getInstrInfo();
230 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000231 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
232
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000233 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000234 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000235 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000236
237 HasFarJump = false;
238
Evan Chenga8e29892007-01-19 07:51:42 +0000239 // Renumber all of the machine basic blocks in the function, guaranteeing that
240 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000241 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000242
Evan Chengd26b14c2009-07-31 18:28:05 +0000243 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000244 // This is so we can keep exact track of where the alignment padding goes.
245
Evan Chengd26b14c2009-07-31 18:28:05 +0000246 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000247 // aligned.
248 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000249
Evan Chenga8e29892007-01-19 07:51:42 +0000250 // Perform the initial placement of the constant pool entries. To start with,
251 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000252 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000253 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000254 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000255 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000256 AFI->setAlign(2U);
257 }
Bob Wilson84945262009-05-12 17:09:30 +0000258
Evan Chenga8e29892007-01-19 07:51:42 +0000259 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000260 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000261
Evan Chenga8e29892007-01-19 07:51:42 +0000262 // Do the initial scan of the function, building up information about the
263 // sizes of each block, the location of all the water, and finding all of the
264 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000265 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000266 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000267
Evan Chenged884f32007-04-03 23:39:48 +0000268 /// Remove dead constant pool entries.
269 RemoveUnusedCPEntries();
270
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000271 // Iteratively place constant pool entries and fix up branches until there
272 // is no change.
273 bool MadeChange = false;
Evan Chengb6879b22009-08-07 07:35:21 +0000274 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000275 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000276 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000277 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000278 CPChange |= HandleConstantPoolUser(MF, i);
279 if (CPChange && ++NoCPIters > 30)
280 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000281 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000282
283 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000284 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000285 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
286 if (BRChange && ++NoBRIters > 30)
287 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000288 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000289
290 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000291 break;
292 MadeChange = true;
293 }
Evan Chenged884f32007-04-03 23:39:48 +0000294
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000295 // Let's see if we can use tbb / tbh to do jump tables.
296 MadeChange |= OptimizeThumb2JumpTables(MF);
297
Dale Johannesen8593e412007-04-29 19:19:30 +0000298 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000299 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000300
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000301 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
302 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000303 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000304 MadeChange |= UndoLRSpillRestore();
305
Evan Chenga8e29892007-01-19 07:51:42 +0000306 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000307 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000308 WaterList.clear();
309 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000310 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000311 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000312 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000313 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000314
315 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000316}
317
318/// DoInitialPlacement - Perform the initial placement of the constant pool
319/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000320void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000321 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000322 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000323 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
324 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000325
Evan Chenga8e29892007-01-19 07:51:42 +0000326 // Add all of the constants from the constant pool to the end block, use an
327 // identity mapping of CPI's to CPE's.
328 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000329 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000330
Evan Cheng5657c012009-07-29 02:18:14 +0000331 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000332 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000333 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000334 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
335 // we would have to pad them out or something so that instructions stay
336 // aligned.
337 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
338 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000339 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000340 .addImm(i).addConstantPoolIndex(i).addImm(Size);
341 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000342
343 // Add a new CPEntry, but no corresponding CPUser yet.
344 std::vector<CPEntry> CPEs;
345 CPEs.push_back(CPEntry(CPEMI, i));
346 CPEntries.push_back(CPEs);
347 NumCPEs++;
348 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000349 }
350}
351
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000352/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000353/// into the block immediately after it.
354static bool BBHasFallthrough(MachineBasicBlock *MBB) {
355 // Get the next machine basic block in the function.
356 MachineFunction::iterator MBBI = MBB;
357 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
358 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000359
Evan Chenga8e29892007-01-19 07:51:42 +0000360 MachineBasicBlock *NextBB = next(MBBI);
361 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
362 E = MBB->succ_end(); I != E; ++I)
363 if (*I == NextBB)
364 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000365
Evan Chenga8e29892007-01-19 07:51:42 +0000366 return false;
367}
368
Evan Chengc99ef082007-02-09 20:54:44 +0000369/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
370/// look up the corresponding CPEntry.
371ARMConstantIslands::CPEntry
372*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
373 const MachineInstr *CPEMI) {
374 std::vector<CPEntry> &CPEs = CPEntries[CPI];
375 // Number of entries per constpool index should be small, just do a
376 // linear search.
377 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
378 if (CPEs[i].CPEMI == CPEMI)
379 return &CPEs[i];
380 }
381 return NULL;
382}
383
Evan Chenga8e29892007-01-19 07:51:42 +0000384/// InitialFunctionScan - Do the initial scan of the function, building up
385/// information about the sizes of each block, the location of all the water,
386/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000387void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000388 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000389 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000390 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000391 MBBI != E; ++MBBI) {
392 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000393
Evan Chenga8e29892007-01-19 07:51:42 +0000394 // If this block doesn't fall through into the next MBB, then this is
395 // 'water' that a constant pool island could be placed.
396 if (!BBHasFallthrough(&MBB))
397 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000398
Evan Chenga8e29892007-01-19 07:51:42 +0000399 unsigned MBBSize = 0;
400 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
401 I != E; ++I) {
402 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000403 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000404
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000405 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000406 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000407 bool isCond = false;
408 unsigned Bits = 0;
409 unsigned Scale = 1;
410 int UOpc = Opc;
411 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000412 default:
413 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000414 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000415 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000416 // be right, functions containing these must be 4-byte aligned.
417 AFI->setAlign(2U);
418 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000419 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000420 MBBSize += 2; // padding
421 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000422 case ARM::t2BR_JT:
423 T2JumpTables.push_back(I);
424 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000425 case ARM::Bcc:
426 isCond = true;
427 UOpc = ARM::B;
428 // Fallthrough
429 case ARM::B:
430 Bits = 24;
431 Scale = 4;
432 break;
433 case ARM::tBcc:
434 isCond = true;
435 UOpc = ARM::tB;
436 Bits = 8;
437 Scale = 2;
438 break;
439 case ARM::tB:
440 Bits = 11;
441 Scale = 2;
442 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000443 case ARM::t2Bcc:
444 isCond = true;
445 UOpc = ARM::t2B;
446 Bits = 20;
447 Scale = 2;
448 break;
449 case ARM::t2B:
450 Bits = 24;
451 Scale = 2;
452 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000453 }
Evan Chengb43216e2007-02-01 10:16:15 +0000454
455 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000456 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000457 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000458 }
459
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000460 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
461 PushPopMIs.push_back(I);
462
Evan Chengd3d9d662009-07-23 18:27:47 +0000463 if (Opc == ARM::CONSTPOOL_ENTRY)
464 continue;
465
Evan Chenga8e29892007-01-19 07:51:42 +0000466 // Scan the instructions for constant pool operands.
467 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000468 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000469 // We found one. The addressing mode tells us the max displacement
470 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000471
Evan Chenga8e29892007-01-19 07:51:42 +0000472 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000473 unsigned Bits = 0;
474 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000475 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000476 bool IsSoImm = false;
477
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000478 // FIXME: Temporary workaround until I can figure out what's going on.
479 unsigned Slack = T2JumpTables.empty() ? 0 : 4;
Evan Chengd3d9d662009-07-23 18:27:47 +0000480 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000481 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000482 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000483 break;
484
485 // Taking the address of a CP entry.
486 case ARM::LEApcrel:
487 // This takes a SoImm, which is 8 bit immediate rotated. We'll
488 // pretend the maximum offset is 255 * 4. Since each instruction
489 // 4 byte wide, this is always correct. We'llc heck for other
490 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000491 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000492 Scale = 4;
493 NegOk = true;
494 IsSoImm = true;
495 break;
496 case ARM::t2LEApcrel:
497 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000498 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000499 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000500 case ARM::tLEApcrel:
501 Bits = 8;
502 Scale = 4;
503 break;
504
505 case ARM::LDR:
506 case ARM::LDRcp:
507 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000508 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000509 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000510 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000511
512 case ARM::tLDRpci:
513 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000514 Bits = 8;
515 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000516 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000517
518 case ARM::FLDD:
519 case ARM::FLDS:
520 Bits = 8;
521 Scale = 4; // +-(offset_8*4)
522 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000523 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000524 }
Evan Chengb43216e2007-02-01 10:16:15 +0000525
Evan Chenga8e29892007-01-19 07:51:42 +0000526 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000527 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000528 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000529 unsigned MaxOffs = ((1 << Bits)-1) * Scale - Slack;
Evan Chengd3d9d662009-07-23 18:27:47 +0000530 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000531
532 // Increment corresponding CPEntry reference count.
533 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
534 assert(CPE && "Cannot find a corresponding CPEntry!");
535 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000536
Evan Chenga8e29892007-01-19 07:51:42 +0000537 // Instructions can only use one CP entry, don't bother scanning the
538 // rest of the operands.
539 break;
540 }
541 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000542
Dale Johannesen8593e412007-04-29 19:19:30 +0000543 // In thumb mode, if this block is a constpool island, we may need padding
544 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000545 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000546 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000547 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
548 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000549 MBBSize += 2;
550
Evan Chenga8e29892007-01-19 07:51:42 +0000551 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000552 BBOffsets.push_back(Offset);
553 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000554 }
555}
556
Evan Chenga8e29892007-01-19 07:51:42 +0000557/// GetOffsetOf - Return the current offset of the specified machine instruction
558/// from the start of the function. This offset changes as stuff is moved
559/// around inside the function.
560unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
561 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000562
Evan Chenga8e29892007-01-19 07:51:42 +0000563 // The offset is composed of two things: the sum of the sizes of all MBB's
564 // before this instruction's block, and the offset from the start of the block
565 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000566 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000567
Dale Johannesen8593e412007-04-29 19:19:30 +0000568 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
569 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000570 if (isThumb &&
571 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000572 Offset%4 != 0)
573 Offset += 2;
574
Evan Chenga8e29892007-01-19 07:51:42 +0000575 // Sum instructions before MI in MBB.
576 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
577 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
578 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000579 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000580 }
581}
582
583/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
584/// ID.
585static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
586 const MachineBasicBlock *RHS) {
587 return LHS->getNumber() < RHS->getNumber();
588}
589
590/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
591/// machine function, it upsets all of the block numbers. Renumber the blocks
592/// and update the arrays that parallel this numbering.
593void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
594 // Renumber the MBB's to keep them consequtive.
595 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000596
Evan Chenga8e29892007-01-19 07:51:42 +0000597 // Insert a size into BBSizes to align it properly with the (newly
598 // renumbered) block numbers.
599 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000600
601 // Likewise for BBOffsets.
602 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000603
604 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000605 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000606 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000607 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
608 CompareMBBNumbers);
609 WaterList.insert(IP, NewBB);
610}
611
612
613/// Split the basic block containing MI into two blocks, which are joined by
614/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000615/// account for this change and returns the newly created block.
616MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000617 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000618 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000619
620 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000621 MachineBasicBlock *NewBB =
622 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000623 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000624 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000625
Evan Chenga8e29892007-01-19 07:51:42 +0000626 // Splice the instructions starting with MI over to NewBB.
627 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000628
Evan Chenga8e29892007-01-19 07:51:42 +0000629 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000630 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000631 // There doesn't seem to be meaningful DebugInfo available; this doesn't
632 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000633 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
634 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000635 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000636
Evan Chenga8e29892007-01-19 07:51:42 +0000637 // Update the CFG. All succs of OrigBB are now succs of NewBB.
638 while (!OrigBB->succ_empty()) {
639 MachineBasicBlock *Succ = *OrigBB->succ_begin();
640 OrigBB->removeSuccessor(Succ);
641 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000642
Evan Chenga8e29892007-01-19 07:51:42 +0000643 // This pass should be run after register allocation, so there should be no
644 // PHI nodes to update.
645 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
646 && "PHI nodes should be eliminated by now!");
647 }
Bob Wilson84945262009-05-12 17:09:30 +0000648
Evan Chenga8e29892007-01-19 07:51:42 +0000649 // OrigBB branches to NewBB.
650 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000651
Evan Chenga8e29892007-01-19 07:51:42 +0000652 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000653 // This is almost the same as UpdateForInsertedWaterBlock, except that
654 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000655 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000656
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000657 // Insert a size into BBSizes to align it properly with the (newly
658 // renumbered) block numbers.
659 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000660
Dale Johannesen99c49a42007-02-25 00:47:03 +0000661 // Likewise for BBOffsets.
662 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
663
Bob Wilson84945262009-05-12 17:09:30 +0000664 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000665 // available water after it (but not if it's already there, which happens
666 // when splitting before a conditional branch that is followed by an
667 // unconditional branch - in that case we want to insert NewBB).
668 std::vector<MachineBasicBlock*>::iterator IP =
669 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
670 CompareMBBNumbers);
671 MachineBasicBlock* WaterBB = *IP;
672 if (WaterBB == OrigBB)
673 WaterList.insert(next(IP), NewBB);
674 else
675 WaterList.insert(IP, OrigBB);
676
Dale Johannesen8593e412007-04-29 19:19:30 +0000677 // Figure out how large the first NewMBB is. (It cannot
678 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000679 unsigned NewBBSize = 0;
680 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
681 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000682 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000683
Dale Johannesen99c49a42007-02-25 00:47:03 +0000684 unsigned OrigBBI = OrigBB->getNumber();
685 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000686 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000687 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000688
Evan Chenga8e29892007-01-19 07:51:42 +0000689 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000690 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000691 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000692 BBSizes[OrigBBI] -= NewBBSize - delta;
693
694 // ...and adjust BBOffsets for NewBB accordingly.
695 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
696
697 // All BBOffsets following these blocks must be modified.
698 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000699
700 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000701}
702
Dale Johannesen8593e412007-04-29 19:19:30 +0000703/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000704/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000705/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000706bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000707 unsigned TrialOffset, unsigned MaxDisp,
708 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000709 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
710 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000711 // Effectively, the valid range of displacements is 2 bytes smaller for such
712 // references.
713 if (isThumb && UserOffset%4 !=0)
714 UserOffset -= 2;
715 // CPEs will be rounded up to a multiple of 4.
716 if (isThumb && TrialOffset%4 != 0)
717 TrialOffset += 2;
718
Dale Johannesen99c49a42007-02-25 00:47:03 +0000719 if (UserOffset <= TrialOffset) {
720 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000721 if (TrialOffset - UserOffset <= MaxDisp)
722 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000723 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000724 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000725 if (UserOffset - TrialOffset <= MaxDisp)
726 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000727 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000728 }
729 return false;
730}
731
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000732/// WaterIsInRange - Returns true if a CPE placed after the specified
733/// Water (a basic block) will be in range for the specific MI.
734
735bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000736 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000737 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000738 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000739 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000740
Dale Johannesend959aa42007-04-02 20:31:06 +0000741 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000742 // the offset of the instruction. (Currently applies only to ARM, so
743 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000744 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000745 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000746
Evan Chengd3d9d662009-07-23 18:27:47 +0000747 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000748}
749
750/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000751/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000752bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000753 MachineInstr *CPEMI, unsigned MaxDisp,
754 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000755 unsigned CPEOffset = GetOffsetOf(CPEMI);
756 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000757
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000758 if (DoDump) {
759 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
760 << " max delta=" << MaxDisp
761 << " insn address=" << UserOffset
762 << " CPE address=" << CPEOffset
763 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
764 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000765
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000766 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000767}
768
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000769#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000770/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
771/// unconditionally branches to its only successor.
772static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
773 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
774 return false;
775
776 MachineBasicBlock *Succ = *MBB->succ_begin();
777 MachineBasicBlock *Pred = *MBB->pred_begin();
778 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000779 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
780 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000781 return PredMI->getOperand(0).getMBB() == Succ;
782 return false;
783}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000784#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000785
Bob Wilson84945262009-05-12 17:09:30 +0000786void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000787 int delta) {
788 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000789 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
790 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000791 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000792 // If some existing blocks have padding, adjust the padding as needed, a
793 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000794 if (!isThumb)
795 continue;
796 MachineBasicBlock *MBB = MBBI;
797 if (!MBB->empty()) {
798 // Constant pool entries require padding.
799 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000800 unsigned OldOffset = BBOffsets[i] - delta;
801 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000802 // add new padding
803 BBSizes[i] += 2;
804 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000805 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000806 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000807 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000808 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000809 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000810 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000811 // Thumb1 jump tables require padding. They should be at the end;
812 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000813 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000814 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000815 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
816 unsigned OldMIOffset = NewMIOffset - delta;
817 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000818 // remove existing padding
819 BBSizes[i] -= 2;
820 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000821 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000822 // add new padding
823 BBSizes[i] += 2;
824 delta += 2;
825 }
826 }
827 if (delta==0)
828 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000829 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000830 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000831 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000832}
833
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000834/// DecrementOldEntry - find the constant pool entry with index CPI
835/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000836/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000837/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000838
Evan Chenged884f32007-04-03 23:39:48 +0000839bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000840 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000841 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
842 assert(CPE && "Unexpected!");
843 if (--CPE->RefCount == 0) {
844 RemoveDeadCPEMI(CPEMI);
845 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000846 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000847 return true;
848 }
849 return false;
850}
851
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000852/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
853/// if not, see if an in-range clone of the CPE is in range, and if so,
854/// change the data structures so the user references the clone. Returns:
855/// 0 = no existing entry found
856/// 1 = entry found, and there were no code insertions or deletions
857/// 2 = entry found, and there were code insertions or deletions
858int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
859{
860 MachineInstr *UserMI = U.MI;
861 MachineInstr *CPEMI = U.CPEMI;
862
863 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000864 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Evan Cheng82020102007-07-10 22:00:16 +0000865 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000866 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000867 }
868
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000869 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000870 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000871 std::vector<CPEntry> &CPEs = CPEntries[CPI];
872 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
873 // We already tried this one
874 if (CPEs[i].CPEMI == CPEMI)
875 continue;
876 // Removing CPEs can leave empty entries, skip
877 if (CPEs[i].CPEMI == NULL)
878 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000879 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000880 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
881 // Point the CPUser node to the replacement
882 U.CPEMI = CPEs[i].CPEMI;
883 // Change the CPI in the instruction operand to refer to the clone.
884 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000885 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000886 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000887 break;
888 }
889 // Adjust the refcount of the clone...
890 CPEs[i].RefCount++;
891 // ...and the original. If we didn't remove the old entry, none of the
892 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000893 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000894 }
895 }
896 return 0;
897}
898
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000899/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
900/// the specific unconditional branch instruction.
901static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000902 switch (Opc) {
903 case ARM::tB:
904 return ((1<<10)-1)*2;
905 case ARM::t2B:
906 return ((1<<23)-1)*2;
907 default:
908 break;
909 }
910
911 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000912}
913
Dale Johannesen8593e412007-04-29 19:19:30 +0000914/// AcceptWater - Small amount of common code factored out of the following.
915
Bob Wilson84945262009-05-12 17:09:30 +0000916MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000917 std::vector<MachineBasicBlock*>::iterator IP) {
918 DOUT << "found water in range\n";
919 // Remove the original WaterList entry; we want subsequent
920 // insertions in this vicinity to go after the one we're
921 // about to insert. This considerably reduces the number
922 // of times we have to move the same CPE more than once.
923 WaterList.erase(IP);
924 // CPE goes before following block (NewMBB).
925 return next(MachineFunction::iterator(WaterBB));
926}
927
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000928/// LookForWater - look for an existing entry in the WaterList in which
929/// we can place the CPE referenced from U so it's within range of U's MI.
930/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000931/// is set to the WaterList entry.
Evan Chengd3d9d662009-07-23 18:27:47 +0000932/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
Dale Johannesen8593e412007-04-29 19:19:30 +0000933/// water that will not introduce padding to water that will; within each
934/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000935bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000936 MachineBasicBlock** NewMBB) {
937 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
938 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000939 if (!WaterList.empty()) {
940 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
Evan Chengd3d9d662009-07-23 18:27:47 +0000941 B = WaterList.begin();; --IP) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000942 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000943 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000944 unsigned WBBId = WaterBB->getNumber();
Dale Johannesen8593e412007-04-29 19:19:30 +0000945 if (isThumb &&
Evan Chengd3d9d662009-07-23 18:27:47 +0000946 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000947 // This is valid Water, but would introduce padding. Remember
948 // it in case we don't find any Water that doesn't do this.
949 if (!WaterBBThatWouldPad) {
950 WaterBBThatWouldPad = WaterBB;
951 IPThatWouldPad = IP;
952 }
953 } else {
954 *NewMBB = AcceptWater(WaterBB, IP);
955 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000956 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000957 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000958 if (IP == B)
959 break;
960 }
961 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000962 if (isThumb && WaterBBThatWouldPad) {
963 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
964 return true;
965 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000966 return false;
967}
968
Bob Wilson84945262009-05-12 17:09:30 +0000969/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000970/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
971/// block is used if in range, and the conditional branch munged so control
972/// flow is correct. Otherwise the block is split to create a hole with an
973/// unconditional branch around it. In either case *NewMBB is set to a
974/// block following which the new island can be inserted (the WaterList
975/// is not adjusted).
976
Bob Wilson84945262009-05-12 17:09:30 +0000977void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000978 unsigned UserOffset, MachineBasicBlock** NewMBB) {
979 CPUser &U = CPUsers[CPUserIndex];
980 MachineInstr *UserMI = U.MI;
981 MachineInstr *CPEMI = U.CPEMI;
982 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000983 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000984 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +0000985 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000986
987 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +0000988 // is within range, make new water there. (The addition below is
Evan Chengd3d9d662009-07-23 18:27:47 +0000989 // for the unconditional branch we will be adding: 4 bytes on ARM + Thumb2,
990 // 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +0000991 // inside OffsetIsInRange.
Bob Wilson84945262009-05-12 17:09:30 +0000992 // If the block ends in an unconditional branch already, it is water,
Dale Johannesen8593e412007-04-29 19:19:30 +0000993 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000994 if (&UserMBB->back() == UserMI ||
Evan Chengd3d9d662009-07-23 18:27:47 +0000995 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
996 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000997 DOUT << "Split at end of block\n";
998 if (&UserMBB->back() == UserMI)
999 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1000 *NewMBB = next(MachineFunction::iterator(UserMBB));
1001 // Add an unconditional branch from UserMBB to fallthrough block.
1002 // Record it for branch lengthening; this new branch will not get out of
1003 // range, but if the preceding conditional branch is out of range, the
1004 // targets will be exchanged, and the altered branch may be out of
1005 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001006 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001007 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1008 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001009 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001010 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001011 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001012 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001013 BBSizes[UserMBB->getNumber()] += delta;
1014 AdjustBBOffsetsAfter(UserMBB, delta);
1015 } else {
1016 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001017 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001018 // and constant pool entries are 4 bytes: if instruction I references
1019 // island CPE, and instruction I+1 references CPE', it will
1020 // not work well to put CPE as far forward as possible, since then
1021 // CPE' cannot immediately follow it (that location is 2 bytes
1022 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001023 // a new island. So, we make a first guess, then walk through the
1024 // instructions between the one currently being looked at and the
1025 // possible insertion point, and make sure any other instructions
1026 // that reference CPEs will be able to use the same island area;
1027 // if not, we back up the insertion point.
1028
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001029 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001030 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001031 // island is handled inside OffsetIsInRange.
1032 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001033 // This could point off the end of the block if we've already got
1034 // constant pool entries following this block; only the last one is
1035 // in the water list. Back past any possible branches (allow for a
1036 // conditional and a maximally long unconditional).
1037 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001038 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001039 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001040 unsigned EndInsertOffset = BaseInsertOffset +
1041 CPEMI->getOperand(2).getImm();
1042 MachineBasicBlock::iterator MI = UserMI;
1043 ++MI;
1044 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001045 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001046 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001047 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001048 MI = next(MI)) {
1049 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001050 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001051 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001052 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1053 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1054 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001055 }
1056 // This is overly conservative, as we don't account for CPEMIs
1057 // being reused within the block, but it doesn't matter much.
1058 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1059 CPUIndex++;
1060 }
1061 }
1062 DOUT << "Split in middle of big block\n";
1063 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1064 }
1065}
1066
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001067/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001068/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001069/// place in-range. Return true if we changed any addresses (thus must run
1070/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001071bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001072 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001073 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001074 MachineInstr *UserMI = U.MI;
1075 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001076 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001077 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001078 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001079 // Compute this only once, it's expensive. The 4 or 8 is the value the
Bob Wilson39bf0512009-05-12 17:35:29 +00001080 // hardware keeps in the PC (2 insns ahead of the reference).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001081 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001082
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001083 // See if the current entry is within range, or there is a clone of it
1084 // in range.
1085 int result = LookForExistingCPEntry(U, UserOffset);
1086 if (result==1) return false;
1087 else if (result==2) return true;
1088
1089 // No existing clone of this CPE is within range.
1090 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001091 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001092
1093 // Look for water where we can place this CPE. We look for the farthest one
1094 // away that will work. Forward references only for now (although later
1095 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001096
Dale Johannesen8593e412007-04-29 19:19:30 +00001097 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001098 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001099 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001100 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001101 }
1102
1103 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001104 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1105 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001106
1107 // Update internal data structures to account for the newly inserted MBB.
1108 UpdateForInsertedWaterBlock(NewIsland);
1109
1110 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001111 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001112
1113 // Now that we have an island to add the CPE to, clone the original CPE and
1114 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001115 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1116 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001117 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001118 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001119 NumCPEs++;
1120
Dale Johannesen8593e412007-04-29 19:19:30 +00001121 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001122 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001123 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001124 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001125 // Increase the size of the island block to account for the new entry.
1126 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001127 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001128
Evan Chenga8e29892007-01-19 07:51:42 +00001129 // Finally, change the CPI in the instruction operand to be ID.
1130 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001131 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001132 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001133 break;
1134 }
Bob Wilson84945262009-05-12 17:09:30 +00001135
Evan Chengc99ef082007-02-09 20:54:44 +00001136 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilson84945262009-05-12 17:09:30 +00001137
Evan Chenga8e29892007-01-19 07:51:42 +00001138 return true;
1139}
1140
Evan Chenged884f32007-04-03 23:39:48 +00001141/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1142/// sizes and offsets of impacted basic blocks.
1143void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1144 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001145 unsigned Size = CPEMI->getOperand(2).getImm();
1146 CPEMI->eraseFromParent();
1147 BBSizes[CPEBB->getNumber()] -= Size;
1148 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001149 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001150 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001151 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001152 // empty, so fix this.
1153 // All succeeding offsets have the current size value added in, fix this.
1154 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001155 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001156 BBSizes[CPEBB->getNumber()] = 0;
1157 }
Evan Chenged884f32007-04-03 23:39:48 +00001158 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001159 AdjustBBOffsetsAfter(CPEBB, -Size);
1160 // An island has only one predecessor BB and one successor BB. Check if
1161 // this BB's predecessor jumps directly to this BB's successor. This
1162 // shouldn't happen currently.
1163 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1164 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001165}
1166
1167/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1168/// are zero.
1169bool ARMConstantIslands::RemoveUnusedCPEntries() {
1170 unsigned MadeChange = false;
1171 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1172 std::vector<CPEntry> &CPEs = CPEntries[i];
1173 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1174 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1175 RemoveDeadCPEMI(CPEs[j].CPEMI);
1176 CPEs[j].CPEMI = NULL;
1177 MadeChange = true;
1178 }
1179 }
Bob Wilson84945262009-05-12 17:09:30 +00001180 }
Evan Chenged884f32007-04-03 23:39:48 +00001181 return MadeChange;
1182}
1183
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001184/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001185/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001186bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1187 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001188 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001189 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001190 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001191
Evan Chengc99ef082007-02-09 20:54:44 +00001192 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1193 << " from BB#" << MI->getParent()->getNumber()
1194 << " max delta=" << MaxDisp
Dale Johannesen8593e412007-04-29 19:19:30 +00001195 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1196 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +00001197
Dale Johannesen8593e412007-04-29 19:19:30 +00001198 if (BrOffset <= DestOffset) {
1199 // Branch before the Dest.
1200 if (DestOffset-BrOffset <= MaxDisp)
1201 return true;
1202 } else {
1203 if (BrOffset-DestOffset <= MaxDisp)
1204 return true;
1205 }
1206 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001207}
1208
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001209/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1210/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001211bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001212 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001213 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001214
Evan Chengc0dbec72007-01-31 19:57:44 +00001215 // Check to see if the DestBB is already in-range.
1216 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001217 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001218
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001219 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001220 return FixUpUnconditionalBr(MF, Br);
1221 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001222}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001223
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001224/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1225/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001226/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001227/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001228bool
Evan Cheng5657c012009-07-29 02:18:14 +00001229ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001230 MachineInstr *MI = Br.MI;
1231 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001232 if (!isThumb1)
1233 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001234
1235 // Use BL to implement far jump.
1236 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001237 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001238 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001239 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001240 HasFarJump = true;
1241 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001242
Evan Chengc99ef082007-02-09 20:54:44 +00001243 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001244
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001245 return true;
1246}
1247
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001248/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001249/// far away to fit in its displacement field. It is converted to an inverse
1250/// conditional branch + an unconditional branch to the destination.
1251bool
Evan Cheng5657c012009-07-29 02:18:14 +00001252ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001253 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001254 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001255
Bob Wilson39bf0512009-05-12 17:35:29 +00001256 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001257 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001258 // blt L1
1259 // =>
1260 // bge L2
1261 // b L1
1262 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001263 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001264 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001265 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001266
1267 // If the branch is at the end of its MBB and that has a fall-through block,
1268 // direct the updated conditional branch to the fall-through block. Otherwise,
1269 // split the MBB before the next instruction.
1270 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001271 MachineInstr *BMI = &MBB->back();
1272 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001273
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001274 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001275 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001276 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001277 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001278 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001279 // condition and swap destinations:
1280 // beq L1
1281 // b L2
1282 // =>
1283 // bne L2
1284 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001285 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001286 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001287 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001288 BMI->getOperand(0).setMBB(DestBB);
1289 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001290 MI->getOperand(1).setImm(CC);
1291 return true;
1292 }
1293 }
1294 }
1295
1296 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001297 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001298 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001299 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001300 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001301 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001302 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1303 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001304 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001305 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001306 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001307 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001308
Evan Chengc99ef082007-02-09 20:54:44 +00001309 DOUT << " Insert B to BB#" << DestBB->getNumber()
1310 << " also invert condition and change dest. to BB#"
1311 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001312
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001313 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001314 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001315 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1316 TII->get(MI->getOpcode()))
1317 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001318 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001319 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001320 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001321 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001322 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001323 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001324
1325 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001326 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001327 MI->eraseFromParent();
1328
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001329 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001330 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001331 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001332 return true;
1333}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001334
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001335/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1336/// LR / restores LR to pc.
1337bool ARMConstantIslands::UndoLRSpillRestore() {
1338 bool MadeChange = false;
1339 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1340 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001341 if (MI->getOpcode() == ARM::tPOP_RET &&
1342 MI->getOperand(0).getReg() == ARM::PC &&
1343 MI->getNumExplicitOperands() == 1) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001344 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001345 MI->eraseFromParent();
1346 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001347 }
1348 }
1349 return MadeChange;
1350}
Evan Cheng5657c012009-07-29 02:18:14 +00001351
1352bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1353 bool MadeChange = false;
1354
1355 // FIXME: After the tables are shrunk, can we get rid some of the
1356 // constantpool tables?
1357 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1358 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1359 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1360 MachineInstr *MI = T2JumpTables[i];
1361 const TargetInstrDesc &TID = MI->getDesc();
1362 unsigned NumOps = TID.getNumOperands();
1363 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1364 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1365 unsigned JTI = JTOP.getIndex();
1366 assert(JTI < JT.size());
1367
1368 bool ByteOk = true;
1369 bool HalfWordOk = true;
1370 unsigned JTOffset = GetOffsetOf(MI) + 4;
1371 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1372 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1373 MachineBasicBlock *MBB = JTBBs[j];
1374 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001375 // Negative offset is not ok. FIXME: We should change BB layout to make
1376 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001377 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001378 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001379 unsigned TBHLimit = ((1<<16)-1)*2;
1380 if (STI->isTargetDarwin())
1381 TBHLimit >>= 1; // FIXME: Work around an assembler bug.
1382 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001383 HalfWordOk = false;
1384 if (!ByteOk && !HalfWordOk)
1385 break;
1386 }
1387
1388 if (ByteOk || HalfWordOk) {
1389 MachineBasicBlock *MBB = MI->getParent();
1390 unsigned BaseReg = MI->getOperand(0).getReg();
1391 bool BaseRegKill = MI->getOperand(0).isKill();
1392 if (!BaseRegKill)
1393 continue;
1394 unsigned IdxReg = MI->getOperand(1).getReg();
1395 bool IdxRegKill = MI->getOperand(1).isKill();
1396 MachineBasicBlock::iterator PrevI = MI;
1397 if (PrevI == MBB->begin())
1398 continue;
1399
1400 MachineInstr *AddrMI = --PrevI;
1401 bool OptOk = true;
1402 // Examine the instruction that calculate the jumptable entry address.
1403 // If it's not the one just before the t2BR_JT, we won't delete it, then
1404 // it's not worth doing the optimization.
1405 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1406 const MachineOperand &MO = AddrMI->getOperand(k);
1407 if (!MO.isReg() || !MO.getReg())
1408 continue;
1409 if (MO.isDef() && MO.getReg() != BaseReg) {
1410 OptOk = false;
1411 break;
1412 }
1413 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1414 OptOk = false;
1415 break;
1416 }
1417 }
1418 if (!OptOk)
1419 continue;
1420
1421 // The previous instruction should be a t2LEApcrelJT, we want to delete
1422 // it as well.
1423 MachineInstr *LeaMI = --PrevI;
1424 if (LeaMI->getOpcode() != ARM::t2LEApcrelJT ||
1425 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001426 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001427
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001428 if (!OptOk)
1429 continue;
1430
1431 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1432 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1433 .addReg(IdxReg, getKillRegState(IdxRegKill))
1434 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1435 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1436 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1437 // is 2-byte aligned. For now, asm printer will fix it up.
1438 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1439 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1440 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1441 OrigSize += TII->GetInstSizeInBytes(MI);
1442
1443 AddrMI->eraseFromParent();
1444 LeaMI->eraseFromParent();
1445 MI->eraseFromParent();
1446
1447 int delta = OrigSize - NewSize;
1448 BBSizes[MBB->getNumber()] -= delta;
1449 AdjustBBOffsetsAfter(MBB, -delta);
1450
1451 ++NumTBs;
1452 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001453 }
1454 }
1455
1456 return MadeChange;
1457}