blob: 8f46c6b35c0c67c4f2bfef663ff3e35c37d70803 [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chenga8e29892007-01-19 07:51:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengd3d9d662009-07-23 18:27:47 +000018#include "ARMAddressingModes.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000019#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000020#include "ARMInstrInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000029#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000031#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000034#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000035#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000036using namespace llvm;
37
Evan Chenga1efbbd2009-08-14 00:32:16 +000038STATISTIC(NumCPEs, "Number of constpool entries");
39STATISTIC(NumSplit, "Number of uncond branches inserted");
40STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42STATISTIC(NumTBs, "Number of table branches generated");
43STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000044STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000045STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000046STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000047STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000048
49
50static cl::opt<bool>
51AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(false),
52 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000053
54namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000055 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000056 /// requires constant pool entries to be scattered among the instructions
57 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000058 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000059 /// special instructions.
60 ///
61 /// The terminology used in this pass includes:
62 /// Islands - Clumps of constants placed in the function.
63 /// Water - Potential places where an island could be formed.
64 /// CPE - A constant pool entry that has been placed somewhere, which
65 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000066 class ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000067 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000068 /// by MBB Number. The two-byte pads required for Thumb alignment are
69 /// counted as part of the following block (i.e., the offset and size for
70 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000071 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000072
Dale Johannesen99c49a42007-02-25 00:47:03 +000073 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000074 /// The two-byte pads required for Thumb alignment are counted as part of
75 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000076 std::vector<unsigned> BBOffsets;
77
Evan Chenga8e29892007-01-19 07:51:42 +000078 /// WaterList - A sorted list of basic blocks where islands could be placed
79 /// (i.e. blocks that don't fall through to the following block, due
80 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000081 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000082
Bob Wilsonb9239532009-10-15 20:49:47 +000083 /// NewWaterList - The subset of WaterList that was created since the
84 /// previous iteration by inserting unconditional branches.
85 SmallSet<MachineBasicBlock*, 4> NewWaterList;
86
Bob Wilson034de5f2009-10-12 18:52:13 +000087 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
88
Evan Chenga8e29892007-01-19 07:51:42 +000089 /// CPUser - One user of a constant pool, keeping the machine instruction
90 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +000091 /// allowed from the instruction to the CP. The HighWaterMark records the
92 /// highest basic block where a new CPEntry can be placed. To ensure this
93 /// pass terminates, the CP entries are initially placed at the end of the
94 /// function and then move monotonically to lower addresses. The
95 /// exception to this rule is when the current CP entry for a particular
96 /// CPUser is out of range, but there is another CP entry for the same
97 /// constant value in range. We want to use the existing in-range CP
98 /// entry, but if it later moves out of range, the search for new water
99 /// should resume where it left off. The HighWaterMark is used to record
100 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000101 struct CPUser {
102 MachineInstr *MI;
103 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000104 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000105 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000106 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000107 bool IsSoImm;
108 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
109 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000110 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
111 HighWaterMark = CPEMI->getParent();
112 }
Evan Chenga8e29892007-01-19 07:51:42 +0000113 };
Bob Wilson84945262009-05-12 17:09:30 +0000114
Evan Chenga8e29892007-01-19 07:51:42 +0000115 /// CPUsers - Keep track of all of the machine instructions that use various
116 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000117 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000118
Evan Chengc99ef082007-02-09 20:54:44 +0000119 /// CPEntry - One per constant pool entry, keeping the machine instruction
120 /// pointer, the constpool index, and the number of CPUser's which
121 /// reference this entry.
122 struct CPEntry {
123 MachineInstr *CPEMI;
124 unsigned CPI;
125 unsigned RefCount;
126 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
127 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
128 };
129
130 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000131 /// instructions. For each original constpool index (i.e. those that
132 /// existed upon entry to this pass), it keeps a vector of entries.
133 /// Original elements are cloned as we go along; the clones are
134 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000135 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000136
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000137 /// ImmBranch - One per immediate branch, keeping the machine instruction
138 /// pointer, conditional or unconditional, the max displacement,
139 /// and (if isCond is true) the corresponding unconditional branch
140 /// opcode.
141 struct ImmBranch {
142 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000143 unsigned MaxDisp : 31;
144 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000145 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000146 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
147 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000148 };
149
Evan Cheng2706f972007-05-16 05:14:06 +0000150 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000151 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000152 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000153
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000154 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
155 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000156 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000157
Evan Cheng5657c012009-07-29 02:18:14 +0000158 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
159 SmallVector<MachineInstr*, 4> T2JumpTables;
160
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000161 /// HasFarJump - True if any far jump instruction has been emitted during
162 /// the branch fix up pass.
163 bool HasFarJump;
164
Evan Chenga8e29892007-01-19 07:51:42 +0000165 const TargetInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000166 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000167 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000168 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000169 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000170 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000171 public:
Devang Patel19974732007-05-03 01:11:54 +0000172 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000173 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000174
Evan Cheng5657c012009-07-29 02:18:14 +0000175 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000176
177 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000178 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000179 }
Bob Wilson84945262009-05-12 17:09:30 +0000180
Evan Chenga8e29892007-01-19 07:51:42 +0000181 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000182 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000183 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000184 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jim Grosbach80697d12009-11-12 17:25:07 +0000185 void JumpTableFunctionScan(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000186 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000187 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000188 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000189 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000190 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000191 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000192 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000193 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000194 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000195 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000196 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000197 void RemoveDeadCPEMI(MachineInstr *CPEMI);
198 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000199 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000200 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
201 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000202 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000203 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000204 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000205 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000206 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000207 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
208 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
209 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000210 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000211 bool OptimizeThumb2Instructions(MachineFunction &MF);
212 bool OptimizeThumb2Branches(MachineFunction &MF);
Jim Grosbach80697d12009-11-12 17:25:07 +0000213 bool ReorderThumb2JumpTables(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000214 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000215 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
216 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000217
Evan Chenga8e29892007-01-19 07:51:42 +0000218 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000219 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000220 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000221 };
Devang Patel19974732007-05-03 01:11:54 +0000222 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000223}
224
Dale Johannesen8593e412007-04-29 19:19:30 +0000225/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000226void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000227 assert(BBOffsets.size() == BBSizes.size());
228 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
229 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000230 if (!isThumb)
231 return;
232#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000233 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000234 MBBI != E; ++MBBI) {
235 MachineBasicBlock *MBB = MBBI;
236 if (!MBB->empty() &&
237 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
238 unsigned MBBId = MBB->getNumber();
239 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
240 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000241 }
242 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000243#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000244}
245
246/// print block size and offset information - debugging
247void ARMConstantIslands::dumpBBs() {
248 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000249 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
250 << " size " << BBSizes[J] << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000251 }
252}
253
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000254/// createARMConstantIslandPass - returns an instance of the constpool
255/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000256FunctionPass *llvm::createARMConstantIslandPass() {
257 return new ARMConstantIslands();
258}
259
Evan Cheng5657c012009-07-29 02:18:14 +0000260bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
261 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000262
Evan Cheng5657c012009-07-29 02:18:14 +0000263 TII = MF.getTarget().getInstrInfo();
264 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000265 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
266
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000267 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000268 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000269 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000270
271 HasFarJump = false;
272
Evan Chenga8e29892007-01-19 07:51:42 +0000273 // Renumber all of the machine basic blocks in the function, guaranteeing that
274 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000275 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000276
Jim Grosbach80697d12009-11-12 17:25:07 +0000277 // Try to reorder and otherwise adjust the block layout to make good use
278 // of the TB[BH] instructions.
279 bool MadeChange = false;
280 if (isThumb2 && AdjustJumpTableBlocks) {
281 JumpTableFunctionScan(MF);
282 MadeChange |= ReorderThumb2JumpTables(MF);
283 // Data is out of date, so clear it. It'll be re-computed later.
284 BBSizes.clear();
285 BBOffsets.clear();
286 T2JumpTables.clear();
287 // Blocks may have shifted around. Keep the numbering up to date.
288 MF.RenumberBlocks();
289 }
290
Evan Chengd26b14c2009-07-31 18:28:05 +0000291 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000292 // This is so we can keep exact track of where the alignment padding goes.
293
Evan Chengd26b14c2009-07-31 18:28:05 +0000294 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000295 // aligned.
296 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000297
Evan Chenga8e29892007-01-19 07:51:42 +0000298 // Perform the initial placement of the constant pool entries. To start with,
299 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000300 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000301 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000302 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000303 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000304 AFI->setAlign(2U);
305 }
Bob Wilson84945262009-05-12 17:09:30 +0000306
Evan Chenga8e29892007-01-19 07:51:42 +0000307 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000308 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000309
Evan Chenga8e29892007-01-19 07:51:42 +0000310 // Do the initial scan of the function, building up information about the
311 // sizes of each block, the location of all the water, and finding all of the
312 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000313 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000314 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000315
Evan Chenged884f32007-04-03 23:39:48 +0000316 /// Remove dead constant pool entries.
317 RemoveUnusedCPEntries();
318
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000319 // Iteratively place constant pool entries and fix up branches until there
320 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000321 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000322 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000323 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000324 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000325 CPChange |= HandleConstantPoolUser(MF, i);
326 if (CPChange && ++NoCPIters > 30)
327 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000328 DEBUG(dumpBBs());
Bob Wilsonb9239532009-10-15 20:49:47 +0000329
330 // Clear NewWaterList now. If we split a block for branches, it should
331 // appear as "new water" for the next iteration of constant pool placement.
332 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000333
334 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000335 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000336 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
337 if (BRChange && ++NoBRIters > 30)
338 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000339 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000340
341 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000342 break;
343 MadeChange = true;
344 }
Evan Chenged884f32007-04-03 23:39:48 +0000345
Evan Chenga1efbbd2009-08-14 00:32:16 +0000346 // Shrink 32-bit Thumb2 branch, load, and store instructions.
347 if (isThumb2)
348 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000349
Dale Johannesen8593e412007-04-29 19:19:30 +0000350 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000351 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000352
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000353 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
354 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000355 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000356 MadeChange |= UndoLRSpillRestore();
357
Evan Chenga8e29892007-01-19 07:51:42 +0000358 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000359 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000360 WaterList.clear();
361 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000362 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000363 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000364 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000365 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000366
367 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000368}
369
370/// DoInitialPlacement - Perform the initial placement of the constant pool
371/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000372void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000373 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000374 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000375 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
376 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000377
Evan Chenga8e29892007-01-19 07:51:42 +0000378 // Add all of the constants from the constant pool to the end block, use an
379 // identity mapping of CPI's to CPE's.
380 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000381 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000382
Evan Cheng5657c012009-07-29 02:18:14 +0000383 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000384 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000385 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000386 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
387 // we would have to pad them out or something so that instructions stay
388 // aligned.
389 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
390 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000391 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000392 .addImm(i).addConstantPoolIndex(i).addImm(Size);
393 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000394
395 // Add a new CPEntry, but no corresponding CPUser yet.
396 std::vector<CPEntry> CPEs;
397 CPEs.push_back(CPEntry(CPEMI, i));
398 CPEntries.push_back(CPEs);
399 NumCPEs++;
Chris Lattner893e1c92009-08-23 06:49:22 +0000400 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
401 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000402 }
403}
404
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000405/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000406/// into the block immediately after it.
407static bool BBHasFallthrough(MachineBasicBlock *MBB) {
408 // Get the next machine basic block in the function.
409 MachineFunction::iterator MBBI = MBB;
410 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
411 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000412
Evan Chenga8e29892007-01-19 07:51:42 +0000413 MachineBasicBlock *NextBB = next(MBBI);
414 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
415 E = MBB->succ_end(); I != E; ++I)
416 if (*I == NextBB)
417 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000418
Evan Chenga8e29892007-01-19 07:51:42 +0000419 return false;
420}
421
Evan Chengc99ef082007-02-09 20:54:44 +0000422/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
423/// look up the corresponding CPEntry.
424ARMConstantIslands::CPEntry
425*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
426 const MachineInstr *CPEMI) {
427 std::vector<CPEntry> &CPEs = CPEntries[CPI];
428 // Number of entries per constpool index should be small, just do a
429 // linear search.
430 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
431 if (CPEs[i].CPEMI == CPEMI)
432 return &CPEs[i];
433 }
434 return NULL;
435}
436
Jim Grosbach80697d12009-11-12 17:25:07 +0000437/// JumpTableFunctionScan - Do a scan of the function, building up
438/// information about the sizes of each block and the locations of all
439/// the jump tables.
440void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
441 unsigned Offset = 0;
442 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
443 MBBI != E; ++MBBI) {
444 MachineBasicBlock &MBB = *MBBI;
445
446 unsigned MBBSize = 0;
447 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
448 I != E; ++I) {
449 // Add instruction size to MBBSize.
450 MBBSize += TII->GetInstSizeInBytes(I);
451
452 int Opc = I->getOpcode();
453 if (I->getDesc().isBranch()) {
454 switch (Opc) {
455 default:
456 continue; // Ignore other JT branches
457 case ARM::t2BR_JT:
458 T2JumpTables.push_back(I);
459 continue; // Does not get an entry in ImmBranches
460 }
461 }
462 }
463
464 BBSizes.push_back(MBBSize);
465 BBOffsets.push_back(Offset);
466 Offset += MBBSize;
467 }
468}
469
Evan Chenga8e29892007-01-19 07:51:42 +0000470/// InitialFunctionScan - Do the initial scan of the function, building up
471/// information about the sizes of each block, the location of all the water,
472/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000473void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000474 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000475 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000476 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000477 MBBI != E; ++MBBI) {
478 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000479
Evan Chenga8e29892007-01-19 07:51:42 +0000480 // If this block doesn't fall through into the next MBB, then this is
481 // 'water' that a constant pool island could be placed.
482 if (!BBHasFallthrough(&MBB))
483 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000484
Evan Chenga8e29892007-01-19 07:51:42 +0000485 unsigned MBBSize = 0;
486 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
487 I != E; ++I) {
488 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000489 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000490
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000491 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000492 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000493 bool isCond = false;
494 unsigned Bits = 0;
495 unsigned Scale = 1;
496 int UOpc = Opc;
497 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000498 default:
499 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000500 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000501 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000502 // be right, functions containing these must be 4-byte aligned.
503 AFI->setAlign(2U);
504 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000505 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000506 MBBSize += 2; // padding
507 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000508 case ARM::t2BR_JT:
509 T2JumpTables.push_back(I);
510 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000511 case ARM::Bcc:
512 isCond = true;
513 UOpc = ARM::B;
514 // Fallthrough
515 case ARM::B:
516 Bits = 24;
517 Scale = 4;
518 break;
519 case ARM::tBcc:
520 isCond = true;
521 UOpc = ARM::tB;
522 Bits = 8;
523 Scale = 2;
524 break;
525 case ARM::tB:
526 Bits = 11;
527 Scale = 2;
528 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000529 case ARM::t2Bcc:
530 isCond = true;
531 UOpc = ARM::t2B;
532 Bits = 20;
533 Scale = 2;
534 break;
535 case ARM::t2B:
536 Bits = 24;
537 Scale = 2;
538 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000539 }
Evan Chengb43216e2007-02-01 10:16:15 +0000540
541 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000542 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000543 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000544 }
545
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000546 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
547 PushPopMIs.push_back(I);
548
Evan Chengd3d9d662009-07-23 18:27:47 +0000549 if (Opc == ARM::CONSTPOOL_ENTRY)
550 continue;
551
Evan Chenga8e29892007-01-19 07:51:42 +0000552 // Scan the instructions for constant pool operands.
553 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000554 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000555 // We found one. The addressing mode tells us the max displacement
556 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000557
Evan Chenga8e29892007-01-19 07:51:42 +0000558 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000559 unsigned Bits = 0;
560 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000561 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000562 bool IsSoImm = false;
563
564 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000565 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000566 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000567 break;
568
569 // Taking the address of a CP entry.
570 case ARM::LEApcrel:
571 // This takes a SoImm, which is 8 bit immediate rotated. We'll
572 // pretend the maximum offset is 255 * 4. Since each instruction
573 // 4 byte wide, this is always correct. We'llc heck for other
574 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000575 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000576 Scale = 4;
577 NegOk = true;
578 IsSoImm = true;
579 break;
580 case ARM::t2LEApcrel:
581 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000582 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000583 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000584 case ARM::tLEApcrel:
585 Bits = 8;
586 Scale = 4;
587 break;
588
589 case ARM::LDR:
590 case ARM::LDRcp:
591 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000592 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000593 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000594 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000595
596 case ARM::tLDRpci:
597 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000598 Bits = 8;
599 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000600 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000601
Jim Grosbache5165492009-11-09 00:11:35 +0000602 case ARM::VLDRD:
603 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000604 Bits = 8;
605 Scale = 4; // +-(offset_8*4)
606 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000607 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000608 }
Evan Chengb43216e2007-02-01 10:16:15 +0000609
Evan Chenga8e29892007-01-19 07:51:42 +0000610 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000611 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000612 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000613 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000614 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000615
616 // Increment corresponding CPEntry reference count.
617 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
618 assert(CPE && "Cannot find a corresponding CPEntry!");
619 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000620
Evan Chenga8e29892007-01-19 07:51:42 +0000621 // Instructions can only use one CP entry, don't bother scanning the
622 // rest of the operands.
623 break;
624 }
625 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000626
Dale Johannesen8593e412007-04-29 19:19:30 +0000627 // In thumb mode, if this block is a constpool island, we may need padding
628 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000629 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000630 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000631 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
632 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000633 MBBSize += 2;
634
Evan Chenga8e29892007-01-19 07:51:42 +0000635 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000636 BBOffsets.push_back(Offset);
637 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000638 }
639}
640
Evan Chenga8e29892007-01-19 07:51:42 +0000641/// GetOffsetOf - Return the current offset of the specified machine instruction
642/// from the start of the function. This offset changes as stuff is moved
643/// around inside the function.
644unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
645 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000646
Evan Chenga8e29892007-01-19 07:51:42 +0000647 // The offset is composed of two things: the sum of the sizes of all MBB's
648 // before this instruction's block, and the offset from the start of the block
649 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000650 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000651
Dale Johannesen8593e412007-04-29 19:19:30 +0000652 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
653 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000654 if (isThumb &&
655 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000656 Offset%4 != 0)
657 Offset += 2;
658
Evan Chenga8e29892007-01-19 07:51:42 +0000659 // Sum instructions before MI in MBB.
660 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
661 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
662 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000663 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000664 }
665}
666
667/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
668/// ID.
669static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
670 const MachineBasicBlock *RHS) {
671 return LHS->getNumber() < RHS->getNumber();
672}
673
674/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
675/// machine function, it upsets all of the block numbers. Renumber the blocks
676/// and update the arrays that parallel this numbering.
677void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
678 // Renumber the MBB's to keep them consequtive.
679 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000680
Evan Chenga8e29892007-01-19 07:51:42 +0000681 // Insert a size into BBSizes to align it properly with the (newly
682 // renumbered) block numbers.
683 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000684
685 // Likewise for BBOffsets.
686 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000687
688 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000689 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000690 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000691 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
692 CompareMBBNumbers);
693 WaterList.insert(IP, NewBB);
694}
695
696
697/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000698/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000699/// account for this change and returns the newly created block.
700MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000701 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000702 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000703
704 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000705 MachineBasicBlock *NewBB =
706 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000707 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000708 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000709
Evan Chenga8e29892007-01-19 07:51:42 +0000710 // Splice the instructions starting with MI over to NewBB.
711 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000712
Evan Chenga8e29892007-01-19 07:51:42 +0000713 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000714 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000715 // There doesn't seem to be meaningful DebugInfo available; this doesn't
716 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000717 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
718 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000719 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000720
Evan Chenga8e29892007-01-19 07:51:42 +0000721 // Update the CFG. All succs of OrigBB are now succs of NewBB.
722 while (!OrigBB->succ_empty()) {
723 MachineBasicBlock *Succ = *OrigBB->succ_begin();
724 OrigBB->removeSuccessor(Succ);
725 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000726
Evan Chenga8e29892007-01-19 07:51:42 +0000727 // This pass should be run after register allocation, so there should be no
728 // PHI nodes to update.
729 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
730 && "PHI nodes should be eliminated by now!");
731 }
Bob Wilson84945262009-05-12 17:09:30 +0000732
Evan Chenga8e29892007-01-19 07:51:42 +0000733 // OrigBB branches to NewBB.
734 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000735
Evan Chenga8e29892007-01-19 07:51:42 +0000736 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000737 // This is almost the same as UpdateForInsertedWaterBlock, except that
738 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000739 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000740
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000741 // Insert a size into BBSizes to align it properly with the (newly
742 // renumbered) block numbers.
743 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000744
Dale Johannesen99c49a42007-02-25 00:47:03 +0000745 // Likewise for BBOffsets.
746 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
747
Bob Wilson84945262009-05-12 17:09:30 +0000748 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000749 // available water after it (but not if it's already there, which happens
750 // when splitting before a conditional branch that is followed by an
751 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000752 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000753 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
754 CompareMBBNumbers);
755 MachineBasicBlock* WaterBB = *IP;
756 if (WaterBB == OrigBB)
757 WaterList.insert(next(IP), NewBB);
758 else
759 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000760 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000761
Dale Johannesen8593e412007-04-29 19:19:30 +0000762 // Figure out how large the first NewMBB is. (It cannot
763 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000764 unsigned NewBBSize = 0;
765 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
766 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000767 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000768
Dale Johannesen99c49a42007-02-25 00:47:03 +0000769 unsigned OrigBBI = OrigBB->getNumber();
770 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000771 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000772 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000773
Evan Chenga8e29892007-01-19 07:51:42 +0000774 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000775 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000776 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000777 BBSizes[OrigBBI] -= NewBBSize - delta;
778
779 // ...and adjust BBOffsets for NewBB accordingly.
780 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
781
782 // All BBOffsets following these blocks must be modified.
783 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000784
785 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000786}
787
Dale Johannesen8593e412007-04-29 19:19:30 +0000788/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000789/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000790/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000791bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000792 unsigned TrialOffset, unsigned MaxDisp,
793 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000794 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
795 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000796 // Effectively, the valid range of displacements is 2 bytes smaller for such
797 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000798 unsigned TotalAdj = 0;
799 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000800 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000801 TotalAdj = 2;
802 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000803 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000804 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000805 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000806 TotalAdj += 2;
807 }
808
809 // In Thumb2 mode, later branch adjustments can shift instructions up and
810 // cause alignment change. In the worst case scenario this can cause the
811 // user's effective address to be subtracted by 2 and the CPE's address to
812 // be plus 2.
813 if (isThumb2 && TotalAdj != 4)
814 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000815
Dale Johannesen99c49a42007-02-25 00:47:03 +0000816 if (UserOffset <= TrialOffset) {
817 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000818 if (TrialOffset - UserOffset <= MaxDisp)
819 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000820 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000821 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000822 if (UserOffset - TrialOffset <= MaxDisp)
823 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000824 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000825 }
826 return false;
827}
828
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000829/// WaterIsInRange - Returns true if a CPE placed after the specified
830/// Water (a basic block) will be in range for the specific MI.
831
832bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000833 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000834 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000835 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000836 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000837
Dale Johannesend959aa42007-04-02 20:31:06 +0000838 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000839 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000840 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000841 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000842
Evan Chengd3d9d662009-07-23 18:27:47 +0000843 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000844}
845
846/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000847/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000848bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000849 MachineInstr *CPEMI, unsigned MaxDisp,
850 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000851 unsigned CPEOffset = GetOffsetOf(CPEMI);
852 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000853
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000854 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000855 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
856 << " max delta=" << MaxDisp
857 << " insn address=" << UserOffset
858 << " CPE address=" << CPEOffset
859 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000860 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000861
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000862 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000863}
864
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000865#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000866/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
867/// unconditionally branches to its only successor.
868static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
869 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
870 return false;
871
872 MachineBasicBlock *Succ = *MBB->succ_begin();
873 MachineBasicBlock *Pred = *MBB->pred_begin();
874 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000875 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
876 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000877 return PredMI->getOperand(0).getMBB() == Succ;
878 return false;
879}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000880#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000881
Bob Wilson84945262009-05-12 17:09:30 +0000882void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000883 int delta) {
884 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000885 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
886 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000887 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000888 // If some existing blocks have padding, adjust the padding as needed, a
889 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000890 if (!isThumb)
891 continue;
892 MachineBasicBlock *MBB = MBBI;
893 if (!MBB->empty()) {
894 // Constant pool entries require padding.
895 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000896 unsigned OldOffset = BBOffsets[i] - delta;
897 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000898 // add new padding
899 BBSizes[i] += 2;
900 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000901 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000902 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000903 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000904 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000905 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000906 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000907 // Thumb1 jump tables require padding. They should be at the end;
908 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000909 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000910 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000911 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
912 unsigned OldMIOffset = NewMIOffset - delta;
913 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000914 // remove existing padding
915 BBSizes[i] -= 2;
916 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000917 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000918 // add new padding
919 BBSizes[i] += 2;
920 delta += 2;
921 }
922 }
923 if (delta==0)
924 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000925 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000926 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000927 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000928}
929
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000930/// DecrementOldEntry - find the constant pool entry with index CPI
931/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000932/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000933/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000934
Evan Chenged884f32007-04-03 23:39:48 +0000935bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000936 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000937 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
938 assert(CPE && "Unexpected!");
939 if (--CPE->RefCount == 0) {
940 RemoveDeadCPEMI(CPEMI);
941 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000942 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000943 return true;
944 }
945 return false;
946}
947
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000948/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
949/// if not, see if an in-range clone of the CPE is in range, and if so,
950/// change the data structures so the user references the clone. Returns:
951/// 0 = no existing entry found
952/// 1 = entry found, and there were no code insertions or deletions
953/// 2 = entry found, and there were code insertions or deletions
954int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
955{
956 MachineInstr *UserMI = U.MI;
957 MachineInstr *CPEMI = U.CPEMI;
958
959 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000960 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000961 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000962 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000963 }
964
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000965 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000966 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000967 std::vector<CPEntry> &CPEs = CPEntries[CPI];
968 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
969 // We already tried this one
970 if (CPEs[i].CPEMI == CPEMI)
971 continue;
972 // Removing CPEs can leave empty entries, skip
973 if (CPEs[i].CPEMI == NULL)
974 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000975 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000976 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
977 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000978 // Point the CPUser node to the replacement
979 U.CPEMI = CPEs[i].CPEMI;
980 // Change the CPI in the instruction operand to refer to the clone.
981 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000982 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000983 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000984 break;
985 }
986 // Adjust the refcount of the clone...
987 CPEs[i].RefCount++;
988 // ...and the original. If we didn't remove the old entry, none of the
989 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000990 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000991 }
992 }
993 return 0;
994}
995
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000996/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
997/// the specific unconditional branch instruction.
998static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000999 switch (Opc) {
1000 case ARM::tB:
1001 return ((1<<10)-1)*2;
1002 case ARM::t2B:
1003 return ((1<<23)-1)*2;
1004 default:
1005 break;
1006 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001007
David Goodwin5e47a9a2009-06-30 18:04:13 +00001008 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001009}
1010
Bob Wilsonb9239532009-10-15 20:49:47 +00001011/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001012/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001013/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001014/// is set to the WaterList entry. For Thumb, prefer water that will not
1015/// introduce padding to water that will. To ensure that this pass
1016/// terminates, the CPE location for a particular CPUser is only allowed to
1017/// move to a lower address, so search backward from the end of the list and
1018/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001019bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001020 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001021 if (WaterList.empty())
1022 return false;
1023
Bob Wilson32c50e82009-10-12 20:45:53 +00001024 bool FoundWaterThatWouldPad = false;
1025 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001026 for (water_iterator IP = prior(WaterList.end()),
1027 B = WaterList.begin();; --IP) {
1028 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001029 // Check if water is in range and is either at a lower address than the
1030 // current "high water mark" or a new water block that was created since
1031 // the previous iteration by inserting an unconditional branch. In the
1032 // latter case, we want to allow resetting the high water mark back to
1033 // this new water since we haven't seen it before. Inserting branches
1034 // should be relatively uncommon and when it does happen, we want to be
1035 // sure to take advantage of it for all the CPEs near that block, so that
1036 // we don't insert more branches than necessary.
1037 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1038 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1039 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001040 unsigned WBBId = WaterBB->getNumber();
1041 if (isThumb &&
1042 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
1043 // This is valid Water, but would introduce padding. Remember
1044 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001045 if (!FoundWaterThatWouldPad) {
1046 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001047 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001048 }
Bob Wilson3b757352009-10-12 19:04:03 +00001049 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001050 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001051 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001052 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001053 }
Bob Wilson3b757352009-10-12 19:04:03 +00001054 if (IP == B)
1055 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001056 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001057 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001058 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001059 return true;
1060 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001061 return false;
1062}
1063
Bob Wilson84945262009-05-12 17:09:30 +00001064/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001065/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1066/// block is used if in range, and the conditional branch munged so control
1067/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001068/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001069/// block following which the new island can be inserted (the WaterList
1070/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001071void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001072 unsigned UserOffset,
1073 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001074 CPUser &U = CPUsers[CPUserIndex];
1075 MachineInstr *UserMI = U.MI;
1076 MachineInstr *CPEMI = U.CPEMI;
1077 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001078 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001079 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001080 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001081
Bob Wilson36fa5322009-10-15 05:10:36 +00001082 // If the block does not end in an unconditional branch already, and if the
1083 // end of the block is within range, make new water there. (The addition
1084 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1085 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001086 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001087 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001088 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1089 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001090 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001091 if (&UserMBB->back() == UserMI)
1092 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Bob Wilson757652c2009-10-12 21:39:43 +00001093 NewMBB = next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001094 // Add an unconditional branch from UserMBB to fallthrough block.
1095 // Record it for branch lengthening; this new branch will not get out of
1096 // range, but if the preceding conditional branch is out of range, the
1097 // targets will be exchanged, and the altered branch may be out of
1098 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001099 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001100 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
Bob Wilson757652c2009-10-12 21:39:43 +00001101 TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001102 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001103 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001104 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001105 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001106 BBSizes[UserMBB->getNumber()] += delta;
1107 AdjustBBOffsetsAfter(UserMBB, delta);
1108 } else {
1109 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001110 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001111 // and constant pool entries are 4 bytes: if instruction I references
1112 // island CPE, and instruction I+1 references CPE', it will
1113 // not work well to put CPE as far forward as possible, since then
1114 // CPE' cannot immediately follow it (that location is 2 bytes
1115 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001116 // a new island. So, we make a first guess, then walk through the
1117 // instructions between the one currently being looked at and the
1118 // possible insertion point, and make sure any other instructions
1119 // that reference CPEs will be able to use the same island area;
1120 // if not, we back up the insertion point.
1121
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001122 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001123 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001124 // island is handled inside OffsetIsInRange.
1125 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001126 // This could point off the end of the block if we've already got
1127 // constant pool entries following this block; only the last one is
1128 // in the water list. Back past any possible branches (allow for a
1129 // conditional and a maximally long unconditional).
1130 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001131 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001132 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001133 unsigned EndInsertOffset = BaseInsertOffset +
1134 CPEMI->getOperand(2).getImm();
1135 MachineBasicBlock::iterator MI = UserMI;
1136 ++MI;
1137 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001138 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001139 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001140 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001141 MI = next(MI)) {
1142 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001143 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001144 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001145 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1146 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1147 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001148 }
1149 // This is overly conservative, as we don't account for CPEMIs
1150 // being reused within the block, but it doesn't matter much.
1151 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1152 CPUIndex++;
1153 }
1154 }
Chris Lattner893e1c92009-08-23 06:49:22 +00001155 DEBUG(errs() << "Split in middle of big block\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001156 NewMBB = SplitBlockBeforeInstr(prior(MI));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001157 }
1158}
1159
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001160/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001161/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001162/// place in-range. Return true if we changed any addresses (thus must run
1163/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001164bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001165 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001166 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001167 MachineInstr *UserMI = U.MI;
1168 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001169 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001170 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001171 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001172 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001173 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001174
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001175 // See if the current entry is within range, or there is a clone of it
1176 // in range.
1177 int result = LookForExistingCPEntry(U, UserOffset);
1178 if (result==1) return false;
1179 else if (result==2) return true;
1180
1181 // No existing clone of this CPE is within range.
1182 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001183 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001184
Bob Wilsonf98032e2009-10-12 21:23:15 +00001185 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001186 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1187 MachineBasicBlock *NewMBB;
1188 water_iterator IP;
1189 if (LookForWater(U, UserOffset, IP)) {
1190 DEBUG(errs() << "found water in range\n");
1191 MachineBasicBlock *WaterBB = *IP;
1192
1193 // If the original WaterList entry was "new water" on this iteration,
1194 // propagate that to the new island. This is just keeping NewWaterList
1195 // updated to match the WaterList, which will be updated below.
1196 if (NewWaterList.count(WaterBB)) {
1197 NewWaterList.erase(WaterBB);
1198 NewWaterList.insert(NewIsland);
1199 }
1200 // The new CPE goes before the following block (NewMBB).
1201 NewMBB = next(MachineFunction::iterator(WaterBB));
1202
1203 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001204 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001205 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001206 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001207
1208 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1209 // called while handling branches so that the water will be seen on the
1210 // next iteration for constant pools, but in this context, we don't want
1211 // it. Check for this so it will be removed from the WaterList.
1212 // Also remove any entry from NewWaterList.
1213 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1214 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1215 if (IP != WaterList.end())
1216 NewWaterList.erase(WaterBB);
1217
1218 // We are adding new water. Update NewWaterList.
1219 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001220 }
1221
Bob Wilsonb9239532009-10-15 20:49:47 +00001222 // Remove the original WaterList entry; we want subsequent insertions in
1223 // this vicinity to go after the one we're about to insert. This
1224 // considerably reduces the number of times we have to move the same CPE
1225 // more than once and is also important to ensure the algorithm terminates.
1226 if (IP != WaterList.end())
1227 WaterList.erase(IP);
1228
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001229 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001230 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001231
1232 // Update internal data structures to account for the newly inserted MBB.
1233 UpdateForInsertedWaterBlock(NewIsland);
1234
1235 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001236 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001237
1238 // Now that we have an island to add the CPE to, clone the original CPE and
1239 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001240 U.HighWaterMark = NewIsland;
Dale Johannesenb6728402009-02-13 02:25:56 +00001241 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1242 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001243 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001244 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001245 NumCPEs++;
1246
Dale Johannesen8593e412007-04-29 19:19:30 +00001247 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001248 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001249 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001250 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001251 // Increase the size of the island block to account for the new entry.
1252 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001253 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001254
Evan Chenga8e29892007-01-19 07:51:42 +00001255 // Finally, change the CPI in the instruction operand to be ID.
1256 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001257 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001258 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001259 break;
1260 }
Bob Wilson84945262009-05-12 17:09:30 +00001261
Chris Lattner705e07f2009-08-23 03:41:05 +00001262 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1263 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001264
Evan Chenga8e29892007-01-19 07:51:42 +00001265 return true;
1266}
1267
Evan Chenged884f32007-04-03 23:39:48 +00001268/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1269/// sizes and offsets of impacted basic blocks.
1270void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1271 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001272 unsigned Size = CPEMI->getOperand(2).getImm();
1273 CPEMI->eraseFromParent();
1274 BBSizes[CPEBB->getNumber()] -= Size;
1275 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001276 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001277 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001278 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001279 // empty, so fix this.
1280 // All succeeding offsets have the current size value added in, fix this.
1281 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001282 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001283 BBSizes[CPEBB->getNumber()] = 0;
1284 }
Evan Chenged884f32007-04-03 23:39:48 +00001285 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001286 AdjustBBOffsetsAfter(CPEBB, -Size);
1287 // An island has only one predecessor BB and one successor BB. Check if
1288 // this BB's predecessor jumps directly to this BB's successor. This
1289 // shouldn't happen currently.
1290 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1291 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001292}
1293
1294/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1295/// are zero.
1296bool ARMConstantIslands::RemoveUnusedCPEntries() {
1297 unsigned MadeChange = false;
1298 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1299 std::vector<CPEntry> &CPEs = CPEntries[i];
1300 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1301 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1302 RemoveDeadCPEMI(CPEs[j].CPEMI);
1303 CPEs[j].CPEMI = NULL;
1304 MadeChange = true;
1305 }
1306 }
Bob Wilson84945262009-05-12 17:09:30 +00001307 }
Evan Chenged884f32007-04-03 23:39:48 +00001308 return MadeChange;
1309}
1310
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001311/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001312/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001313bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1314 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001315 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001316 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001317 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001318
Chris Lattner705e07f2009-08-23 03:41:05 +00001319 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1320 << " from BB#" << MI->getParent()->getNumber()
1321 << " max delta=" << MaxDisp
1322 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1323 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001324
Dale Johannesen8593e412007-04-29 19:19:30 +00001325 if (BrOffset <= DestOffset) {
1326 // Branch before the Dest.
1327 if (DestOffset-BrOffset <= MaxDisp)
1328 return true;
1329 } else {
1330 if (BrOffset-DestOffset <= MaxDisp)
1331 return true;
1332 }
1333 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001334}
1335
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001336/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1337/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001338bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001339 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001340 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001341
Evan Chengc0dbec72007-01-31 19:57:44 +00001342 // Check to see if the DestBB is already in-range.
1343 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001344 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001345
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001346 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001347 return FixUpUnconditionalBr(MF, Br);
1348 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001349}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001350
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001351/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1352/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001353/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001354/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001355bool
Evan Cheng5657c012009-07-29 02:18:14 +00001356ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001357 MachineInstr *MI = Br.MI;
1358 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001359 if (!isThumb1)
1360 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001361
1362 // Use BL to implement far jump.
1363 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001364 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001365 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001366 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001367 HasFarJump = true;
1368 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001369
Chris Lattner705e07f2009-08-23 03:41:05 +00001370 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001371
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001372 return true;
1373}
1374
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001375/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001376/// far away to fit in its displacement field. It is converted to an inverse
1377/// conditional branch + an unconditional branch to the destination.
1378bool
Evan Cheng5657c012009-07-29 02:18:14 +00001379ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001380 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001381 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001382
Bob Wilson39bf0512009-05-12 17:35:29 +00001383 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001384 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001385 // blt L1
1386 // =>
1387 // bge L2
1388 // b L1
1389 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001390 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001391 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001392 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001393
1394 // If the branch is at the end of its MBB and that has a fall-through block,
1395 // direct the updated conditional branch to the fall-through block. Otherwise,
1396 // split the MBB before the next instruction.
1397 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001398 MachineInstr *BMI = &MBB->back();
1399 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001400
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001401 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001402 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001403 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001404 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001405 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001406 // condition and swap destinations:
1407 // beq L1
1408 // b L2
1409 // =>
1410 // bne L2
1411 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001412 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001413 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001414 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1415 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001416 BMI->getOperand(0).setMBB(DestBB);
1417 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001418 MI->getOperand(1).setImm(CC);
1419 return true;
1420 }
1421 }
1422 }
1423
1424 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001425 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001426 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001427 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001428 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001429 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001430 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1431 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001432 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001433 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001434 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001435 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001436
Chris Lattner893e1c92009-08-23 06:49:22 +00001437 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1438 << " also invert condition and change dest. to BB#"
1439 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001440
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001441 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001442 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001443 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1444 TII->get(MI->getOpcode()))
1445 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001446 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001447 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001448 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001449 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001450 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001451 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001452
1453 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001454 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001455 MI->eraseFromParent();
1456
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001457 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001458 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001459 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001460 return true;
1461}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001462
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001463/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001464/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1465/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001466bool ARMConstantIslands::UndoLRSpillRestore() {
1467 bool MadeChange = false;
1468 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1469 MachineInstr *MI = PushPopMIs[i];
Evan Cheng10469f82009-10-01 20:54:53 +00001470 // First two operands are predicates, the third is a zero since there
1471 // is no writeback.
Evan Cheng44bec522007-05-15 01:29:07 +00001472 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng10469f82009-10-01 20:54:53 +00001473 MI->getOperand(3).getReg() == ARM::PC &&
1474 MI->getNumExplicitOperands() == 4) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001475 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001476 MI->eraseFromParent();
1477 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001478 }
1479 }
1480 return MadeChange;
1481}
Evan Cheng5657c012009-07-29 02:18:14 +00001482
Evan Chenga1efbbd2009-08-14 00:32:16 +00001483bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1484 bool MadeChange = false;
1485
1486 // Shrink ADR and LDR from constantpool.
1487 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1488 CPUser &U = CPUsers[i];
1489 unsigned Opcode = U.MI->getOpcode();
1490 unsigned NewOpc = 0;
1491 unsigned Scale = 1;
1492 unsigned Bits = 0;
1493 switch (Opcode) {
1494 default: break;
1495 case ARM::t2LEApcrel:
1496 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1497 NewOpc = ARM::tLEApcrel;
1498 Bits = 8;
1499 Scale = 4;
1500 }
1501 break;
1502 case ARM::t2LDRpci:
1503 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1504 NewOpc = ARM::tLDRpci;
1505 Bits = 8;
1506 Scale = 4;
1507 }
1508 break;
1509 }
1510
1511 if (!NewOpc)
1512 continue;
1513
1514 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1515 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1516 // FIXME: Check if offset is multiple of scale if scale is not 4.
1517 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1518 U.MI->setDesc(TII->get(NewOpc));
1519 MachineBasicBlock *MBB = U.MI->getParent();
1520 BBSizes[MBB->getNumber()] -= 2;
1521 AdjustBBOffsetsAfter(MBB, -2);
1522 ++NumT2CPShrunk;
1523 MadeChange = true;
1524 }
1525 }
1526
Evan Chenga1efbbd2009-08-14 00:32:16 +00001527 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001528 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001529 return MadeChange;
1530}
1531
1532bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001533 bool MadeChange = false;
1534
1535 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1536 ImmBranch &Br = ImmBranches[i];
1537 unsigned Opcode = Br.MI->getOpcode();
1538 unsigned NewOpc = 0;
1539 unsigned Scale = 1;
1540 unsigned Bits = 0;
1541 switch (Opcode) {
1542 default: break;
1543 case ARM::t2B:
1544 NewOpc = ARM::tB;
1545 Bits = 11;
1546 Scale = 2;
1547 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001548 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001549 NewOpc = ARM::tBcc;
1550 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001551 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001552 break;
1553 }
Evan Chengde17fb62009-10-31 23:46:45 +00001554 }
1555 if (NewOpc) {
1556 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1557 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1558 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1559 Br.MI->setDesc(TII->get(NewOpc));
1560 MachineBasicBlock *MBB = Br.MI->getParent();
1561 BBSizes[MBB->getNumber()] -= 2;
1562 AdjustBBOffsetsAfter(MBB, -2);
1563 ++NumT2BrShrunk;
1564 MadeChange = true;
1565 }
1566 }
1567
1568 Opcode = Br.MI->getOpcode();
1569 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001570 continue;
1571
Evan Chengde17fb62009-10-31 23:46:45 +00001572 NewOpc = 0;
1573 unsigned PredReg = 0;
1574 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1575 if (Pred == ARMCC::EQ)
1576 NewOpc = ARM::tCBZ;
1577 else if (Pred == ARMCC::NE)
1578 NewOpc = ARM::tCBNZ;
1579 if (!NewOpc)
1580 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001581 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001582 // Check if the distance is within 126. Subtract starting offset by 2
1583 // because the cmp will be eliminated.
1584 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1585 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1586 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1587 MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
1588 if (CmpMI->getOpcode() == ARM::tCMPzi8) {
1589 unsigned Reg = CmpMI->getOperand(0).getReg();
1590 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1591 if (Pred == ARMCC::AL &&
1592 CmpMI->getOperand(1).getImm() == 0 &&
1593 isARMLowRegister(Reg)) {
1594 MachineBasicBlock *MBB = Br.MI->getParent();
1595 MachineInstr *NewBR =
1596 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1597 .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1598 CmpMI->eraseFromParent();
1599 Br.MI->eraseFromParent();
1600 Br.MI = NewBR;
1601 BBSizes[MBB->getNumber()] -= 2;
1602 AdjustBBOffsetsAfter(MBB, -2);
1603 ++NumCBZ;
1604 MadeChange = true;
1605 }
1606 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001607 }
1608 }
1609
1610 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001611}
1612
Evan Chenga1efbbd2009-08-14 00:32:16 +00001613/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1614/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001615bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1616 bool MadeChange = false;
1617
1618 // FIXME: After the tables are shrunk, can we get rid some of the
1619 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001620 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Evan Cheng5657c012009-07-29 02:18:14 +00001621 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1622 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1623 MachineInstr *MI = T2JumpTables[i];
1624 const TargetInstrDesc &TID = MI->getDesc();
1625 unsigned NumOps = TID.getNumOperands();
1626 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1627 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1628 unsigned JTI = JTOP.getIndex();
1629 assert(JTI < JT.size());
1630
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001631 bool ByteOk = true;
1632 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001633 unsigned JTOffset = GetOffsetOf(MI) + 4;
1634 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001635 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1636 MachineBasicBlock *MBB = JTBBs[j];
1637 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001638 // Negative offset is not ok. FIXME: We should change BB layout to make
1639 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001640 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001641 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001642 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001643 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001644 HalfWordOk = false;
1645 if (!ByteOk && !HalfWordOk)
1646 break;
1647 }
1648
1649 if (ByteOk || HalfWordOk) {
1650 MachineBasicBlock *MBB = MI->getParent();
1651 unsigned BaseReg = MI->getOperand(0).getReg();
1652 bool BaseRegKill = MI->getOperand(0).isKill();
1653 if (!BaseRegKill)
1654 continue;
1655 unsigned IdxReg = MI->getOperand(1).getReg();
1656 bool IdxRegKill = MI->getOperand(1).isKill();
1657 MachineBasicBlock::iterator PrevI = MI;
1658 if (PrevI == MBB->begin())
1659 continue;
1660
1661 MachineInstr *AddrMI = --PrevI;
1662 bool OptOk = true;
1663 // Examine the instruction that calculate the jumptable entry address.
1664 // If it's not the one just before the t2BR_JT, we won't delete it, then
1665 // it's not worth doing the optimization.
1666 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1667 const MachineOperand &MO = AddrMI->getOperand(k);
1668 if (!MO.isReg() || !MO.getReg())
1669 continue;
1670 if (MO.isDef() && MO.getReg() != BaseReg) {
1671 OptOk = false;
1672 break;
1673 }
1674 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1675 OptOk = false;
1676 break;
1677 }
1678 }
1679 if (!OptOk)
1680 continue;
1681
Evan Chenga1efbbd2009-08-14 00:32:16 +00001682 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1683 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001684 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001685 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1686 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001687 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001688 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001689
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001690 if (!OptOk)
1691 continue;
1692
1693 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1694 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1695 .addReg(IdxReg, getKillRegState(IdxRegKill))
1696 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1697 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1698 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1699 // is 2-byte aligned. For now, asm printer will fix it up.
1700 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1701 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1702 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1703 OrigSize += TII->GetInstSizeInBytes(MI);
1704
1705 AddrMI->eraseFromParent();
1706 LeaMI->eraseFromParent();
1707 MI->eraseFromParent();
1708
1709 int delta = OrigSize - NewSize;
1710 BBSizes[MBB->getNumber()] -= delta;
1711 AdjustBBOffsetsAfter(MBB, -delta);
1712
1713 ++NumTBs;
1714 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001715 }
1716 }
1717
1718 return MadeChange;
1719}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001720
Jim Grosbach80697d12009-11-12 17:25:07 +00001721/// ReorderThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1722/// jumptables when it's possible.
1723bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1724 bool MadeChange = false;
1725
1726 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1727 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1728 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1729 MachineInstr *MI = T2JumpTables[i];
1730 const TargetInstrDesc &TID = MI->getDesc();
1731 unsigned NumOps = TID.getNumOperands();
1732 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1733 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1734 unsigned JTI = JTOP.getIndex();
1735 assert(JTI < JT.size());
1736
1737 // We prefer if target blocks for the jump table come after the jump
1738 // instruction so we can use TB[BH]. Loop through the target blocks
1739 // and try to adjust them such that that's true.
1740 unsigned JTOffset = GetOffsetOf(MI) + 4;
1741 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1742 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1743 MachineBasicBlock *MBB = JTBBs[j];
1744 unsigned DstOffset = BBOffsets[MBB->getNumber()];
1745
1746 if (DstOffset < JTOffset) {
1747 // The destination precedes the switch. Try to move the block forward
1748 // so we have a positive offset.
1749 MachineBasicBlock *NewBB =
1750 AdjustJTTargetBlockForward(MBB, MI->getParent());
1751 if (NewBB)
1752 MJTI->ReplaceMBBInJumpTables(JTBBs[j], NewBB);
1753 MadeChange = true;
1754 }
1755 }
1756 }
1757
1758 return MadeChange;
1759}
1760
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001761MachineBasicBlock *ARMConstantIslands::
1762AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1763{
1764 MachineFunction &MF = *BB->getParent();
1765
Jim Grosbach80697d12009-11-12 17:25:07 +00001766 // FIXME: If it's a small block terminated by an unconditional branch,
1767 // try to move it; otherwise, create a new block following the jump
1768 // table that branches back to the actual target. This is an overly
1769 // simplistic heuristic here for proof-of-concept.
1770
1771 int BBI = BB->getNumber();
1772 int Size = BBSizes[BBI];
1773 MachineBasicBlock *TBB = 0, *FBB = 0;
1774 SmallVector<MachineOperand, 4> Cond;
1775 // If the block terminator isn't analyzable, don't try to move the block
1776 if (TII->AnalyzeBranch(*BB, TBB, FBB, Cond))
1777 return NULL;
1778
1779 // If the block is small and ends in an unconditional branch, move it.
1780 if (Size < 50 && Cond.empty()) {
1781 MachineFunction::iterator OldPrior = prior(BB);
1782 BB->moveAfter(JTBB);
1783 OldPrior->updateTerminator();
1784 //BB->updateTerminator();
1785 ++NumJTMoved;
1786 return NULL;
1787 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001788
1789 // Create a new MBB for the code after the jump BB.
1790 MachineBasicBlock *NewBB =
1791 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1792 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1793 MF.insert(MBBI, NewBB);
1794
1795 // Add an unconditional branch from NewBB to BB.
1796 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1797 // correspond directly to anything in the source.
1798 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1799 BuildMI(NewBB, DebugLoc::getUnknownLoc(), TII->get(ARM::t2B)).addMBB(BB);
1800
1801 // Update the CFG.
1802 NewBB->addSuccessor(BB);
1803 JTBB->removeSuccessor(BB);
1804 JTBB->addSuccessor(NewBB);
1805
1806 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001807 // This is almost the same as UpdateForInsertedWaterBlock, except that
1808 // the Water goes after OrigBB, not NewBB.
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001809 MF.RenumberBlocks(NewBB);
1810
1811 // Insert a size into BBSizes to align it properly with the (newly
1812 // renumbered) block numbers.
1813 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
1814
1815 // Likewise for BBOffsets.
1816 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
1817
1818 // Figure out how large the first NewMBB is.
1819 unsigned NewBBSize = 0;
1820 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
1821 I != E; ++I)
1822 NewBBSize += TII->GetInstSizeInBytes(I);
1823
1824 unsigned NewBBI = NewBB->getNumber();
1825 unsigned JTBBI = JTBB->getNumber();
1826 // Set the size of NewBB in BBSizes.
1827 BBSizes[NewBBI] = NewBBSize;
1828
1829 // ...and adjust BBOffsets for NewBB accordingly.
1830 BBOffsets[NewBBI] = BBOffsets[JTBBI] + BBSizes[JTBBI];
1831
1832 // All BBOffsets following these blocks must be modified.
1833 AdjustBBOffsetsAfter(NewBB, 4);
1834
Jim Grosbach80697d12009-11-12 17:25:07 +00001835 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001836 return NewBB;
1837}