blob: f29247ef0cdee7f2d57f94f525762ea363eef9f8 [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 Chenga1efbbd2009-08-14 00:32:16 +000035STATISTIC(NumCPEs, "Number of constpool entries");
36STATISTIC(NumSplit, "Number of uncond branches inserted");
37STATISTIC(NumCBrFixed, "Number of cond branches fixed");
38STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
39STATISTIC(NumTBs, "Number of table branches generated");
40STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000041STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chenga8e29892007-01-19 07:51:42 +000042
43namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000044 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000045 /// requires constant pool entries to be scattered among the instructions
46 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000047 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000048 /// special instructions.
49 ///
50 /// The terminology used in this pass includes:
51 /// Islands - Clumps of constants placed in the function.
52 /// Water - Potential places where an island could be formed.
53 /// CPE - A constant pool entry that has been placed somewhere, which
54 /// tracks a list of users.
55 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000056 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000057 /// by MBB Number. The two-byte pads required for Thumb alignment are
58 /// counted as part of the following block (i.e., the offset and size for
59 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000060 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000061
Dale Johannesen99c49a42007-02-25 00:47:03 +000062 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000063 /// The two-byte pads required for Thumb alignment are counted as part of
64 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000065 std::vector<unsigned> BBOffsets;
66
Evan Chenga8e29892007-01-19 07:51:42 +000067 /// WaterList - A sorted list of basic blocks where islands could be placed
68 /// (i.e. blocks that don't fall through to the following block, due
69 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000070 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000071
Evan Chenga8e29892007-01-19 07:51:42 +000072 /// CPUser - One user of a constant pool, keeping the machine instruction
73 /// pointer, the constant pool being referenced, and the max displacement
74 /// allowed from the instruction to the CP.
75 struct CPUser {
76 MachineInstr *MI;
77 MachineInstr *CPEMI;
78 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +000079 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +000080 bool IsSoImm;
81 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
82 bool neg, bool soimm)
83 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {}
Evan Chenga8e29892007-01-19 07:51:42 +000084 };
Bob Wilson84945262009-05-12 17:09:30 +000085
Evan Chenga8e29892007-01-19 07:51:42 +000086 /// CPUsers - Keep track of all of the machine instructions that use various
87 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000088 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +000089
Evan Chengc99ef082007-02-09 20:54:44 +000090 /// CPEntry - One per constant pool entry, keeping the machine instruction
91 /// pointer, the constpool index, and the number of CPUser's which
92 /// reference this entry.
93 struct CPEntry {
94 MachineInstr *CPEMI;
95 unsigned CPI;
96 unsigned RefCount;
97 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
98 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
99 };
100
101 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000102 /// instructions. For each original constpool index (i.e. those that
103 /// existed upon entry to this pass), it keeps a vector of entries.
104 /// Original elements are cloned as we go along; the clones are
105 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000106 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000107
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000108 /// ImmBranch - One per immediate branch, keeping the machine instruction
109 /// pointer, conditional or unconditional, the max displacement,
110 /// and (if isCond is true) the corresponding unconditional branch
111 /// opcode.
112 struct ImmBranch {
113 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000114 unsigned MaxDisp : 31;
115 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000116 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000117 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
118 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000119 };
120
Evan Cheng2706f972007-05-16 05:14:06 +0000121 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000122 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000123 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000124
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000125 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
126 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000127 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000128
Evan Cheng5657c012009-07-29 02:18:14 +0000129 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
130 SmallVector<MachineInstr*, 4> T2JumpTables;
131
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000132 /// HasFarJump - True if any far jump instruction has been emitted during
133 /// the branch fix up pass.
134 bool HasFarJump;
135
Evan Chenga8e29892007-01-19 07:51:42 +0000136 const TargetInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000137 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000138 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000139 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000140 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000141 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000142 public:
Devang Patel19974732007-05-03 01:11:54 +0000143 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000144 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000145
Evan Cheng5657c012009-07-29 02:18:14 +0000146 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000147
148 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000149 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000150 }
Bob Wilson84945262009-05-12 17:09:30 +0000151
Evan Chenga8e29892007-01-19 07:51:42 +0000152 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000153 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000154 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000155 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng5657c012009-07-29 02:18:14 +0000156 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000157 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000158 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000159 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000160 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000161 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000162 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilson84945262009-05-12 17:09:30 +0000163 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000164 MachineBasicBlock** NewMBB);
Bob Wilson84945262009-05-12 17:09:30 +0000165 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000166 std::vector<MachineBasicBlock*>::iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000167 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
168 MachineBasicBlock** NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000169 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000170 void RemoveDeadCPEMI(MachineInstr *CPEMI);
171 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000172 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000173 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
174 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000175 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000176 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000177 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000178 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000179 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000180 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
181 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
182 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000183 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000184 bool OptimizeThumb2Instructions(MachineFunction &MF);
185 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000186 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000187
Evan Chenga8e29892007-01-19 07:51:42 +0000188 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000189 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000190 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000191 };
Devang Patel19974732007-05-03 01:11:54 +0000192 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000193}
194
Dale Johannesen8593e412007-04-29 19:19:30 +0000195/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000196void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000197 assert(BBOffsets.size() == BBSizes.size());
198 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
199 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000200 if (!isThumb)
201 return;
202#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000203 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000204 MBBI != E; ++MBBI) {
205 MachineBasicBlock *MBB = MBBI;
206 if (!MBB->empty() &&
207 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
208 unsigned MBBId = MBB->getNumber();
209 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
210 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000211 }
212 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000213#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000214}
215
216/// print block size and offset information - debugging
217void ARMConstantIslands::dumpBBs() {
218 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilson84945262009-05-12 17:09:30 +0000219 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000220 " size " << BBSizes[J] << "\n";
Dale Johannesen8593e412007-04-29 19:19:30 +0000221 }
222}
223
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000224/// createARMConstantIslandPass - returns an instance of the constpool
225/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000226FunctionPass *llvm::createARMConstantIslandPass() {
227 return new ARMConstantIslands();
228}
229
Evan Cheng5657c012009-07-29 02:18:14 +0000230bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
231 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000232
Evan Cheng5657c012009-07-29 02:18:14 +0000233 TII = MF.getTarget().getInstrInfo();
234 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000235 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
236
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000237 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000238 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000239 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000240
241 HasFarJump = false;
242
Evan Chenga8e29892007-01-19 07:51:42 +0000243 // Renumber all of the machine basic blocks in the function, guaranteeing that
244 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000245 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000246
Evan Chengd26b14c2009-07-31 18:28:05 +0000247 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000248 // This is so we can keep exact track of where the alignment padding goes.
249
Evan Chengd26b14c2009-07-31 18:28:05 +0000250 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000251 // aligned.
252 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000253
Evan Chenga8e29892007-01-19 07:51:42 +0000254 // Perform the initial placement of the constant pool entries. To start with,
255 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000256 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000257 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000258 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000259 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000260 AFI->setAlign(2U);
261 }
Bob Wilson84945262009-05-12 17:09:30 +0000262
Evan Chenga8e29892007-01-19 07:51:42 +0000263 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000264 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000265
Evan Chenga8e29892007-01-19 07:51:42 +0000266 // Do the initial scan of the function, building up information about the
267 // sizes of each block, the location of all the water, and finding all of the
268 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000269 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000270 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000271
Evan Chenged884f32007-04-03 23:39:48 +0000272 /// Remove dead constant pool entries.
273 RemoveUnusedCPEntries();
274
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000275 // Iteratively place constant pool entries and fix up branches until there
276 // is no change.
277 bool MadeChange = false;
Evan Chengb6879b22009-08-07 07:35:21 +0000278 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000279 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000280 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000281 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000282 CPChange |= HandleConstantPoolUser(MF, i);
283 if (CPChange && ++NoCPIters > 30)
284 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000285 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000286
287 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000288 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000289 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
290 if (BRChange && ++NoBRIters > 30)
291 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000292 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000293
294 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000295 break;
296 MadeChange = true;
297 }
Evan Chenged884f32007-04-03 23:39:48 +0000298
Evan Chenga1efbbd2009-08-14 00:32:16 +0000299 // Shrink 32-bit Thumb2 branch, load, and store instructions.
300 if (isThumb2)
301 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000302
Dale Johannesen8593e412007-04-29 19:19:30 +0000303 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000304 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000305
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000306 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
307 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000308 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000309 MadeChange |= UndoLRSpillRestore();
310
Evan Chenga8e29892007-01-19 07:51:42 +0000311 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000312 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000313 WaterList.clear();
314 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000315 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000316 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000317 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000318 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000319
320 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000321}
322
323/// DoInitialPlacement - Perform the initial placement of the constant pool
324/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000325void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000326 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000327 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000328 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
329 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000330
Evan Chenga8e29892007-01-19 07:51:42 +0000331 // Add all of the constants from the constant pool to the end block, use an
332 // identity mapping of CPI's to CPE's.
333 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000334 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000335
Evan Cheng5657c012009-07-29 02:18:14 +0000336 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000337 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000338 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000339 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
340 // we would have to pad them out or something so that instructions stay
341 // aligned.
342 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
343 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000344 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000345 .addImm(i).addConstantPoolIndex(i).addImm(Size);
346 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000347
348 // Add a new CPEntry, but no corresponding CPUser yet.
349 std::vector<CPEntry> CPEs;
350 CPEs.push_back(CPEntry(CPEMI, i));
351 CPEntries.push_back(CPEs);
352 NumCPEs++;
353 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000354 }
355}
356
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000357/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000358/// into the block immediately after it.
359static bool BBHasFallthrough(MachineBasicBlock *MBB) {
360 // Get the next machine basic block in the function.
361 MachineFunction::iterator MBBI = MBB;
362 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
363 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000364
Evan Chenga8e29892007-01-19 07:51:42 +0000365 MachineBasicBlock *NextBB = next(MBBI);
366 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
367 E = MBB->succ_end(); I != E; ++I)
368 if (*I == NextBB)
369 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000370
Evan Chenga8e29892007-01-19 07:51:42 +0000371 return false;
372}
373
Evan Chengc99ef082007-02-09 20:54:44 +0000374/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
375/// look up the corresponding CPEntry.
376ARMConstantIslands::CPEntry
377*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
378 const MachineInstr *CPEMI) {
379 std::vector<CPEntry> &CPEs = CPEntries[CPI];
380 // Number of entries per constpool index should be small, just do a
381 // linear search.
382 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
383 if (CPEs[i].CPEMI == CPEMI)
384 return &CPEs[i];
385 }
386 return NULL;
387}
388
Evan Chenga8e29892007-01-19 07:51:42 +0000389/// InitialFunctionScan - Do the initial scan of the function, building up
390/// information about the sizes of each block, the location of all the water,
391/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000392void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000393 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000394 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000395 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000396 MBBI != E; ++MBBI) {
397 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000398
Evan Chenga8e29892007-01-19 07:51:42 +0000399 // If this block doesn't fall through into the next MBB, then this is
400 // 'water' that a constant pool island could be placed.
401 if (!BBHasFallthrough(&MBB))
402 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000403
Evan Chenga8e29892007-01-19 07:51:42 +0000404 unsigned MBBSize = 0;
405 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
406 I != E; ++I) {
407 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000408 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000409
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000410 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000411 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000412 bool isCond = false;
413 unsigned Bits = 0;
414 unsigned Scale = 1;
415 int UOpc = Opc;
416 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000417 default:
418 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000419 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000420 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000421 // be right, functions containing these must be 4-byte aligned.
422 AFI->setAlign(2U);
423 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000424 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000425 MBBSize += 2; // padding
426 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000427 case ARM::t2BR_JT:
428 T2JumpTables.push_back(I);
429 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000430 case ARM::Bcc:
431 isCond = true;
432 UOpc = ARM::B;
433 // Fallthrough
434 case ARM::B:
435 Bits = 24;
436 Scale = 4;
437 break;
438 case ARM::tBcc:
439 isCond = true;
440 UOpc = ARM::tB;
441 Bits = 8;
442 Scale = 2;
443 break;
444 case ARM::tB:
445 Bits = 11;
446 Scale = 2;
447 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000448 case ARM::t2Bcc:
449 isCond = true;
450 UOpc = ARM::t2B;
451 Bits = 20;
452 Scale = 2;
453 break;
454 case ARM::t2B:
455 Bits = 24;
456 Scale = 2;
457 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000458 }
Evan Chengb43216e2007-02-01 10:16:15 +0000459
460 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000461 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000462 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000463 }
464
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000465 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
466 PushPopMIs.push_back(I);
467
Evan Chengd3d9d662009-07-23 18:27:47 +0000468 if (Opc == ARM::CONSTPOOL_ENTRY)
469 continue;
470
Evan Chenga8e29892007-01-19 07:51:42 +0000471 // Scan the instructions for constant pool operands.
472 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000473 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000474 // We found one. The addressing mode tells us the max displacement
475 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000476
Evan Chenga8e29892007-01-19 07:51:42 +0000477 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000478 unsigned Bits = 0;
479 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000480 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000481 bool IsSoImm = false;
482
483 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000484 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000485 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000486 break;
487
488 // Taking the address of a CP entry.
489 case ARM::LEApcrel:
490 // This takes a SoImm, which is 8 bit immediate rotated. We'll
491 // pretend the maximum offset is 255 * 4. Since each instruction
492 // 4 byte wide, this is always correct. We'llc heck for other
493 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000494 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000495 Scale = 4;
496 NegOk = true;
497 IsSoImm = true;
498 break;
499 case ARM::t2LEApcrel:
500 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000501 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000502 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000503 case ARM::tLEApcrel:
504 Bits = 8;
505 Scale = 4;
506 break;
507
508 case ARM::LDR:
509 case ARM::LDRcp:
510 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000511 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000512 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000513 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000514
515 case ARM::tLDRpci:
516 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000517 Bits = 8;
518 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000519 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000520
521 case ARM::FLDD:
522 case ARM::FLDS:
523 Bits = 8;
524 Scale = 4; // +-(offset_8*4)
525 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000526 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000527 }
Evan Chengb43216e2007-02-01 10:16:15 +0000528
Evan Chenga8e29892007-01-19 07:51:42 +0000529 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000530 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000531 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000532 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000533 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000534
535 // Increment corresponding CPEntry reference count.
536 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
537 assert(CPE && "Cannot find a corresponding CPEntry!");
538 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000539
Evan Chenga8e29892007-01-19 07:51:42 +0000540 // Instructions can only use one CP entry, don't bother scanning the
541 // rest of the operands.
542 break;
543 }
544 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000545
Dale Johannesen8593e412007-04-29 19:19:30 +0000546 // In thumb mode, if this block is a constpool island, we may need padding
547 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000548 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000549 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000550 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
551 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000552 MBBSize += 2;
553
Evan Chenga8e29892007-01-19 07:51:42 +0000554 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000555 BBOffsets.push_back(Offset);
556 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000557 }
558}
559
Evan Chenga8e29892007-01-19 07:51:42 +0000560/// GetOffsetOf - Return the current offset of the specified machine instruction
561/// from the start of the function. This offset changes as stuff is moved
562/// around inside the function.
563unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
564 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000565
Evan Chenga8e29892007-01-19 07:51:42 +0000566 // The offset is composed of two things: the sum of the sizes of all MBB's
567 // before this instruction's block, and the offset from the start of the block
568 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000569 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000570
Dale Johannesen8593e412007-04-29 19:19:30 +0000571 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
572 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000573 if (isThumb &&
574 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000575 Offset%4 != 0)
576 Offset += 2;
577
Evan Chenga8e29892007-01-19 07:51:42 +0000578 // Sum instructions before MI in MBB.
579 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
580 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
581 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000582 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000583 }
584}
585
586/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
587/// ID.
588static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
589 const MachineBasicBlock *RHS) {
590 return LHS->getNumber() < RHS->getNumber();
591}
592
593/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
594/// machine function, it upsets all of the block numbers. Renumber the blocks
595/// and update the arrays that parallel this numbering.
596void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
597 // Renumber the MBB's to keep them consequtive.
598 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000599
Evan Chenga8e29892007-01-19 07:51:42 +0000600 // Insert a size into BBSizes to align it properly with the (newly
601 // renumbered) block numbers.
602 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000603
604 // Likewise for BBOffsets.
605 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000606
607 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000608 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000609 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000610 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
611 CompareMBBNumbers);
612 WaterList.insert(IP, NewBB);
613}
614
615
616/// Split the basic block containing MI into two blocks, which are joined by
617/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000618/// account for this change and returns the newly created block.
619MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000620 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000621 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000622
623 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000624 MachineBasicBlock *NewBB =
625 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000626 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000627 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000628
Evan Chenga8e29892007-01-19 07:51:42 +0000629 // Splice the instructions starting with MI over to NewBB.
630 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000631
Evan Chenga8e29892007-01-19 07:51:42 +0000632 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000633 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000634 // There doesn't seem to be meaningful DebugInfo available; this doesn't
635 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000636 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
637 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000638 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000639
Evan Chenga8e29892007-01-19 07:51:42 +0000640 // Update the CFG. All succs of OrigBB are now succs of NewBB.
641 while (!OrigBB->succ_empty()) {
642 MachineBasicBlock *Succ = *OrigBB->succ_begin();
643 OrigBB->removeSuccessor(Succ);
644 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000645
Evan Chenga8e29892007-01-19 07:51:42 +0000646 // This pass should be run after register allocation, so there should be no
647 // PHI nodes to update.
648 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
649 && "PHI nodes should be eliminated by now!");
650 }
Bob Wilson84945262009-05-12 17:09:30 +0000651
Evan Chenga8e29892007-01-19 07:51:42 +0000652 // OrigBB branches to NewBB.
653 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000654
Evan Chenga8e29892007-01-19 07:51:42 +0000655 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000656 // This is almost the same as UpdateForInsertedWaterBlock, except that
657 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000658 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000659
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000660 // Insert a size into BBSizes to align it properly with the (newly
661 // renumbered) block numbers.
662 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000663
Dale Johannesen99c49a42007-02-25 00:47:03 +0000664 // Likewise for BBOffsets.
665 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
666
Bob Wilson84945262009-05-12 17:09:30 +0000667 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000668 // available water after it (but not if it's already there, which happens
669 // when splitting before a conditional branch that is followed by an
670 // unconditional branch - in that case we want to insert NewBB).
671 std::vector<MachineBasicBlock*>::iterator IP =
672 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
673 CompareMBBNumbers);
674 MachineBasicBlock* WaterBB = *IP;
675 if (WaterBB == OrigBB)
676 WaterList.insert(next(IP), NewBB);
677 else
678 WaterList.insert(IP, OrigBB);
679
Dale Johannesen8593e412007-04-29 19:19:30 +0000680 // Figure out how large the first NewMBB is. (It cannot
681 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000682 unsigned NewBBSize = 0;
683 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
684 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000685 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000686
Dale Johannesen99c49a42007-02-25 00:47:03 +0000687 unsigned OrigBBI = OrigBB->getNumber();
688 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000689 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000690 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000691
Evan Chenga8e29892007-01-19 07:51:42 +0000692 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000693 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000694 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000695 BBSizes[OrigBBI] -= NewBBSize - delta;
696
697 // ...and adjust BBOffsets for NewBB accordingly.
698 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
699
700 // All BBOffsets following these blocks must be modified.
701 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000702
703 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000704}
705
Dale Johannesen8593e412007-04-29 19:19:30 +0000706/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000707/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000708/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000709bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000710 unsigned TrialOffset, unsigned MaxDisp,
711 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000712 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
713 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000714 // Effectively, the valid range of displacements is 2 bytes smaller for such
715 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000716 unsigned TotalAdj = 0;
717 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000718 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000719 TotalAdj = 2;
720 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000721 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000722 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000723 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000724 TotalAdj += 2;
725 }
726
727 // In Thumb2 mode, later branch adjustments can shift instructions up and
728 // cause alignment change. In the worst case scenario this can cause the
729 // user's effective address to be subtracted by 2 and the CPE's address to
730 // be plus 2.
731 if (isThumb2 && TotalAdj != 4)
732 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000733
Dale Johannesen99c49a42007-02-25 00:47:03 +0000734 if (UserOffset <= TrialOffset) {
735 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000736 if (TrialOffset - UserOffset <= MaxDisp)
737 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000738 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000739 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000740 if (UserOffset - TrialOffset <= MaxDisp)
741 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000742 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000743 }
744 return false;
745}
746
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000747/// WaterIsInRange - Returns true if a CPE placed after the specified
748/// Water (a basic block) will be in range for the specific MI.
749
750bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000751 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000752 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000753 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000754 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000755
Dale Johannesend959aa42007-04-02 20:31:06 +0000756 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000757 // the offset of the instruction. (Currently applies only to ARM, so
758 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000759 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000760 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000761
Evan Chengd3d9d662009-07-23 18:27:47 +0000762 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000763}
764
765/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000766/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000767bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000768 MachineInstr *CPEMI, unsigned MaxDisp,
769 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000770 unsigned CPEOffset = GetOffsetOf(CPEMI);
771 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000772
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000773 if (DoDump) {
774 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
775 << " max delta=" << MaxDisp
776 << " insn address=" << UserOffset
777 << " CPE address=" << CPEOffset
778 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
779 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000780
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000781 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000782}
783
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000784#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000785/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
786/// unconditionally branches to its only successor.
787static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
788 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
789 return false;
790
791 MachineBasicBlock *Succ = *MBB->succ_begin();
792 MachineBasicBlock *Pred = *MBB->pred_begin();
793 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000794 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
795 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000796 return PredMI->getOperand(0).getMBB() == Succ;
797 return false;
798}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000799#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000800
Bob Wilson84945262009-05-12 17:09:30 +0000801void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000802 int delta) {
803 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000804 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
805 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000806 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000807 // If some existing blocks have padding, adjust the padding as needed, a
808 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000809 if (!isThumb)
810 continue;
811 MachineBasicBlock *MBB = MBBI;
812 if (!MBB->empty()) {
813 // Constant pool entries require padding.
814 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000815 unsigned OldOffset = BBOffsets[i] - delta;
816 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000817 // add new padding
818 BBSizes[i] += 2;
819 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000820 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000821 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000822 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000823 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000824 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000825 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000826 // Thumb1 jump tables require padding. They should be at the end;
827 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000828 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000829 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000830 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
831 unsigned OldMIOffset = NewMIOffset - delta;
832 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000833 // remove existing padding
834 BBSizes[i] -= 2;
835 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000836 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000837 // add new padding
838 BBSizes[i] += 2;
839 delta += 2;
840 }
841 }
842 if (delta==0)
843 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000844 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000845 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000846 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000847}
848
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000849/// DecrementOldEntry - find the constant pool entry with index CPI
850/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000851/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000852/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000853
Evan Chenged884f32007-04-03 23:39:48 +0000854bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000855 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000856 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
857 assert(CPE && "Unexpected!");
858 if (--CPE->RefCount == 0) {
859 RemoveDeadCPEMI(CPEMI);
860 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000861 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000862 return true;
863 }
864 return false;
865}
866
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000867/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
868/// if not, see if an in-range clone of the CPE is in range, and if so,
869/// change the data structures so the user references the clone. Returns:
870/// 0 = no existing entry found
871/// 1 = entry found, and there were no code insertions or deletions
872/// 2 = entry found, and there were code insertions or deletions
873int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
874{
875 MachineInstr *UserMI = U.MI;
876 MachineInstr *CPEMI = U.CPEMI;
877
878 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000879 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Evan Cheng82020102007-07-10 22:00:16 +0000880 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000881 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000882 }
883
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000884 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000885 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000886 std::vector<CPEntry> &CPEs = CPEntries[CPI];
887 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
888 // We already tried this one
889 if (CPEs[i].CPEMI == CPEMI)
890 continue;
891 // Removing CPEs can leave empty entries, skip
892 if (CPEs[i].CPEMI == NULL)
893 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000894 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000895 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
896 // Point the CPUser node to the replacement
897 U.CPEMI = CPEs[i].CPEMI;
898 // Change the CPI in the instruction operand to refer to the clone.
899 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000900 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000901 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000902 break;
903 }
904 // Adjust the refcount of the clone...
905 CPEs[i].RefCount++;
906 // ...and the original. If we didn't remove the old entry, none of the
907 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000908 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000909 }
910 }
911 return 0;
912}
913
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000914/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
915/// the specific unconditional branch instruction.
916static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000917 switch (Opc) {
918 case ARM::tB:
919 return ((1<<10)-1)*2;
920 case ARM::t2B:
921 return ((1<<23)-1)*2;
922 default:
923 break;
924 }
Jim Grosbach764ab522009-08-11 15:33:49 +0000925
David Goodwin5e47a9a2009-06-30 18:04:13 +0000926 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000927}
928
Dale Johannesen8593e412007-04-29 19:19:30 +0000929/// AcceptWater - Small amount of common code factored out of the following.
930
Bob Wilson84945262009-05-12 17:09:30 +0000931MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000932 std::vector<MachineBasicBlock*>::iterator IP) {
933 DOUT << "found water in range\n";
934 // Remove the original WaterList entry; we want subsequent
935 // insertions in this vicinity to go after the one we're
936 // about to insert. This considerably reduces the number
937 // of times we have to move the same CPE more than once.
938 WaterList.erase(IP);
939 // CPE goes before following block (NewMBB).
940 return next(MachineFunction::iterator(WaterBB));
941}
942
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000943/// LookForWater - look for an existing entry in the WaterList in which
944/// we can place the CPE referenced from U so it's within range of U's MI.
945/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000946/// is set to the WaterList entry.
Evan Chengd3d9d662009-07-23 18:27:47 +0000947/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
Dale Johannesen8593e412007-04-29 19:19:30 +0000948/// water that will not introduce padding to water that will; within each
949/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000950bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000951 MachineBasicBlock** NewMBB) {
952 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
953 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000954 if (!WaterList.empty()) {
955 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
Evan Chengd3d9d662009-07-23 18:27:47 +0000956 B = WaterList.begin();; --IP) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000957 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000958 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000959 unsigned WBBId = WaterBB->getNumber();
Dale Johannesen8593e412007-04-29 19:19:30 +0000960 if (isThumb &&
Evan Chengd3d9d662009-07-23 18:27:47 +0000961 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000962 // This is valid Water, but would introduce padding. Remember
963 // it in case we don't find any Water that doesn't do this.
964 if (!WaterBBThatWouldPad) {
965 WaterBBThatWouldPad = WaterBB;
966 IPThatWouldPad = IP;
967 }
968 } else {
969 *NewMBB = AcceptWater(WaterBB, IP);
970 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000971 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000972 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000973 if (IP == B)
974 break;
975 }
976 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000977 if (isThumb && WaterBBThatWouldPad) {
978 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
979 return true;
980 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000981 return false;
982}
983
Bob Wilson84945262009-05-12 17:09:30 +0000984/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000985/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
986/// block is used if in range, and the conditional branch munged so control
987/// flow is correct. Otherwise the block is split to create a hole with an
988/// unconditional branch around it. In either case *NewMBB is set to a
989/// block following which the new island can be inserted (the WaterList
990/// is not adjusted).
991
Bob Wilson84945262009-05-12 17:09:30 +0000992void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000993 unsigned UserOffset, MachineBasicBlock** NewMBB) {
994 CPUser &U = CPUsers[CPUserIndex];
995 MachineInstr *UserMI = U.MI;
996 MachineInstr *CPEMI = U.CPEMI;
997 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000998 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000999 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001000 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001001
1002 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +00001003 // is within range, make new water there. (The addition below is
Evan Chengd3d9d662009-07-23 18:27:47 +00001004 // for the unconditional branch we will be adding: 4 bytes on ARM + Thumb2,
1005 // 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001006 // inside OffsetIsInRange.
Bob Wilson84945262009-05-12 17:09:30 +00001007 // If the block ends in an unconditional branch already, it is water,
Dale Johannesen8593e412007-04-29 19:19:30 +00001008 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001009 if (&UserMBB->back() == UserMI ||
Evan Chengd3d9d662009-07-23 18:27:47 +00001010 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1011 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001012 DOUT << "Split at end of block\n";
1013 if (&UserMBB->back() == UserMI)
1014 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1015 *NewMBB = next(MachineFunction::iterator(UserMBB));
1016 // Add an unconditional branch from UserMBB to fallthrough block.
1017 // Record it for branch lengthening; this new branch will not get out of
1018 // range, but if the preceding conditional branch is out of range, the
1019 // targets will be exchanged, and the altered branch may be out of
1020 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001021 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001022 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1023 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001024 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001025 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001026 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001027 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001028 BBSizes[UserMBB->getNumber()] += delta;
1029 AdjustBBOffsetsAfter(UserMBB, delta);
1030 } else {
1031 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001032 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001033 // and constant pool entries are 4 bytes: if instruction I references
1034 // island CPE, and instruction I+1 references CPE', it will
1035 // not work well to put CPE as far forward as possible, since then
1036 // CPE' cannot immediately follow it (that location is 2 bytes
1037 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001038 // a new island. So, we make a first guess, then walk through the
1039 // instructions between the one currently being looked at and the
1040 // possible insertion point, and make sure any other instructions
1041 // that reference CPEs will be able to use the same island area;
1042 // if not, we back up the insertion point.
1043
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001044 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001045 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001046 // island is handled inside OffsetIsInRange.
1047 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001048 // This could point off the end of the block if we've already got
1049 // constant pool entries following this block; only the last one is
1050 // in the water list. Back past any possible branches (allow for a
1051 // conditional and a maximally long unconditional).
1052 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001053 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001054 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001055 unsigned EndInsertOffset = BaseInsertOffset +
1056 CPEMI->getOperand(2).getImm();
1057 MachineBasicBlock::iterator MI = UserMI;
1058 ++MI;
1059 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001060 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001061 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001062 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001063 MI = next(MI)) {
1064 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001065 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001066 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001067 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1068 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1069 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001070 }
1071 // This is overly conservative, as we don't account for CPEMIs
1072 // being reused within the block, but it doesn't matter much.
1073 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1074 CPUIndex++;
1075 }
1076 }
1077 DOUT << "Split in middle of big block\n";
1078 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1079 }
1080}
1081
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001082/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001083/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001084/// place in-range. Return true if we changed any addresses (thus must run
1085/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001086bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001087 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001088 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001089 MachineInstr *UserMI = U.MI;
1090 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001091 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001092 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001093 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001094 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001095 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001096 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001097
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001098 // See if the current entry is within range, or there is a clone of it
1099 // in range.
1100 int result = LookForExistingCPEntry(U, UserOffset);
1101 if (result==1) return false;
1102 else if (result==2) return true;
1103
1104 // No existing clone of this CPE is within range.
1105 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001106 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001107
1108 // Look for water where we can place this CPE. We look for the farthest one
1109 // away that will work. Forward references only for now (although later
1110 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001111
Dale Johannesen8593e412007-04-29 19:19:30 +00001112 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001113 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001114 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001115 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001116 }
1117
1118 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001119 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1120 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001121
1122 // Update internal data structures to account for the newly inserted MBB.
1123 UpdateForInsertedWaterBlock(NewIsland);
1124
1125 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001126 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001127
1128 // Now that we have an island to add the CPE to, clone the original CPE and
1129 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001130 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1131 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001132 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001133 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001134 NumCPEs++;
1135
Dale Johannesen8593e412007-04-29 19:19:30 +00001136 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001137 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001138 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001139 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001140 // Increase the size of the island block to account for the new entry.
1141 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001142 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001143
Evan Chenga8e29892007-01-19 07:51:42 +00001144 // Finally, change the CPI in the instruction operand to be ID.
1145 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001146 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001147 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001148 break;
1149 }
Bob Wilson84945262009-05-12 17:09:30 +00001150
Evan Chengc99ef082007-02-09 20:54:44 +00001151 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilson84945262009-05-12 17:09:30 +00001152
Evan Chenga8e29892007-01-19 07:51:42 +00001153 return true;
1154}
1155
Evan Chenged884f32007-04-03 23:39:48 +00001156/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1157/// sizes and offsets of impacted basic blocks.
1158void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1159 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001160 unsigned Size = CPEMI->getOperand(2).getImm();
1161 CPEMI->eraseFromParent();
1162 BBSizes[CPEBB->getNumber()] -= Size;
1163 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001164 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001165 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001166 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001167 // empty, so fix this.
1168 // All succeeding offsets have the current size value added in, fix this.
1169 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001170 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001171 BBSizes[CPEBB->getNumber()] = 0;
1172 }
Evan Chenged884f32007-04-03 23:39:48 +00001173 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001174 AdjustBBOffsetsAfter(CPEBB, -Size);
1175 // An island has only one predecessor BB and one successor BB. Check if
1176 // this BB's predecessor jumps directly to this BB's successor. This
1177 // shouldn't happen currently.
1178 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1179 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001180}
1181
1182/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1183/// are zero.
1184bool ARMConstantIslands::RemoveUnusedCPEntries() {
1185 unsigned MadeChange = false;
1186 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1187 std::vector<CPEntry> &CPEs = CPEntries[i];
1188 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1189 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1190 RemoveDeadCPEMI(CPEs[j].CPEMI);
1191 CPEs[j].CPEMI = NULL;
1192 MadeChange = true;
1193 }
1194 }
Bob Wilson84945262009-05-12 17:09:30 +00001195 }
Evan Chenged884f32007-04-03 23:39:48 +00001196 return MadeChange;
1197}
1198
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001199/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001200/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001201bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1202 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001203 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001204 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001205 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001206
Evan Chengc99ef082007-02-09 20:54:44 +00001207 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1208 << " from BB#" << MI->getParent()->getNumber()
1209 << " max delta=" << MaxDisp
Dale Johannesen8593e412007-04-29 19:19:30 +00001210 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1211 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +00001212
Dale Johannesen8593e412007-04-29 19:19:30 +00001213 if (BrOffset <= DestOffset) {
1214 // Branch before the Dest.
1215 if (DestOffset-BrOffset <= MaxDisp)
1216 return true;
1217 } else {
1218 if (BrOffset-DestOffset <= MaxDisp)
1219 return true;
1220 }
1221 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001222}
1223
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001224/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1225/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001226bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001227 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001228 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001229
Evan Chengc0dbec72007-01-31 19:57:44 +00001230 // Check to see if the DestBB is already in-range.
1231 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001232 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001233
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001234 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001235 return FixUpUnconditionalBr(MF, Br);
1236 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001237}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001238
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001239/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1240/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001241/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001242/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001243bool
Evan Cheng5657c012009-07-29 02:18:14 +00001244ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001245 MachineInstr *MI = Br.MI;
1246 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001247 if (!isThumb1)
1248 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001249
1250 // Use BL to implement far jump.
1251 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001252 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001253 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001254 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001255 HasFarJump = true;
1256 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001257
Evan Chengc99ef082007-02-09 20:54:44 +00001258 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001259
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001260 return true;
1261}
1262
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001263/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001264/// far away to fit in its displacement field. It is converted to an inverse
1265/// conditional branch + an unconditional branch to the destination.
1266bool
Evan Cheng5657c012009-07-29 02:18:14 +00001267ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001268 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001269 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001270
Bob Wilson39bf0512009-05-12 17:35:29 +00001271 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001272 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001273 // blt L1
1274 // =>
1275 // bge L2
1276 // b L1
1277 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001278 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001279 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001280 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001281
1282 // If the branch is at the end of its MBB and that has a fall-through block,
1283 // direct the updated conditional branch to the fall-through block. Otherwise,
1284 // split the MBB before the next instruction.
1285 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001286 MachineInstr *BMI = &MBB->back();
1287 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001288
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001289 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001290 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001291 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001292 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001293 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001294 // condition and swap destinations:
1295 // beq L1
1296 // b L2
1297 // =>
1298 // bne L2
1299 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001300 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001301 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001302 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001303 BMI->getOperand(0).setMBB(DestBB);
1304 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001305 MI->getOperand(1).setImm(CC);
1306 return true;
1307 }
1308 }
1309 }
1310
1311 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001312 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001313 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001314 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001315 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001316 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001317 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1318 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001319 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001320 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001321 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001322 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001323
Evan Chengc99ef082007-02-09 20:54:44 +00001324 DOUT << " Insert B to BB#" << DestBB->getNumber()
1325 << " also invert condition and change dest. to BB#"
1326 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001327
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001328 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001329 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001330 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1331 TII->get(MI->getOpcode()))
1332 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001333 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001334 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001335 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001336 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001337 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001338 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001339
1340 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001341 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001342 MI->eraseFromParent();
1343
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001344 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001345 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001346 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001347 return true;
1348}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001349
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001350/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001351/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1352/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001353bool ARMConstantIslands::UndoLRSpillRestore() {
1354 bool MadeChange = false;
1355 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1356 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001357 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng48bd7e32009-08-13 06:05:07 +00001358 MI->getOperand(2).getReg() == ARM::PC &&
1359 MI->getNumExplicitOperands() == 3) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001360 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001361 MI->eraseFromParent();
1362 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001363 }
1364 }
1365 return MadeChange;
1366}
Evan Cheng5657c012009-07-29 02:18:14 +00001367
Evan Chenga1efbbd2009-08-14 00:32:16 +00001368bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1369 bool MadeChange = false;
1370
1371 // Shrink ADR and LDR from constantpool.
1372 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1373 CPUser &U = CPUsers[i];
1374 unsigned Opcode = U.MI->getOpcode();
1375 unsigned NewOpc = 0;
1376 unsigned Scale = 1;
1377 unsigned Bits = 0;
1378 switch (Opcode) {
1379 default: break;
1380 case ARM::t2LEApcrel:
1381 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1382 NewOpc = ARM::tLEApcrel;
1383 Bits = 8;
1384 Scale = 4;
1385 }
1386 break;
1387 case ARM::t2LDRpci:
1388 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1389 NewOpc = ARM::tLDRpci;
1390 Bits = 8;
1391 Scale = 4;
1392 }
1393 break;
1394 }
1395
1396 if (!NewOpc)
1397 continue;
1398
1399 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1400 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1401 // FIXME: Check if offset is multiple of scale if scale is not 4.
1402 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1403 U.MI->setDesc(TII->get(NewOpc));
1404 MachineBasicBlock *MBB = U.MI->getParent();
1405 BBSizes[MBB->getNumber()] -= 2;
1406 AdjustBBOffsetsAfter(MBB, -2);
1407 ++NumT2CPShrunk;
1408 MadeChange = true;
1409 }
1410 }
1411
Evan Chenga1efbbd2009-08-14 00:32:16 +00001412 MadeChange |= OptimizeThumb2Branches(MF);
Evan Cheng31b99dd2009-08-14 18:31:44 +00001413 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001414 return MadeChange;
1415}
1416
1417bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001418 bool MadeChange = false;
1419
1420 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1421 ImmBranch &Br = ImmBranches[i];
1422 unsigned Opcode = Br.MI->getOpcode();
1423 unsigned NewOpc = 0;
1424 unsigned Scale = 1;
1425 unsigned Bits = 0;
1426 switch (Opcode) {
1427 default: break;
1428 case ARM::t2B:
1429 NewOpc = ARM::tB;
1430 Bits = 11;
1431 Scale = 2;
1432 break;
1433 case ARM::t2Bcc:
1434 NewOpc = ARM::tBcc;
1435 Bits = 8;
1436 Scale = 2;
1437 break;
1438 }
1439 if (!NewOpc)
1440 continue;
1441
1442 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1443 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1444 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1445 Br.MI->setDesc(TII->get(NewOpc));
1446 MachineBasicBlock *MBB = Br.MI->getParent();
1447 BBSizes[MBB->getNumber()] -= 2;
1448 AdjustBBOffsetsAfter(MBB, -2);
1449 ++NumT2BrShrunk;
1450 MadeChange = true;
1451 }
1452 }
1453
1454 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001455}
1456
1457
1458/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1459/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001460bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1461 bool MadeChange = false;
1462
1463 // FIXME: After the tables are shrunk, can we get rid some of the
1464 // constantpool tables?
1465 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1466 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1467 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1468 MachineInstr *MI = T2JumpTables[i];
1469 const TargetInstrDesc &TID = MI->getDesc();
1470 unsigned NumOps = TID.getNumOperands();
1471 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1472 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1473 unsigned JTI = JTOP.getIndex();
1474 assert(JTI < JT.size());
1475
1476 bool ByteOk = true;
1477 bool HalfWordOk = true;
1478 unsigned JTOffset = GetOffsetOf(MI) + 4;
1479 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1480 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1481 MachineBasicBlock *MBB = JTBBs[j];
1482 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001483 // Negative offset is not ok. FIXME: We should change BB layout to make
1484 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001485 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001486 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001487 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001488 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001489 HalfWordOk = false;
1490 if (!ByteOk && !HalfWordOk)
1491 break;
1492 }
1493
1494 if (ByteOk || HalfWordOk) {
1495 MachineBasicBlock *MBB = MI->getParent();
1496 unsigned BaseReg = MI->getOperand(0).getReg();
1497 bool BaseRegKill = MI->getOperand(0).isKill();
1498 if (!BaseRegKill)
1499 continue;
1500 unsigned IdxReg = MI->getOperand(1).getReg();
1501 bool IdxRegKill = MI->getOperand(1).isKill();
1502 MachineBasicBlock::iterator PrevI = MI;
1503 if (PrevI == MBB->begin())
1504 continue;
1505
1506 MachineInstr *AddrMI = --PrevI;
1507 bool OptOk = true;
1508 // Examine the instruction that calculate the jumptable entry address.
1509 // If it's not the one just before the t2BR_JT, we won't delete it, then
1510 // it's not worth doing the optimization.
1511 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1512 const MachineOperand &MO = AddrMI->getOperand(k);
1513 if (!MO.isReg() || !MO.getReg())
1514 continue;
1515 if (MO.isDef() && MO.getReg() != BaseReg) {
1516 OptOk = false;
1517 break;
1518 }
1519 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1520 OptOk = false;
1521 break;
1522 }
1523 }
1524 if (!OptOk)
1525 continue;
1526
Evan Chenga1efbbd2009-08-14 00:32:16 +00001527 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1528 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001529 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001530 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1531 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001532 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001533 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001534
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001535 if (!OptOk)
1536 continue;
1537
1538 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1539 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1540 .addReg(IdxReg, getKillRegState(IdxRegKill))
1541 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1542 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1543 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1544 // is 2-byte aligned. For now, asm printer will fix it up.
1545 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1546 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1547 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1548 OrigSize += TII->GetInstSizeInBytes(MI);
1549
1550 AddrMI->eraseFromParent();
1551 LeaMI->eraseFromParent();
1552 MI->eraseFromParent();
1553
1554 int delta = OrigSize - NewSize;
1555 BBSizes[MBB->getNumber()] -= delta;
1556 AdjustBBOffsetsAfter(MBB, -delta);
1557
1558 ++NumTBs;
1559 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001560 }
1561 }
1562
1563 return MadeChange;
1564}