blob: 9ea9c9c128a6732c970c8db38eb9d4087f70e899 [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");
47
48
49static cl::opt<bool>
50AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(false),
51 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000052
53namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000054 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000055 /// requires constant pool entries to be scattered among the instructions
56 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000057 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000058 /// special instructions.
59 ///
60 /// The terminology used in this pass includes:
61 /// Islands - Clumps of constants placed in the function.
62 /// Water - Potential places where an island could be formed.
63 /// CPE - A constant pool entry that has been placed somewhere, which
64 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000065 class ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000066 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000067 /// by MBB Number. The two-byte pads required for Thumb alignment are
68 /// counted as part of the following block (i.e., the offset and size for
69 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000070 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000071
Dale Johannesen99c49a42007-02-25 00:47:03 +000072 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000073 /// The two-byte pads required for Thumb alignment are counted as part of
74 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000075 std::vector<unsigned> BBOffsets;
76
Evan Chenga8e29892007-01-19 07:51:42 +000077 /// WaterList - A sorted list of basic blocks where islands could be placed
78 /// (i.e. blocks that don't fall through to the following block, due
79 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000080 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000081
Bob Wilsonb9239532009-10-15 20:49:47 +000082 /// NewWaterList - The subset of WaterList that was created since the
83 /// previous iteration by inserting unconditional branches.
84 SmallSet<MachineBasicBlock*, 4> NewWaterList;
85
Bob Wilson034de5f2009-10-12 18:52:13 +000086 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
87
Evan Chenga8e29892007-01-19 07:51:42 +000088 /// CPUser - One user of a constant pool, keeping the machine instruction
89 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +000090 /// allowed from the instruction to the CP. The HighWaterMark records the
91 /// highest basic block where a new CPEntry can be placed. To ensure this
92 /// pass terminates, the CP entries are initially placed at the end of the
93 /// function and then move monotonically to lower addresses. The
94 /// exception to this rule is when the current CP entry for a particular
95 /// CPUser is out of range, but there is another CP entry for the same
96 /// constant value in range. We want to use the existing in-range CP
97 /// entry, but if it later moves out of range, the search for new water
98 /// should resume where it left off. The HighWaterMark is used to record
99 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000100 struct CPUser {
101 MachineInstr *MI;
102 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000103 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000104 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000105 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000106 bool IsSoImm;
107 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
108 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000109 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
110 HighWaterMark = CPEMI->getParent();
111 }
Evan Chenga8e29892007-01-19 07:51:42 +0000112 };
Bob Wilson84945262009-05-12 17:09:30 +0000113
Evan Chenga8e29892007-01-19 07:51:42 +0000114 /// CPUsers - Keep track of all of the machine instructions that use various
115 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000116 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000117
Evan Chengc99ef082007-02-09 20:54:44 +0000118 /// CPEntry - One per constant pool entry, keeping the machine instruction
119 /// pointer, the constpool index, and the number of CPUser's which
120 /// reference this entry.
121 struct CPEntry {
122 MachineInstr *CPEMI;
123 unsigned CPI;
124 unsigned RefCount;
125 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
126 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
127 };
128
129 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000130 /// instructions. For each original constpool index (i.e. those that
131 /// existed upon entry to this pass), it keeps a vector of entries.
132 /// Original elements are cloned as we go along; the clones are
133 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000134 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000135
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000136 /// ImmBranch - One per immediate branch, keeping the machine instruction
137 /// pointer, conditional or unconditional, the max displacement,
138 /// and (if isCond is true) the corresponding unconditional branch
139 /// opcode.
140 struct ImmBranch {
141 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000142 unsigned MaxDisp : 31;
143 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000144 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000145 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
146 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000147 };
148
Evan Cheng2706f972007-05-16 05:14:06 +0000149 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000150 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000151 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000152
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000153 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
154 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000155 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000156
Evan Cheng5657c012009-07-29 02:18:14 +0000157 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
158 SmallVector<MachineInstr*, 4> T2JumpTables;
159
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000160 /// HasFarJump - True if any far jump instruction has been emitted during
161 /// the branch fix up pass.
162 bool HasFarJump;
163
Evan Chenga8e29892007-01-19 07:51:42 +0000164 const TargetInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000165 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000166 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000167 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000168 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000169 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000170 public:
Devang Patel19974732007-05-03 01:11:54 +0000171 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000172 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000173
Evan Cheng5657c012009-07-29 02:18:14 +0000174 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000175
176 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000177 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000178 }
Bob Wilson84945262009-05-12 17:09:30 +0000179
Evan Chenga8e29892007-01-19 07:51:42 +0000180 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000181 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000182 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000183 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng5657c012009-07-29 02:18:14 +0000184 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000185 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000186 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000187 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000188 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000189 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000190 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000191 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000192 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000193 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000194 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000195 void RemoveDeadCPEMI(MachineInstr *CPEMI);
196 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000197 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000198 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
199 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000200 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000201 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000202 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000203 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000204 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000205 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
206 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
207 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000208 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000209 bool OptimizeThumb2Instructions(MachineFunction &MF);
210 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000211 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000212 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
213 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000214
Evan Chenga8e29892007-01-19 07:51:42 +0000215 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000216 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000217 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000218 };
Devang Patel19974732007-05-03 01:11:54 +0000219 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000220}
221
Dale Johannesen8593e412007-04-29 19:19:30 +0000222/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000223void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000224 assert(BBOffsets.size() == BBSizes.size());
225 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
226 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000227 if (!isThumb)
228 return;
229#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000230 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000231 MBBI != E; ++MBBI) {
232 MachineBasicBlock *MBB = MBBI;
233 if (!MBB->empty() &&
234 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
235 unsigned MBBId = MBB->getNumber();
236 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
237 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000238 }
239 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000240#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000241}
242
243/// print block size and offset information - debugging
244void ARMConstantIslands::dumpBBs() {
245 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000246 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
247 << " size " << BBSizes[J] << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000248 }
249}
250
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000251/// createARMConstantIslandPass - returns an instance of the constpool
252/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000253FunctionPass *llvm::createARMConstantIslandPass() {
254 return new ARMConstantIslands();
255}
256
Evan Cheng5657c012009-07-29 02:18:14 +0000257bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
258 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000259
Evan Cheng5657c012009-07-29 02:18:14 +0000260 TII = MF.getTarget().getInstrInfo();
261 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000262 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
263
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000264 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000265 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000266 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000267
268 HasFarJump = false;
269
Evan Chenga8e29892007-01-19 07:51:42 +0000270 // Renumber all of the machine basic blocks in the function, guaranteeing that
271 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000272 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000273
Evan Chengd26b14c2009-07-31 18:28:05 +0000274 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000275 // This is so we can keep exact track of where the alignment padding goes.
276
Evan Chengd26b14c2009-07-31 18:28:05 +0000277 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000278 // aligned.
279 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000280
Evan Chenga8e29892007-01-19 07:51:42 +0000281 // Perform the initial placement of the constant pool entries. To start with,
282 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000283 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000284 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000285 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000286 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000287 AFI->setAlign(2U);
288 }
Bob Wilson84945262009-05-12 17:09:30 +0000289
Evan Chenga8e29892007-01-19 07:51:42 +0000290 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000291 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000292
Evan Chenga8e29892007-01-19 07:51:42 +0000293 // Do the initial scan of the function, building up information about the
294 // sizes of each block, the location of all the water, and finding all of the
295 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000296 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000297 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000298
Evan Chenged884f32007-04-03 23:39:48 +0000299 /// Remove dead constant pool entries.
300 RemoveUnusedCPEntries();
301
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000302 // Iteratively place constant pool entries and fix up branches until there
303 // is no change.
Jim Grosbach01dec0e2009-11-12 03:28:35 +0000304 bool MadeChange = false;
Evan Chengb6879b22009-08-07 07:35:21 +0000305 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000306 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000307 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000308 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000309 CPChange |= HandleConstantPoolUser(MF, i);
310 if (CPChange && ++NoCPIters > 30)
311 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000312 DEBUG(dumpBBs());
Bob Wilsonb9239532009-10-15 20:49:47 +0000313
314 // Clear NewWaterList now. If we split a block for branches, it should
315 // appear as "new water" for the next iteration of constant pool placement.
316 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000317
318 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000319 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000320 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
321 if (BRChange && ++NoBRIters > 30)
322 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000323 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000324
325 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000326 break;
327 MadeChange = true;
328 }
Evan Chenged884f32007-04-03 23:39:48 +0000329
Evan Chenga1efbbd2009-08-14 00:32:16 +0000330 // Shrink 32-bit Thumb2 branch, load, and store instructions.
331 if (isThumb2)
332 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000333
Dale Johannesen8593e412007-04-29 19:19:30 +0000334 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000335 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000336
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000337 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
338 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000339 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000340 MadeChange |= UndoLRSpillRestore();
341
Evan Chenga8e29892007-01-19 07:51:42 +0000342 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000343 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000344 WaterList.clear();
345 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000346 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000347 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000348 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000349 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000350
351 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000352}
353
354/// DoInitialPlacement - Perform the initial placement of the constant pool
355/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000356void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000357 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000358 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000359 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
360 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000361
Evan Chenga8e29892007-01-19 07:51:42 +0000362 // Add all of the constants from the constant pool to the end block, use an
363 // identity mapping of CPI's to CPE's.
364 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000365 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000366
Evan Cheng5657c012009-07-29 02:18:14 +0000367 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000368 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000369 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000370 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
371 // we would have to pad them out or something so that instructions stay
372 // aligned.
373 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
374 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000375 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000376 .addImm(i).addConstantPoolIndex(i).addImm(Size);
377 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000378
379 // Add a new CPEntry, but no corresponding CPUser yet.
380 std::vector<CPEntry> CPEs;
381 CPEs.push_back(CPEntry(CPEMI, i));
382 CPEntries.push_back(CPEs);
383 NumCPEs++;
Chris Lattner893e1c92009-08-23 06:49:22 +0000384 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
385 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000386 }
387}
388
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000389/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000390/// into the block immediately after it.
391static bool BBHasFallthrough(MachineBasicBlock *MBB) {
392 // Get the next machine basic block in the function.
393 MachineFunction::iterator MBBI = MBB;
394 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
395 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000396
Evan Chenga8e29892007-01-19 07:51:42 +0000397 MachineBasicBlock *NextBB = next(MBBI);
398 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
399 E = MBB->succ_end(); I != E; ++I)
400 if (*I == NextBB)
401 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000402
Evan Chenga8e29892007-01-19 07:51:42 +0000403 return false;
404}
405
Evan Chengc99ef082007-02-09 20:54:44 +0000406/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
407/// look up the corresponding CPEntry.
408ARMConstantIslands::CPEntry
409*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
410 const MachineInstr *CPEMI) {
411 std::vector<CPEntry> &CPEs = CPEntries[CPI];
412 // Number of entries per constpool index should be small, just do a
413 // linear search.
414 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
415 if (CPEs[i].CPEMI == CPEMI)
416 return &CPEs[i];
417 }
418 return NULL;
419}
420
Evan Chenga8e29892007-01-19 07:51:42 +0000421/// InitialFunctionScan - Do the initial scan of the function, building up
422/// information about the sizes of each block, the location of all the water,
423/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000424void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000425 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000426 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000427 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000428 MBBI != E; ++MBBI) {
429 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000430
Evan Chenga8e29892007-01-19 07:51:42 +0000431 // If this block doesn't fall through into the next MBB, then this is
432 // 'water' that a constant pool island could be placed.
433 if (!BBHasFallthrough(&MBB))
434 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000435
Evan Chenga8e29892007-01-19 07:51:42 +0000436 unsigned MBBSize = 0;
437 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
438 I != E; ++I) {
439 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000440 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000441
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000442 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000443 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000444 bool isCond = false;
445 unsigned Bits = 0;
446 unsigned Scale = 1;
447 int UOpc = Opc;
448 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000449 default:
450 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000451 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000452 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000453 // be right, functions containing these must be 4-byte aligned.
454 AFI->setAlign(2U);
455 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000456 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000457 MBBSize += 2; // padding
458 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000459 case ARM::t2BR_JT:
460 T2JumpTables.push_back(I);
461 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000462 case ARM::Bcc:
463 isCond = true;
464 UOpc = ARM::B;
465 // Fallthrough
466 case ARM::B:
467 Bits = 24;
468 Scale = 4;
469 break;
470 case ARM::tBcc:
471 isCond = true;
472 UOpc = ARM::tB;
473 Bits = 8;
474 Scale = 2;
475 break;
476 case ARM::tB:
477 Bits = 11;
478 Scale = 2;
479 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000480 case ARM::t2Bcc:
481 isCond = true;
482 UOpc = ARM::t2B;
483 Bits = 20;
484 Scale = 2;
485 break;
486 case ARM::t2B:
487 Bits = 24;
488 Scale = 2;
489 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000490 }
Evan Chengb43216e2007-02-01 10:16:15 +0000491
492 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000493 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000494 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000495 }
496
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000497 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
498 PushPopMIs.push_back(I);
499
Evan Chengd3d9d662009-07-23 18:27:47 +0000500 if (Opc == ARM::CONSTPOOL_ENTRY)
501 continue;
502
Evan Chenga8e29892007-01-19 07:51:42 +0000503 // Scan the instructions for constant pool operands.
504 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000505 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000506 // We found one. The addressing mode tells us the max displacement
507 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000508
Evan Chenga8e29892007-01-19 07:51:42 +0000509 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000510 unsigned Bits = 0;
511 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000512 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000513 bool IsSoImm = false;
514
515 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000516 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000517 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000518 break;
519
520 // Taking the address of a CP entry.
521 case ARM::LEApcrel:
522 // This takes a SoImm, which is 8 bit immediate rotated. We'll
523 // pretend the maximum offset is 255 * 4. Since each instruction
524 // 4 byte wide, this is always correct. We'llc heck for other
525 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000526 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000527 Scale = 4;
528 NegOk = true;
529 IsSoImm = true;
530 break;
531 case ARM::t2LEApcrel:
532 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000533 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000534 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000535 case ARM::tLEApcrel:
536 Bits = 8;
537 Scale = 4;
538 break;
539
540 case ARM::LDR:
541 case ARM::LDRcp:
542 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000543 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000544 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000545 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000546
547 case ARM::tLDRpci:
548 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000549 Bits = 8;
550 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000551 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000552
Jim Grosbache5165492009-11-09 00:11:35 +0000553 case ARM::VLDRD:
554 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000555 Bits = 8;
556 Scale = 4; // +-(offset_8*4)
557 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000558 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000559 }
Evan Chengb43216e2007-02-01 10:16:15 +0000560
Evan Chenga8e29892007-01-19 07:51:42 +0000561 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000562 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000563 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000564 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000565 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000566
567 // Increment corresponding CPEntry reference count.
568 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
569 assert(CPE && "Cannot find a corresponding CPEntry!");
570 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000571
Evan Chenga8e29892007-01-19 07:51:42 +0000572 // Instructions can only use one CP entry, don't bother scanning the
573 // rest of the operands.
574 break;
575 }
576 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000577
Dale Johannesen8593e412007-04-29 19:19:30 +0000578 // In thumb mode, if this block is a constpool island, we may need padding
579 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000580 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000581 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000582 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
583 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000584 MBBSize += 2;
585
Evan Chenga8e29892007-01-19 07:51:42 +0000586 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000587 BBOffsets.push_back(Offset);
588 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000589 }
590}
591
Evan Chenga8e29892007-01-19 07:51:42 +0000592/// GetOffsetOf - Return the current offset of the specified machine instruction
593/// from the start of the function. This offset changes as stuff is moved
594/// around inside the function.
595unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
596 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000597
Evan Chenga8e29892007-01-19 07:51:42 +0000598 // The offset is composed of two things: the sum of the sizes of all MBB's
599 // before this instruction's block, and the offset from the start of the block
600 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000601 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000602
Dale Johannesen8593e412007-04-29 19:19:30 +0000603 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
604 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000605 if (isThumb &&
606 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000607 Offset%4 != 0)
608 Offset += 2;
609
Evan Chenga8e29892007-01-19 07:51:42 +0000610 // Sum instructions before MI in MBB.
611 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
612 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
613 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000614 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000615 }
616}
617
618/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
619/// ID.
620static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
621 const MachineBasicBlock *RHS) {
622 return LHS->getNumber() < RHS->getNumber();
623}
624
625/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
626/// machine function, it upsets all of the block numbers. Renumber the blocks
627/// and update the arrays that parallel this numbering.
628void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
629 // Renumber the MBB's to keep them consequtive.
630 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000631
Evan Chenga8e29892007-01-19 07:51:42 +0000632 // Insert a size into BBSizes to align it properly with the (newly
633 // renumbered) block numbers.
634 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000635
636 // Likewise for BBOffsets.
637 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000638
639 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000640 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000641 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000642 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
643 CompareMBBNumbers);
644 WaterList.insert(IP, NewBB);
645}
646
647
648/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000649/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000650/// account for this change and returns the newly created block.
651MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000652 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000653 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000654
655 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000656 MachineBasicBlock *NewBB =
657 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000658 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000659 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000660
Evan Chenga8e29892007-01-19 07:51:42 +0000661 // Splice the instructions starting with MI over to NewBB.
662 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000663
Evan Chenga8e29892007-01-19 07:51:42 +0000664 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000665 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000666 // There doesn't seem to be meaningful DebugInfo available; this doesn't
667 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000668 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
669 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000670 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000671
Evan Chenga8e29892007-01-19 07:51:42 +0000672 // Update the CFG. All succs of OrigBB are now succs of NewBB.
673 while (!OrigBB->succ_empty()) {
674 MachineBasicBlock *Succ = *OrigBB->succ_begin();
675 OrigBB->removeSuccessor(Succ);
676 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000677
Evan Chenga8e29892007-01-19 07:51:42 +0000678 // This pass should be run after register allocation, so there should be no
679 // PHI nodes to update.
680 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
681 && "PHI nodes should be eliminated by now!");
682 }
Bob Wilson84945262009-05-12 17:09:30 +0000683
Evan Chenga8e29892007-01-19 07:51:42 +0000684 // OrigBB branches to NewBB.
685 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000686
Evan Chenga8e29892007-01-19 07:51:42 +0000687 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000688 // This is almost the same as UpdateForInsertedWaterBlock, except that
689 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000690 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000691
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000692 // Insert a size into BBSizes to align it properly with the (newly
693 // renumbered) block numbers.
694 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000695
Dale Johannesen99c49a42007-02-25 00:47:03 +0000696 // Likewise for BBOffsets.
697 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
698
Bob Wilson84945262009-05-12 17:09:30 +0000699 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000700 // available water after it (but not if it's already there, which happens
701 // when splitting before a conditional branch that is followed by an
702 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000703 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000704 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
705 CompareMBBNumbers);
706 MachineBasicBlock* WaterBB = *IP;
707 if (WaterBB == OrigBB)
708 WaterList.insert(next(IP), NewBB);
709 else
710 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000711 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000712
Dale Johannesen8593e412007-04-29 19:19:30 +0000713 // Figure out how large the first NewMBB is. (It cannot
714 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000715 unsigned NewBBSize = 0;
716 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
717 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000718 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000719
Dale Johannesen99c49a42007-02-25 00:47:03 +0000720 unsigned OrigBBI = OrigBB->getNumber();
721 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000722 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000723 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000724
Evan Chenga8e29892007-01-19 07:51:42 +0000725 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000726 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000727 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000728 BBSizes[OrigBBI] -= NewBBSize - delta;
729
730 // ...and adjust BBOffsets for NewBB accordingly.
731 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
732
733 // All BBOffsets following these blocks must be modified.
734 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000735
736 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000737}
738
Dale Johannesen8593e412007-04-29 19:19:30 +0000739/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000740/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000741/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000742bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000743 unsigned TrialOffset, unsigned MaxDisp,
744 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000745 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
746 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000747 // Effectively, the valid range of displacements is 2 bytes smaller for such
748 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000749 unsigned TotalAdj = 0;
750 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000751 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000752 TotalAdj = 2;
753 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000754 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000755 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000756 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000757 TotalAdj += 2;
758 }
759
760 // In Thumb2 mode, later branch adjustments can shift instructions up and
761 // cause alignment change. In the worst case scenario this can cause the
762 // user's effective address to be subtracted by 2 and the CPE's address to
763 // be plus 2.
764 if (isThumb2 && TotalAdj != 4)
765 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000766
Dale Johannesen99c49a42007-02-25 00:47:03 +0000767 if (UserOffset <= TrialOffset) {
768 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000769 if (TrialOffset - UserOffset <= MaxDisp)
770 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000771 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000772 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000773 if (UserOffset - TrialOffset <= MaxDisp)
774 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000775 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000776 }
777 return false;
778}
779
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000780/// WaterIsInRange - Returns true if a CPE placed after the specified
781/// Water (a basic block) will be in range for the specific MI.
782
783bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000784 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000785 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000786 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000787 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000788
Dale Johannesend959aa42007-04-02 20:31:06 +0000789 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000790 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000791 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000792 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000793
Evan Chengd3d9d662009-07-23 18:27:47 +0000794 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000795}
796
797/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000798/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000799bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000800 MachineInstr *CPEMI, unsigned MaxDisp,
801 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000802 unsigned CPEOffset = GetOffsetOf(CPEMI);
803 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000804
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000805 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000806 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
807 << " max delta=" << MaxDisp
808 << " insn address=" << UserOffset
809 << " CPE address=" << CPEOffset
810 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000811 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000812
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000813 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000814}
815
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000816#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000817/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
818/// unconditionally branches to its only successor.
819static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
820 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
821 return false;
822
823 MachineBasicBlock *Succ = *MBB->succ_begin();
824 MachineBasicBlock *Pred = *MBB->pred_begin();
825 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000826 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
827 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000828 return PredMI->getOperand(0).getMBB() == Succ;
829 return false;
830}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000831#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000832
Bob Wilson84945262009-05-12 17:09:30 +0000833void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000834 int delta) {
835 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000836 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
837 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000838 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000839 // If some existing blocks have padding, adjust the padding as needed, a
840 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000841 if (!isThumb)
842 continue;
843 MachineBasicBlock *MBB = MBBI;
844 if (!MBB->empty()) {
845 // Constant pool entries require padding.
846 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000847 unsigned OldOffset = BBOffsets[i] - delta;
848 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000849 // add new padding
850 BBSizes[i] += 2;
851 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000852 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000853 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000854 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000855 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000856 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000857 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000858 // Thumb1 jump tables require padding. They should be at the end;
859 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000860 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000861 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000862 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
863 unsigned OldMIOffset = NewMIOffset - delta;
864 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000865 // remove existing padding
866 BBSizes[i] -= 2;
867 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000868 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000869 // add new padding
870 BBSizes[i] += 2;
871 delta += 2;
872 }
873 }
874 if (delta==0)
875 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000876 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000877 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000878 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000879}
880
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000881/// DecrementOldEntry - find the constant pool entry with index CPI
882/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000883/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000884/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000885
Evan Chenged884f32007-04-03 23:39:48 +0000886bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000887 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000888 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
889 assert(CPE && "Unexpected!");
890 if (--CPE->RefCount == 0) {
891 RemoveDeadCPEMI(CPEMI);
892 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000893 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000894 return true;
895 }
896 return false;
897}
898
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000899/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
900/// if not, see if an in-range clone of the CPE is in range, and if so,
901/// change the data structures so the user references the clone. Returns:
902/// 0 = no existing entry found
903/// 1 = entry found, and there were no code insertions or deletions
904/// 2 = entry found, and there were code insertions or deletions
905int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
906{
907 MachineInstr *UserMI = U.MI;
908 MachineInstr *CPEMI = U.CPEMI;
909
910 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000911 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000912 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000913 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000914 }
915
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000916 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000917 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000918 std::vector<CPEntry> &CPEs = CPEntries[CPI];
919 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
920 // We already tried this one
921 if (CPEs[i].CPEMI == CPEMI)
922 continue;
923 // Removing CPEs can leave empty entries, skip
924 if (CPEs[i].CPEMI == NULL)
925 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000926 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000927 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
928 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000929 // Point the CPUser node to the replacement
930 U.CPEMI = CPEs[i].CPEMI;
931 // Change the CPI in the instruction operand to refer to the clone.
932 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000933 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000934 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000935 break;
936 }
937 // Adjust the refcount of the clone...
938 CPEs[i].RefCount++;
939 // ...and the original. If we didn't remove the old entry, none of the
940 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000941 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000942 }
943 }
944 return 0;
945}
946
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000947/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
948/// the specific unconditional branch instruction.
949static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000950 switch (Opc) {
951 case ARM::tB:
952 return ((1<<10)-1)*2;
953 case ARM::t2B:
954 return ((1<<23)-1)*2;
955 default:
956 break;
957 }
Jim Grosbach764ab522009-08-11 15:33:49 +0000958
David Goodwin5e47a9a2009-06-30 18:04:13 +0000959 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000960}
961
Bob Wilsonb9239532009-10-15 20:49:47 +0000962/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000963/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +0000964/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +0000965/// is set to the WaterList entry. For Thumb, prefer water that will not
966/// introduce padding to water that will. To ensure that this pass
967/// terminates, the CPE location for a particular CPUser is only allowed to
968/// move to a lower address, so search backward from the end of the list and
969/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000970bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +0000971 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +0000972 if (WaterList.empty())
973 return false;
974
Bob Wilson32c50e82009-10-12 20:45:53 +0000975 bool FoundWaterThatWouldPad = false;
976 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +0000977 for (water_iterator IP = prior(WaterList.end()),
978 B = WaterList.begin();; --IP) {
979 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +0000980 // Check if water is in range and is either at a lower address than the
981 // current "high water mark" or a new water block that was created since
982 // the previous iteration by inserting an unconditional branch. In the
983 // latter case, we want to allow resetting the high water mark back to
984 // this new water since we haven't seen it before. Inserting branches
985 // should be relatively uncommon and when it does happen, we want to be
986 // sure to take advantage of it for all the CPEs near that block, so that
987 // we don't insert more branches than necessary.
988 if (WaterIsInRange(UserOffset, WaterBB, U) &&
989 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
990 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +0000991 unsigned WBBId = WaterBB->getNumber();
992 if (isThumb &&
993 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
994 // This is valid Water, but would introduce padding. Remember
995 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +0000996 if (!FoundWaterThatWouldPad) {
997 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +0000998 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000999 }
Bob Wilson3b757352009-10-12 19:04:03 +00001000 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001001 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001002 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001003 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001004 }
Bob Wilson3b757352009-10-12 19:04:03 +00001005 if (IP == B)
1006 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001007 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001008 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001009 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001010 return true;
1011 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001012 return false;
1013}
1014
Bob Wilson84945262009-05-12 17:09:30 +00001015/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001016/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1017/// block is used if in range, and the conditional branch munged so control
1018/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001019/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001020/// block following which the new island can be inserted (the WaterList
1021/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001022void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001023 unsigned UserOffset,
1024 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001025 CPUser &U = CPUsers[CPUserIndex];
1026 MachineInstr *UserMI = U.MI;
1027 MachineInstr *CPEMI = U.CPEMI;
1028 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001029 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001030 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001031 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001032
Bob Wilson36fa5322009-10-15 05:10:36 +00001033 // If the block does not end in an unconditional branch already, and if the
1034 // end of the block is within range, make new water there. (The addition
1035 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1036 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001037 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001038 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001039 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1040 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001041 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001042 if (&UserMBB->back() == UserMI)
1043 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Bob Wilson757652c2009-10-12 21:39:43 +00001044 NewMBB = next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001045 // Add an unconditional branch from UserMBB to fallthrough block.
1046 // Record it for branch lengthening; this new branch will not get out of
1047 // range, but if the preceding conditional branch is out of range, the
1048 // targets will be exchanged, and the altered branch may be out of
1049 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001050 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001051 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
Bob Wilson757652c2009-10-12 21:39:43 +00001052 TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001053 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001054 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001055 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001056 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001057 BBSizes[UserMBB->getNumber()] += delta;
1058 AdjustBBOffsetsAfter(UserMBB, delta);
1059 } else {
1060 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001061 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001062 // and constant pool entries are 4 bytes: if instruction I references
1063 // island CPE, and instruction I+1 references CPE', it will
1064 // not work well to put CPE as far forward as possible, since then
1065 // CPE' cannot immediately follow it (that location is 2 bytes
1066 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001067 // a new island. So, we make a first guess, then walk through the
1068 // instructions between the one currently being looked at and the
1069 // possible insertion point, and make sure any other instructions
1070 // that reference CPEs will be able to use the same island area;
1071 // if not, we back up the insertion point.
1072
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001073 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001074 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001075 // island is handled inside OffsetIsInRange.
1076 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001077 // This could point off the end of the block if we've already got
1078 // constant pool entries following this block; only the last one is
1079 // in the water list. Back past any possible branches (allow for a
1080 // conditional and a maximally long unconditional).
1081 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001082 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001083 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001084 unsigned EndInsertOffset = BaseInsertOffset +
1085 CPEMI->getOperand(2).getImm();
1086 MachineBasicBlock::iterator MI = UserMI;
1087 ++MI;
1088 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001089 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001090 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001091 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001092 MI = next(MI)) {
1093 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001094 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001095 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001096 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1097 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1098 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001099 }
1100 // This is overly conservative, as we don't account for CPEMIs
1101 // being reused within the block, but it doesn't matter much.
1102 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1103 CPUIndex++;
1104 }
1105 }
Chris Lattner893e1c92009-08-23 06:49:22 +00001106 DEBUG(errs() << "Split in middle of big block\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001107 NewMBB = SplitBlockBeforeInstr(prior(MI));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001108 }
1109}
1110
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001111/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001112/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001113/// place in-range. Return true if we changed any addresses (thus must run
1114/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001115bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001116 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001117 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001118 MachineInstr *UserMI = U.MI;
1119 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001120 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001121 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001122 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001123 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001124 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001125
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001126 // See if the current entry is within range, or there is a clone of it
1127 // in range.
1128 int result = LookForExistingCPEntry(U, UserOffset);
1129 if (result==1) return false;
1130 else if (result==2) return true;
1131
1132 // No existing clone of this CPE is within range.
1133 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001134 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001135
Bob Wilsonf98032e2009-10-12 21:23:15 +00001136 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001137 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1138 MachineBasicBlock *NewMBB;
1139 water_iterator IP;
1140 if (LookForWater(U, UserOffset, IP)) {
1141 DEBUG(errs() << "found water in range\n");
1142 MachineBasicBlock *WaterBB = *IP;
1143
1144 // If the original WaterList entry was "new water" on this iteration,
1145 // propagate that to the new island. This is just keeping NewWaterList
1146 // updated to match the WaterList, which will be updated below.
1147 if (NewWaterList.count(WaterBB)) {
1148 NewWaterList.erase(WaterBB);
1149 NewWaterList.insert(NewIsland);
1150 }
1151 // The new CPE goes before the following block (NewMBB).
1152 NewMBB = next(MachineFunction::iterator(WaterBB));
1153
1154 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001155 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001156 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001157 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001158
1159 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1160 // called while handling branches so that the water will be seen on the
1161 // next iteration for constant pools, but in this context, we don't want
1162 // it. Check for this so it will be removed from the WaterList.
1163 // Also remove any entry from NewWaterList.
1164 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1165 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1166 if (IP != WaterList.end())
1167 NewWaterList.erase(WaterBB);
1168
1169 // We are adding new water. Update NewWaterList.
1170 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001171 }
1172
Bob Wilsonb9239532009-10-15 20:49:47 +00001173 // Remove the original WaterList entry; we want subsequent insertions in
1174 // this vicinity to go after the one we're about to insert. This
1175 // considerably reduces the number of times we have to move the same CPE
1176 // more than once and is also important to ensure the algorithm terminates.
1177 if (IP != WaterList.end())
1178 WaterList.erase(IP);
1179
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001180 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001181 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001182
1183 // Update internal data structures to account for the newly inserted MBB.
1184 UpdateForInsertedWaterBlock(NewIsland);
1185
1186 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001187 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001188
1189 // Now that we have an island to add the CPE to, clone the original CPE and
1190 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001191 U.HighWaterMark = NewIsland;
Dale Johannesenb6728402009-02-13 02:25:56 +00001192 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1193 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001194 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001195 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001196 NumCPEs++;
1197
Dale Johannesen8593e412007-04-29 19:19:30 +00001198 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001199 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001200 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001201 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001202 // Increase the size of the island block to account for the new entry.
1203 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001204 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001205
Evan Chenga8e29892007-01-19 07:51:42 +00001206 // Finally, change the CPI in the instruction operand to be ID.
1207 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001208 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001209 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001210 break;
1211 }
Bob Wilson84945262009-05-12 17:09:30 +00001212
Chris Lattner705e07f2009-08-23 03:41:05 +00001213 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1214 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001215
Evan Chenga8e29892007-01-19 07:51:42 +00001216 return true;
1217}
1218
Evan Chenged884f32007-04-03 23:39:48 +00001219/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1220/// sizes and offsets of impacted basic blocks.
1221void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1222 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001223 unsigned Size = CPEMI->getOperand(2).getImm();
1224 CPEMI->eraseFromParent();
1225 BBSizes[CPEBB->getNumber()] -= Size;
1226 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001227 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001228 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001229 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001230 // empty, so fix this.
1231 // All succeeding offsets have the current size value added in, fix this.
1232 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001233 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001234 BBSizes[CPEBB->getNumber()] = 0;
1235 }
Evan Chenged884f32007-04-03 23:39:48 +00001236 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001237 AdjustBBOffsetsAfter(CPEBB, -Size);
1238 // An island has only one predecessor BB and one successor BB. Check if
1239 // this BB's predecessor jumps directly to this BB's successor. This
1240 // shouldn't happen currently.
1241 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1242 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001243}
1244
1245/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1246/// are zero.
1247bool ARMConstantIslands::RemoveUnusedCPEntries() {
1248 unsigned MadeChange = false;
1249 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1250 std::vector<CPEntry> &CPEs = CPEntries[i];
1251 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1252 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1253 RemoveDeadCPEMI(CPEs[j].CPEMI);
1254 CPEs[j].CPEMI = NULL;
1255 MadeChange = true;
1256 }
1257 }
Bob Wilson84945262009-05-12 17:09:30 +00001258 }
Evan Chenged884f32007-04-03 23:39:48 +00001259 return MadeChange;
1260}
1261
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001262/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001263/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001264bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1265 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001266 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001267 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001268 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001269
Chris Lattner705e07f2009-08-23 03:41:05 +00001270 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1271 << " from BB#" << MI->getParent()->getNumber()
1272 << " max delta=" << MaxDisp
1273 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1274 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001275
Dale Johannesen8593e412007-04-29 19:19:30 +00001276 if (BrOffset <= DestOffset) {
1277 // Branch before the Dest.
1278 if (DestOffset-BrOffset <= MaxDisp)
1279 return true;
1280 } else {
1281 if (BrOffset-DestOffset <= MaxDisp)
1282 return true;
1283 }
1284 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001285}
1286
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001287/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1288/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001289bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001290 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001291 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001292
Evan Chengc0dbec72007-01-31 19:57:44 +00001293 // Check to see if the DestBB is already in-range.
1294 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001295 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001296
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001297 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001298 return FixUpUnconditionalBr(MF, Br);
1299 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001300}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001301
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001302/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1303/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001304/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001305/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001306bool
Evan Cheng5657c012009-07-29 02:18:14 +00001307ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001308 MachineInstr *MI = Br.MI;
1309 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001310 if (!isThumb1)
1311 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001312
1313 // Use BL to implement far jump.
1314 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001315 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001316 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001317 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001318 HasFarJump = true;
1319 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001320
Chris Lattner705e07f2009-08-23 03:41:05 +00001321 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001322
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001323 return true;
1324}
1325
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001326/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001327/// far away to fit in its displacement field. It is converted to an inverse
1328/// conditional branch + an unconditional branch to the destination.
1329bool
Evan Cheng5657c012009-07-29 02:18:14 +00001330ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001331 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001332 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001333
Bob Wilson39bf0512009-05-12 17:35:29 +00001334 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001335 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001336 // blt L1
1337 // =>
1338 // bge L2
1339 // b L1
1340 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001341 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001342 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001343 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001344
1345 // If the branch is at the end of its MBB and that has a fall-through block,
1346 // direct the updated conditional branch to the fall-through block. Otherwise,
1347 // split the MBB before the next instruction.
1348 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001349 MachineInstr *BMI = &MBB->back();
1350 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001351
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001352 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001353 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001354 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001355 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001356 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001357 // condition and swap destinations:
1358 // beq L1
1359 // b L2
1360 // =>
1361 // bne L2
1362 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001363 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001364 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001365 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1366 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001367 BMI->getOperand(0).setMBB(DestBB);
1368 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001369 MI->getOperand(1).setImm(CC);
1370 return true;
1371 }
1372 }
1373 }
1374
1375 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001376 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001377 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001378 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001379 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001380 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001381 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1382 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001383 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001384 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001385 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001386 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001387
Chris Lattner893e1c92009-08-23 06:49:22 +00001388 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1389 << " also invert condition and change dest. to BB#"
1390 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001391
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001392 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001393 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001394 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1395 TII->get(MI->getOpcode()))
1396 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001397 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001398 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001399 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001400 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001401 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001402 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001403
1404 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001405 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001406 MI->eraseFromParent();
1407
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001408 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001409 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001410 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001411 return true;
1412}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001413
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001414/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001415/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1416/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001417bool ARMConstantIslands::UndoLRSpillRestore() {
1418 bool MadeChange = false;
1419 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1420 MachineInstr *MI = PushPopMIs[i];
Evan Cheng10469f82009-10-01 20:54:53 +00001421 // First two operands are predicates, the third is a zero since there
1422 // is no writeback.
Evan Cheng44bec522007-05-15 01:29:07 +00001423 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng10469f82009-10-01 20:54:53 +00001424 MI->getOperand(3).getReg() == ARM::PC &&
1425 MI->getNumExplicitOperands() == 4) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001426 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001427 MI->eraseFromParent();
1428 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001429 }
1430 }
1431 return MadeChange;
1432}
Evan Cheng5657c012009-07-29 02:18:14 +00001433
Evan Chenga1efbbd2009-08-14 00:32:16 +00001434bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1435 bool MadeChange = false;
1436
1437 // Shrink ADR and LDR from constantpool.
1438 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1439 CPUser &U = CPUsers[i];
1440 unsigned Opcode = U.MI->getOpcode();
1441 unsigned NewOpc = 0;
1442 unsigned Scale = 1;
1443 unsigned Bits = 0;
1444 switch (Opcode) {
1445 default: break;
1446 case ARM::t2LEApcrel:
1447 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1448 NewOpc = ARM::tLEApcrel;
1449 Bits = 8;
1450 Scale = 4;
1451 }
1452 break;
1453 case ARM::t2LDRpci:
1454 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1455 NewOpc = ARM::tLDRpci;
1456 Bits = 8;
1457 Scale = 4;
1458 }
1459 break;
1460 }
1461
1462 if (!NewOpc)
1463 continue;
1464
1465 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1466 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1467 // FIXME: Check if offset is multiple of scale if scale is not 4.
1468 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1469 U.MI->setDesc(TII->get(NewOpc));
1470 MachineBasicBlock *MBB = U.MI->getParent();
1471 BBSizes[MBB->getNumber()] -= 2;
1472 AdjustBBOffsetsAfter(MBB, -2);
1473 ++NumT2CPShrunk;
1474 MadeChange = true;
1475 }
1476 }
1477
Evan Chenga1efbbd2009-08-14 00:32:16 +00001478 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001479 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001480 return MadeChange;
1481}
1482
1483bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001484 bool MadeChange = false;
1485
1486 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1487 ImmBranch &Br = ImmBranches[i];
1488 unsigned Opcode = Br.MI->getOpcode();
1489 unsigned NewOpc = 0;
1490 unsigned Scale = 1;
1491 unsigned Bits = 0;
1492 switch (Opcode) {
1493 default: break;
1494 case ARM::t2B:
1495 NewOpc = ARM::tB;
1496 Bits = 11;
1497 Scale = 2;
1498 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001499 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001500 NewOpc = ARM::tBcc;
1501 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001502 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001503 break;
1504 }
Evan Chengde17fb62009-10-31 23:46:45 +00001505 }
1506 if (NewOpc) {
1507 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1508 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1509 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1510 Br.MI->setDesc(TII->get(NewOpc));
1511 MachineBasicBlock *MBB = Br.MI->getParent();
1512 BBSizes[MBB->getNumber()] -= 2;
1513 AdjustBBOffsetsAfter(MBB, -2);
1514 ++NumT2BrShrunk;
1515 MadeChange = true;
1516 }
1517 }
1518
1519 Opcode = Br.MI->getOpcode();
1520 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001521 continue;
1522
Evan Chengde17fb62009-10-31 23:46:45 +00001523 NewOpc = 0;
1524 unsigned PredReg = 0;
1525 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1526 if (Pred == ARMCC::EQ)
1527 NewOpc = ARM::tCBZ;
1528 else if (Pred == ARMCC::NE)
1529 NewOpc = ARM::tCBNZ;
1530 if (!NewOpc)
1531 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001532 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001533 // Check if the distance is within 126. Subtract starting offset by 2
1534 // because the cmp will be eliminated.
1535 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1536 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1537 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1538 MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
1539 if (CmpMI->getOpcode() == ARM::tCMPzi8) {
1540 unsigned Reg = CmpMI->getOperand(0).getReg();
1541 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1542 if (Pred == ARMCC::AL &&
1543 CmpMI->getOperand(1).getImm() == 0 &&
1544 isARMLowRegister(Reg)) {
1545 MachineBasicBlock *MBB = Br.MI->getParent();
1546 MachineInstr *NewBR =
1547 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1548 .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1549 CmpMI->eraseFromParent();
1550 Br.MI->eraseFromParent();
1551 Br.MI = NewBR;
1552 BBSizes[MBB->getNumber()] -= 2;
1553 AdjustBBOffsetsAfter(MBB, -2);
1554 ++NumCBZ;
1555 MadeChange = true;
1556 }
1557 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001558 }
1559 }
1560
1561 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001562}
1563
1564
1565/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1566/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001567bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1568 bool MadeChange = false;
1569
1570 // FIXME: After the tables are shrunk, can we get rid some of the
1571 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001572 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Evan Cheng5657c012009-07-29 02:18:14 +00001573 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1574 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1575 MachineInstr *MI = T2JumpTables[i];
1576 const TargetInstrDesc &TID = MI->getDesc();
1577 unsigned NumOps = TID.getNumOperands();
1578 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1579 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1580 unsigned JTI = JTOP.getIndex();
1581 assert(JTI < JT.size());
1582
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001583 // We prefer if target blocks for the jump table come after the jump
1584 // instruction so we can use TB[BH]. Loop through the target blocks
1585 // and try to adjust them such that that's true.
Evan Cheng5657c012009-07-29 02:18:14 +00001586 unsigned JTOffset = GetOffsetOf(MI) + 4;
1587 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001588 if (AdjustJumpTableBlocks) {
1589 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1590 MachineBasicBlock *MBB = JTBBs[j];
1591 unsigned DstOffset = BBOffsets[MBB->getNumber()];
1592
1593 if (DstOffset < JTOffset) {
1594 // The destination precedes the switch. Try to move the block forward
1595 // so we have a positive offset.
1596 MachineBasicBlock *NewBB =
1597 AdjustJTTargetBlockForward(MBB, MI->getParent());
1598 if (NewBB) {
1599 MJTI->ReplaceMBBInJumpTables(JTBBs[j], NewBB);
1600 JTOffset = GetOffsetOf(MI) + 4;
1601 DstOffset = BBOffsets[MBB->getNumber()];
1602 }
1603 }
1604 }
1605 }
1606
1607 bool ByteOk = true;
1608 bool HalfWordOk = true;
1609 JTOffset = GetOffsetOf(MI) + 4;
Evan Cheng5657c012009-07-29 02:18:14 +00001610 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1611 MachineBasicBlock *MBB = JTBBs[j];
1612 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001613 // Negative offset is not ok. FIXME: We should change BB layout to make
1614 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001615 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001616 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001617 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001618 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001619 HalfWordOk = false;
1620 if (!ByteOk && !HalfWordOk)
1621 break;
1622 }
1623
1624 if (ByteOk || HalfWordOk) {
1625 MachineBasicBlock *MBB = MI->getParent();
1626 unsigned BaseReg = MI->getOperand(0).getReg();
1627 bool BaseRegKill = MI->getOperand(0).isKill();
1628 if (!BaseRegKill)
1629 continue;
1630 unsigned IdxReg = MI->getOperand(1).getReg();
1631 bool IdxRegKill = MI->getOperand(1).isKill();
1632 MachineBasicBlock::iterator PrevI = MI;
1633 if (PrevI == MBB->begin())
1634 continue;
1635
1636 MachineInstr *AddrMI = --PrevI;
1637 bool OptOk = true;
1638 // Examine the instruction that calculate the jumptable entry address.
1639 // If it's not the one just before the t2BR_JT, we won't delete it, then
1640 // it's not worth doing the optimization.
1641 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1642 const MachineOperand &MO = AddrMI->getOperand(k);
1643 if (!MO.isReg() || !MO.getReg())
1644 continue;
1645 if (MO.isDef() && MO.getReg() != BaseReg) {
1646 OptOk = false;
1647 break;
1648 }
1649 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1650 OptOk = false;
1651 break;
1652 }
1653 }
1654 if (!OptOk)
1655 continue;
1656
Evan Chenga1efbbd2009-08-14 00:32:16 +00001657 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1658 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001659 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001660 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1661 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001662 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001663 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001664
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001665 if (!OptOk)
1666 continue;
1667
1668 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1669 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1670 .addReg(IdxReg, getKillRegState(IdxRegKill))
1671 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1672 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1673 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1674 // is 2-byte aligned. For now, asm printer will fix it up.
1675 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1676 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1677 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1678 OrigSize += TII->GetInstSizeInBytes(MI);
1679
1680 AddrMI->eraseFromParent();
1681 LeaMI->eraseFromParent();
1682 MI->eraseFromParent();
1683
1684 int delta = OrigSize - NewSize;
1685 BBSizes[MBB->getNumber()] -= delta;
1686 AdjustBBOffsetsAfter(MBB, -delta);
1687
1688 ++NumTBs;
1689 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001690 }
1691 }
1692
1693 return MadeChange;
1694}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001695
1696MachineBasicBlock *ARMConstantIslands::
1697AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1698{
1699 MachineFunction &MF = *BB->getParent();
1700
1701 // FIXME: For now, instead of moving the block, we'll create a new block
1702 // immediate following the jump that's an unconditional branch to the
1703 // actual target. This is obviously not what we want for a real solution,
1704 // but it's useful for proof of concept, and it may be a useful fallback
1705 // later for cases where we otherwise can't move a block.
1706
1707 // Create a new MBB for the code after the jump BB.
1708 MachineBasicBlock *NewBB =
1709 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1710 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1711 MF.insert(MBBI, NewBB);
1712
1713 // Add an unconditional branch from NewBB to BB.
1714 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1715 // correspond directly to anything in the source.
1716 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1717 BuildMI(NewBB, DebugLoc::getUnknownLoc(), TII->get(ARM::t2B)).addMBB(BB);
1718
1719 // Update the CFG.
1720 NewBB->addSuccessor(BB);
1721 JTBB->removeSuccessor(BB);
1722 JTBB->addSuccessor(NewBB);
1723
1724 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001725 // This is almost the same as UpdateForInsertedWaterBlock, except that
1726 // the Water goes after OrigBB, not NewBB.
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001727 MF.RenumberBlocks(NewBB);
1728
1729 // Insert a size into BBSizes to align it properly with the (newly
1730 // renumbered) block numbers.
1731 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
1732
1733 // Likewise for BBOffsets.
1734 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
1735
1736 // Figure out how large the first NewMBB is.
1737 unsigned NewBBSize = 0;
1738 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
1739 I != E; ++I)
1740 NewBBSize += TII->GetInstSizeInBytes(I);
1741
1742 unsigned NewBBI = NewBB->getNumber();
1743 unsigned JTBBI = JTBB->getNumber();
1744 // Set the size of NewBB in BBSizes.
1745 BBSizes[NewBBI] = NewBBSize;
1746
1747 // ...and adjust BBOffsets for NewBB accordingly.
1748 BBOffsets[NewBBI] = BBOffsets[JTBBI] + BBSizes[JTBBI];
1749
1750 // All BBOffsets following these blocks must be modified.
1751 AdjustBBOffsetsAfter(NewBB, 4);
1752
1753 ++NumJTMoved;
1754 return NewBB;
1755}