blob: 8066cb735b1361167070ba933aa2487016cf6f25 [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"
Evan Cheng719510a2010-08-12 20:30:05 +000021#include "Thumb2InstrInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000022#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000029#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000031#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000034#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000035#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000036using namespace llvm;
37
Evan Chenga1efbbd2009-08-14 00:32:16 +000038STATISTIC(NumCPEs, "Number of constpool entries");
39STATISTIC(NumSplit, "Number of uncond branches inserted");
40STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42STATISTIC(NumTBs, "Number of table branches generated");
43STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000044STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000045STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000046STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach80697d12009-11-12 17:25:07 +000047STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000048
49
50static cl::opt<bool>
Jim Grosbachf04777b2009-11-17 21:24:11 +000051AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach1fc7d712009-11-11 02:47:19 +000052 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000053
54namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000055 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000056 /// requires constant pool entries to be scattered among the instructions
57 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000058 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000059 /// special instructions.
60 ///
61 /// The terminology used in this pass includes:
62 /// Islands - Clumps of constants placed in the function.
63 /// Water - Potential places where an island could be formed.
64 /// CPE - A constant pool entry that has been placed somewhere, which
65 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000066 class ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000067 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000068 /// by MBB Number. The two-byte pads required for Thumb alignment are
69 /// counted as part of the following block (i.e., the offset and size for
70 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000071 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000072
Dale Johannesen99c49a42007-02-25 00:47:03 +000073 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000074 /// The two-byte pads required for Thumb alignment are counted as part of
75 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000076 std::vector<unsigned> BBOffsets;
77
Evan Chenga8e29892007-01-19 07:51:42 +000078 /// WaterList - A sorted list of basic blocks where islands could be placed
79 /// (i.e. blocks that don't fall through to the following block, due
80 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000081 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000082
Bob Wilsonb9239532009-10-15 20:49:47 +000083 /// NewWaterList - The subset of WaterList that was created since the
84 /// previous iteration by inserting unconditional branches.
85 SmallSet<MachineBasicBlock*, 4> NewWaterList;
86
Bob Wilson034de5f2009-10-12 18:52:13 +000087 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
88
Evan Chenga8e29892007-01-19 07:51:42 +000089 /// CPUser - One user of a constant pool, keeping the machine instruction
90 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +000091 /// allowed from the instruction to the CP. The HighWaterMark records the
92 /// highest basic block where a new CPEntry can be placed. To ensure this
93 /// pass terminates, the CP entries are initially placed at the end of the
94 /// function and then move monotonically to lower addresses. The
95 /// exception to this rule is when the current CP entry for a particular
96 /// CPUser is out of range, but there is another CP entry for the same
97 /// constant value in range. We want to use the existing in-range CP
98 /// entry, but if it later moves out of range, the search for new water
99 /// should resume where it left off. The HighWaterMark is used to record
100 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000101 struct CPUser {
102 MachineInstr *MI;
103 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000104 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000105 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000106 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000107 bool IsSoImm;
108 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
109 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000110 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
111 HighWaterMark = CPEMI->getParent();
112 }
Evan Chenga8e29892007-01-19 07:51:42 +0000113 };
Bob Wilson84945262009-05-12 17:09:30 +0000114
Evan Chenga8e29892007-01-19 07:51:42 +0000115 /// CPUsers - Keep track of all of the machine instructions that use various
116 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000117 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000118
Evan Chengc99ef082007-02-09 20:54:44 +0000119 /// CPEntry - One per constant pool entry, keeping the machine instruction
120 /// pointer, the constpool index, and the number of CPUser's which
121 /// reference this entry.
122 struct CPEntry {
123 MachineInstr *CPEMI;
124 unsigned CPI;
125 unsigned RefCount;
126 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
127 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
128 };
129
130 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000131 /// instructions. For each original constpool index (i.e. those that
132 /// existed upon entry to this pass), it keeps a vector of entries.
133 /// Original elements are cloned as we go along; the clones are
134 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000135 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000136
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000137 /// ImmBranch - One per immediate branch, keeping the machine instruction
138 /// pointer, conditional or unconditional, the max displacement,
139 /// and (if isCond is true) the corresponding unconditional branch
140 /// opcode.
141 struct ImmBranch {
142 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000143 unsigned MaxDisp : 31;
144 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000145 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000146 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
147 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000148 };
149
Evan Cheng2706f972007-05-16 05:14:06 +0000150 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000151 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000152 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000153
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000154 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
155 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000156 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000157
Evan Cheng5657c012009-07-29 02:18:14 +0000158 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
159 SmallVector<MachineInstr*, 4> T2JumpTables;
160
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000161 /// HasFarJump - True if any far jump instruction has been emitted during
162 /// the branch fix up pass.
163 bool HasFarJump;
164
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000165 /// HasInlineAsm - True if the function contains inline assembly.
166 bool HasInlineAsm;
167
Chris Lattner20628752010-07-22 21:27:00 +0000168 const ARMInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000169 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000170 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000171 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000172 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000173 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000174 public:
Devang Patel19974732007-05-03 01:11:54 +0000175 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000176 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000177
Evan Cheng5657c012009-07-29 02:18:14 +0000178 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000179
180 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000181 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000182 }
Bob Wilson84945262009-05-12 17:09:30 +0000183
Evan Chenga8e29892007-01-19 07:51:42 +0000184 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000185 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000186 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000187 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jim Grosbach80697d12009-11-12 17:25:07 +0000188 void JumpTableFunctionScan(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000189 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000190 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000191 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000192 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000193 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000194 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000195 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000196 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000197 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000198 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000199 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000200 void RemoveDeadCPEMI(MachineInstr *CPEMI);
201 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000202 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000203 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
204 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000205 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000206 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000207 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000208 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000209 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000210 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
211 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
212 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000213 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000214 bool OptimizeThumb2Instructions(MachineFunction &MF);
215 bool OptimizeThumb2Branches(MachineFunction &MF);
Jim Grosbach80697d12009-11-12 17:25:07 +0000216 bool ReorderThumb2JumpTables(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000217 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000218 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
219 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000220
Evan Chenga8e29892007-01-19 07:51:42 +0000221 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000222 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000223 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000224 };
Devang Patel19974732007-05-03 01:11:54 +0000225 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000226}
227
Dale Johannesen8593e412007-04-29 19:19:30 +0000228/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000229void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000230 assert(BBOffsets.size() == BBSizes.size());
231 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
232 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000233 if (!isThumb)
234 return;
235#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000236 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000237 MBBI != E; ++MBBI) {
238 MachineBasicBlock *MBB = MBBI;
239 if (!MBB->empty() &&
240 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
241 unsigned MBBId = MBB->getNumber();
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000242 assert(HasInlineAsm ||
243 (BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
Evan Chengd3d9d662009-07-23 18:27:47 +0000244 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000245 }
246 }
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000247 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
248 CPUser &U = CPUsers[i];
249 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
Jim Grosbacha9562562009-11-20 19:37:38 +0000250 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
251 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
252 UserOffset - CPEOffset;
253 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000254 }
Jim Grosbacha9562562009-11-20 19:37:38 +0000255#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000256}
257
258/// print block size and offset information - debugging
259void ARMConstantIslands::dumpBBs() {
260 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000261 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
262 << " size " << BBSizes[J] << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000263 }
264}
265
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000266/// createARMConstantIslandPass - returns an instance of the constpool
267/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000268FunctionPass *llvm::createARMConstantIslandPass() {
269 return new ARMConstantIslands();
270}
271
Evan Cheng5657c012009-07-29 02:18:14 +0000272bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
273 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000274
Chris Lattner20628752010-07-22 21:27:00 +0000275 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
Evan Cheng5657c012009-07-29 02:18:14 +0000276 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000277 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
278
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000279 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000280 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000281 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000282
283 HasFarJump = false;
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000284 HasInlineAsm = false;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000285
Evan Chenga8e29892007-01-19 07:51:42 +0000286 // Renumber all of the machine basic blocks in the function, guaranteeing that
287 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000288 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000289
Jim Grosbach80697d12009-11-12 17:25:07 +0000290 // Try to reorder and otherwise adjust the block layout to make good use
291 // of the TB[BH] instructions.
292 bool MadeChange = false;
293 if (isThumb2 && AdjustJumpTableBlocks) {
294 JumpTableFunctionScan(MF);
295 MadeChange |= ReorderThumb2JumpTables(MF);
296 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach80697d12009-11-12 17:25:07 +0000297 T2JumpTables.clear();
298 // Blocks may have shifted around. Keep the numbering up to date.
299 MF.RenumberBlocks();
300 }
301
Evan Chengd26b14c2009-07-31 18:28:05 +0000302 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000303 // This is so we can keep exact track of where the alignment padding goes.
304
Chris Lattner7d7dab02010-01-27 23:37:36 +0000305 // ARM and Thumb2 functions need to be 4-byte aligned.
306 if (!isThumb1)
307 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000308
Evan Chenga8e29892007-01-19 07:51:42 +0000309 // Perform the initial placement of the constant pool entries. To start with,
310 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000311 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000312 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000313 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000314 if (isThumb1)
Chris Lattner7d7dab02010-01-27 23:37:36 +0000315 MF.EnsureAlignment(2); // 2 = log2(4)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000316 }
Bob Wilson84945262009-05-12 17:09:30 +0000317
Evan Chenga8e29892007-01-19 07:51:42 +0000318 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000319 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000320
Evan Chenga8e29892007-01-19 07:51:42 +0000321 // Do the initial scan of the function, building up information about the
322 // sizes of each block, the location of all the water, and finding all of the
323 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000324 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000325 CPEMIs.clear();
Dale Johannesen8086d582010-07-23 22:50:23 +0000326 DEBUG(dumpBBs());
327
Bob Wilson84945262009-05-12 17:09:30 +0000328
Evan Chenged884f32007-04-03 23:39:48 +0000329 /// Remove dead constant pool entries.
330 RemoveUnusedCPEntries();
331
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000332 // Iteratively place constant pool entries and fix up branches until there
333 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000334 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000335 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000336 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000337 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000338 CPChange |= HandleConstantPoolUser(MF, i);
339 if (CPChange && ++NoCPIters > 30)
340 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000341 DEBUG(dumpBBs());
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000342
Bob Wilsonb9239532009-10-15 20:49:47 +0000343 // Clear NewWaterList now. If we split a block for branches, it should
344 // appear as "new water" for the next iteration of constant pool placement.
345 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000346
347 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000348 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000349 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
350 if (BRChange && ++NoBRIters > 30)
351 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000352 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000353
354 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000355 break;
356 MadeChange = true;
357 }
Evan Chenged884f32007-04-03 23:39:48 +0000358
Evan Chenga1efbbd2009-08-14 00:32:16 +0000359 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chenge44be632010-08-09 18:35:19 +0000360 if (isThumb2 && !STI->prefers32BitThumb())
Evan Chenga1efbbd2009-08-14 00:32:16 +0000361 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000362
Dale Johannesen8593e412007-04-29 19:19:30 +0000363 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000364 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000365
Jim Grosbach26b8ef52010-07-07 21:06:51 +0000366 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
367 // undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000368 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000369 MadeChange |= UndoLRSpillRestore();
370
Evan Chengb1c857b2010-07-22 02:09:47 +0000371 DEBUG(errs() << '\n'; dumpBBs());
372
Evan Chenga8e29892007-01-19 07:51:42 +0000373 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000374 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000375 WaterList.clear();
376 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000377 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000378 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000379 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000380 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000381
382 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000383}
384
385/// DoInitialPlacement - Perform the initial placement of the constant pool
386/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000387void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000388 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000389 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000390 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
391 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000392
Evan Chenga8e29892007-01-19 07:51:42 +0000393 // Add all of the constants from the constant pool to the end block, use an
394 // identity mapping of CPI's to CPE's.
395 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000396 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000397
Evan Cheng5657c012009-07-29 02:18:14 +0000398 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000399 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000400 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000401 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
402 // we would have to pad them out or something so that instructions stay
403 // aligned.
404 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
405 MachineInstr *CPEMI =
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000406 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
407 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000408 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000409
410 // Add a new CPEntry, but no corresponding CPUser yet.
411 std::vector<CPEntry> CPEs;
412 CPEs.push_back(CPEntry(CPEMI, i));
413 CPEntries.push_back(CPEs);
Dan Gohmanfe601042010-06-22 15:08:57 +0000414 ++NumCPEs;
Chris Lattner893e1c92009-08-23 06:49:22 +0000415 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
416 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000417 }
418}
419
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000420/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000421/// into the block immediately after it.
422static bool BBHasFallthrough(MachineBasicBlock *MBB) {
423 // Get the next machine basic block in the function.
424 MachineFunction::iterator MBBI = MBB;
Jim Grosbach18f30e62010-06-02 21:53:11 +0000425 // Can't fall off end of function.
426 if (llvm::next(MBBI) == MBB->getParent()->end())
Evan Chenga8e29892007-01-19 07:51:42 +0000427 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000428
Chris Lattner7896c9f2009-12-03 00:50:42 +0000429 MachineBasicBlock *NextBB = llvm::next(MBBI);
Evan Chenga8e29892007-01-19 07:51:42 +0000430 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
431 E = MBB->succ_end(); I != E; ++I)
432 if (*I == NextBB)
433 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000434
Evan Chenga8e29892007-01-19 07:51:42 +0000435 return false;
436}
437
Evan Chengc99ef082007-02-09 20:54:44 +0000438/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
439/// look up the corresponding CPEntry.
440ARMConstantIslands::CPEntry
441*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
442 const MachineInstr *CPEMI) {
443 std::vector<CPEntry> &CPEs = CPEntries[CPI];
444 // Number of entries per constpool index should be small, just do a
445 // linear search.
446 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
447 if (CPEs[i].CPEMI == CPEMI)
448 return &CPEs[i];
449 }
450 return NULL;
451}
452
Jim Grosbach80697d12009-11-12 17:25:07 +0000453/// JumpTableFunctionScan - Do a scan of the function, building up
454/// information about the sizes of each block and the locations of all
455/// the jump tables.
456void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
Jim Grosbach80697d12009-11-12 17:25:07 +0000457 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
458 MBBI != E; ++MBBI) {
459 MachineBasicBlock &MBB = *MBBI;
460
Jim Grosbach80697d12009-11-12 17:25:07 +0000461 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach08cbda52009-11-16 18:58:52 +0000462 I != E; ++I)
463 if (I->getDesc().isBranch() && I->getOpcode() == ARM::t2BR_JT)
464 T2JumpTables.push_back(I);
Jim Grosbach80697d12009-11-12 17:25:07 +0000465 }
466}
467
Evan Chenga8e29892007-01-19 07:51:42 +0000468/// InitialFunctionScan - Do the initial scan of the function, building up
469/// information about the sizes of each block, the location of all the water,
470/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000471void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000472 const std::vector<MachineInstr*> &CPEMIs) {
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000473 // First thing, see if the function has any inline assembly in it. If so,
474 // we have to be conservative about alignment assumptions, as we don't
475 // know for sure the size of any instructions in the inline assembly.
476 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
477 MBBI != E; ++MBBI) {
478 MachineBasicBlock &MBB = *MBBI;
479 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
480 I != E; ++I)
481 if (I->getOpcode() == ARM::INLINEASM)
482 HasInlineAsm = true;
483 }
484
485 // Now go back through the instructions and build up our data structures
Dale Johannesen99c49a42007-02-25 00:47:03 +0000486 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000487 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000488 MBBI != E; ++MBBI) {
489 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000490
Evan Chenga8e29892007-01-19 07:51:42 +0000491 // If this block doesn't fall through into the next MBB, then this is
492 // 'water' that a constant pool island could be placed.
493 if (!BBHasFallthrough(&MBB))
494 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000495
Evan Chenga8e29892007-01-19 07:51:42 +0000496 unsigned MBBSize = 0;
497 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
498 I != E; ++I) {
Jim Grosbach9cfcfeb2010-06-21 17:49:23 +0000499 if (I->isDebugValue())
500 continue;
Evan Chenga8e29892007-01-19 07:51:42 +0000501 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000502 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000503
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000504 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000505 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000506 bool isCond = false;
507 unsigned Bits = 0;
508 unsigned Scale = 1;
509 int UOpc = Opc;
510 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000511 default:
512 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000513 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000514 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000515 // be right, functions containing these must be 4-byte aligned.
Evan Chengb1c857b2010-07-22 02:09:47 +0000516 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
517 // table entries. So this code checks whether offset of tBR_JTr + 2
Dale Johannesen8086d582010-07-23 22:50:23 +0000518 // is aligned. That is held in Offset+MBBSize, which already has
519 // 2 added in for the size of the mov pc instruction.
Chris Lattner7d7dab02010-01-27 23:37:36 +0000520 MF.EnsureAlignment(2U);
Dale Johannesen8086d582010-07-23 22:50:23 +0000521 if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
Evan Cheng5657c012009-07-29 02:18:14 +0000522 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000523 MBBSize += 2; // padding
524 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000525 case ARM::t2BR_JT:
526 T2JumpTables.push_back(I);
527 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000528 case ARM::Bcc:
529 isCond = true;
530 UOpc = ARM::B;
531 // Fallthrough
532 case ARM::B:
533 Bits = 24;
534 Scale = 4;
535 break;
536 case ARM::tBcc:
537 isCond = true;
538 UOpc = ARM::tB;
539 Bits = 8;
540 Scale = 2;
541 break;
542 case ARM::tB:
543 Bits = 11;
544 Scale = 2;
545 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000546 case ARM::t2Bcc:
547 isCond = true;
548 UOpc = ARM::t2B;
549 Bits = 20;
550 Scale = 2;
551 break;
552 case ARM::t2B:
553 Bits = 24;
554 Scale = 2;
555 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000556 }
Evan Chengb43216e2007-02-01 10:16:15 +0000557
558 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000559 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000560 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000561 }
562
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000563 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
564 PushPopMIs.push_back(I);
565
Evan Chengd3d9d662009-07-23 18:27:47 +0000566 if (Opc == ARM::CONSTPOOL_ENTRY)
567 continue;
568
Evan Chenga8e29892007-01-19 07:51:42 +0000569 // Scan the instructions for constant pool operands.
570 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000571 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000572 // We found one. The addressing mode tells us the max displacement
573 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000574
Evan Chenga8e29892007-01-19 07:51:42 +0000575 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000576 unsigned Bits = 0;
577 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000578 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000579 bool IsSoImm = false;
580
581 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000582 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000583 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000584 break;
585
586 // Taking the address of a CP entry.
587 case ARM::LEApcrel:
588 // This takes a SoImm, which is 8 bit immediate rotated. We'll
589 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbachdec6de92009-11-19 18:23:19 +0000590 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd3d9d662009-07-23 18:27:47 +0000591 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000592 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000593 Scale = 4;
594 NegOk = true;
595 IsSoImm = true;
596 break;
Owen Anderson6b8719f2010-12-13 22:51:08 +0000597 case ARM::t2LEApcrel:
Evan Chengd3d9d662009-07-23 18:27:47 +0000598 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000599 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000600 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000601 case ARM::tLEApcrel:
602 Bits = 8;
603 Scale = 4;
604 break;
605
Jim Grosbach3e556122010-10-26 22:37:02 +0000606 case ARM::LDRi12:
Evan Chengd3d9d662009-07-23 18:27:47 +0000607 case ARM::LDRcp:
Owen Andersoneb6779c2010-12-07 00:45:21 +0000608 case ARM::t2LDRi12:
609 case ARM::t2LDRHi12:
610 case ARM::t2LDRBi12:
611 case ARM::t2LDRSHi12:
612 case ARM::t2LDRSBi12:
Evan Cheng556f33c2007-02-01 20:44:52 +0000613 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000614 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000615 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000616
617 case ARM::tLDRpci:
618 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000619 Bits = 8;
620 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000621 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000622
Jim Grosbache5165492009-11-09 00:11:35 +0000623 case ARM::VLDRD:
624 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000625 Bits = 8;
626 Scale = 4; // +-(offset_8*4)
627 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000628 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000629 }
Evan Chengb43216e2007-02-01 10:16:15 +0000630
Evan Chenga8e29892007-01-19 07:51:42 +0000631 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000632 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000633 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000634 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000635 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000636
637 // Increment corresponding CPEntry reference count.
638 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
639 assert(CPE && "Cannot find a corresponding CPEntry!");
640 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000641
Evan Chenga8e29892007-01-19 07:51:42 +0000642 // Instructions can only use one CP entry, don't bother scanning the
643 // rest of the operands.
644 break;
645 }
646 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000647
Dale Johannesen8593e412007-04-29 19:19:30 +0000648 // In thumb mode, if this block is a constpool island, we may need padding
649 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000650 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000651 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000652 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000653 ((Offset%4) != 0 || HasInlineAsm))
Evan Cheng2021abe2007-02-01 01:09:47 +0000654 MBBSize += 2;
655
Evan Chenga8e29892007-01-19 07:51:42 +0000656 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000657 BBOffsets.push_back(Offset);
658 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000659 }
660}
661
Evan Chenga8e29892007-01-19 07:51:42 +0000662/// GetOffsetOf - Return the current offset of the specified machine instruction
663/// from the start of the function. This offset changes as stuff is moved
664/// around inside the function.
665unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
666 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000667
Evan Chenga8e29892007-01-19 07:51:42 +0000668 // The offset is composed of two things: the sum of the sizes of all MBB's
669 // before this instruction's block, and the offset from the start of the block
670 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000671 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000672
Dale Johannesen8593e412007-04-29 19:19:30 +0000673 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
674 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000675 if (isThumb &&
676 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000677 (Offset%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +0000678 Offset += 2;
679
Evan Chenga8e29892007-01-19 07:51:42 +0000680 // Sum instructions before MI in MBB.
681 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
682 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
683 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000684 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000685 }
686}
687
688/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
689/// ID.
690static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
691 const MachineBasicBlock *RHS) {
692 return LHS->getNumber() < RHS->getNumber();
693}
694
695/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
696/// machine function, it upsets all of the block numbers. Renumber the blocks
697/// and update the arrays that parallel this numbering.
698void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
699 // Renumber the MBB's to keep them consequtive.
700 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000701
Evan Chenga8e29892007-01-19 07:51:42 +0000702 // Insert a size into BBSizes to align it properly with the (newly
703 // renumbered) block numbers.
704 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000705
706 // Likewise for BBOffsets.
707 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000708
709 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000710 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000711 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000712 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
713 CompareMBBNumbers);
714 WaterList.insert(IP, NewBB);
715}
716
717
718/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000719/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000720/// account for this change and returns the newly created block.
721MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000722 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000723 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000724
725 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000726 MachineBasicBlock *NewBB =
727 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000728 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000729 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000730
Evan Chenga8e29892007-01-19 07:51:42 +0000731 // Splice the instructions starting with MI over to NewBB.
732 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000733
Evan Chenga8e29892007-01-19 07:51:42 +0000734 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000735 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000736 // There doesn't seem to be meaningful DebugInfo available; this doesn't
737 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000738 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +0000739 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
Dan Gohmanfe601042010-06-22 15:08:57 +0000740 ++NumSplit;
Bob Wilson84945262009-05-12 17:09:30 +0000741
Evan Chenga8e29892007-01-19 07:51:42 +0000742 // Update the CFG. All succs of OrigBB are now succs of NewBB.
743 while (!OrigBB->succ_empty()) {
744 MachineBasicBlock *Succ = *OrigBB->succ_begin();
745 OrigBB->removeSuccessor(Succ);
746 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000747
Evan Chenga8e29892007-01-19 07:51:42 +0000748 // This pass should be run after register allocation, so there should be no
749 // PHI nodes to update.
Chris Lattner518bb532010-02-09 19:54:29 +0000750 assert((Succ->empty() || !Succ->begin()->isPHI())
Evan Chenga8e29892007-01-19 07:51:42 +0000751 && "PHI nodes should be eliminated by now!");
752 }
Bob Wilson84945262009-05-12 17:09:30 +0000753
Evan Chenga8e29892007-01-19 07:51:42 +0000754 // OrigBB branches to NewBB.
755 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000756
Evan Chenga8e29892007-01-19 07:51:42 +0000757 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000758 // This is almost the same as UpdateForInsertedWaterBlock, except that
759 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000760 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000761
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000762 // Insert a size into BBSizes to align it properly with the (newly
763 // renumbered) block numbers.
764 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000765
Dale Johannesen99c49a42007-02-25 00:47:03 +0000766 // Likewise for BBOffsets.
767 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
768
Bob Wilson84945262009-05-12 17:09:30 +0000769 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000770 // available water after it (but not if it's already there, which happens
771 // when splitting before a conditional branch that is followed by an
772 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000773 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000774 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
775 CompareMBBNumbers);
776 MachineBasicBlock* WaterBB = *IP;
777 if (WaterBB == OrigBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000778 WaterList.insert(llvm::next(IP), NewBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000779 else
780 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000781 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000782
Dale Johannesen99c49a42007-02-25 00:47:03 +0000783 unsigned OrigBBI = OrigBB->getNumber();
784 unsigned NewBBI = NewBB->getNumber();
Bob Wilson84945262009-05-12 17:09:30 +0000785
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000786 int delta = isThumb1 ? 2 : 4;
Dale Johannesen8086d582010-07-23 22:50:23 +0000787
788 // Figure out how large the OrigBB is. As the first half of the original
789 // block, it cannot contain a tablejump. The size includes
790 // the new jump we added. (It should be possible to do this without
791 // recounting everything, but it's very confusing, and this is rarely
792 // executed.)
793 unsigned OrigBBSize = 0;
794 for (MachineBasicBlock::iterator I = OrigBB->begin(), E = OrigBB->end();
795 I != E; ++I)
796 OrigBBSize += TII->GetInstSizeInBytes(I);
797 BBSizes[OrigBBI] = OrigBBSize;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000798
799 // ...and adjust BBOffsets for NewBB accordingly.
800 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
801
Dale Johannesen8086d582010-07-23 22:50:23 +0000802 // Figure out how large the NewMBB is. As the second half of the original
803 // block, it may contain a tablejump.
804 unsigned NewBBSize = 0;
805 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
806 I != E; ++I)
807 NewBBSize += TII->GetInstSizeInBytes(I);
808 // Set the size of NewBB in BBSizes. It does not include any padding now.
809 BBSizes[NewBBI] = NewBBSize;
810
811 MachineInstr* ThumbJTMI = prior(NewBB->end());
812 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
813 // We've added another 2-byte instruction before this tablejump, which
814 // means we will always need padding if we didn't before, and vice versa.
815
816 // The original offset of the jump instruction was:
817 unsigned OrigOffset = BBOffsets[OrigBBI] + BBSizes[OrigBBI] - delta;
818 if (OrigOffset%4 == 0) {
819 // We had padding before and now we don't. No net change in code size.
820 delta = 0;
821 } else {
822 // We didn't have padding before and now we do.
823 BBSizes[NewBBI] += 2;
824 delta = 4;
825 }
826 }
827
Dale Johannesen99c49a42007-02-25 00:47:03 +0000828 // All BBOffsets following these blocks must be modified.
Dale Johannesen8086d582010-07-23 22:50:23 +0000829 if (delta)
830 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000831
832 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000833}
834
Dale Johannesen8593e412007-04-29 19:19:30 +0000835/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000836/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000837/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000838bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000839 unsigned TrialOffset, unsigned MaxDisp,
840 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000841 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
842 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000843 // Effectively, the valid range of displacements is 2 bytes smaller for such
844 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000845 unsigned TotalAdj = 0;
846 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000847 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000848 TotalAdj = 2;
849 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000850 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000851 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000852 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000853 TotalAdj += 2;
854 }
855
856 // In Thumb2 mode, later branch adjustments can shift instructions up and
857 // cause alignment change. In the worst case scenario this can cause the
858 // user's effective address to be subtracted by 2 and the CPE's address to
859 // be plus 2.
860 if (isThumb2 && TotalAdj != 4)
861 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000862
Dale Johannesen99c49a42007-02-25 00:47:03 +0000863 if (UserOffset <= TrialOffset) {
864 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000865 if (TrialOffset - UserOffset <= MaxDisp)
866 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000867 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000868 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000869 if (UserOffset - TrialOffset <= MaxDisp)
870 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000871 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000872 }
873 return false;
874}
875
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000876/// WaterIsInRange - Returns true if a CPE placed after the specified
877/// Water (a basic block) will be in range for the specific MI.
878
879bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000880 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000881 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000882 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000883 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000884
Dale Johannesend959aa42007-04-02 20:31:06 +0000885 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000886 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000887 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000888 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000889
Evan Chengd3d9d662009-07-23 18:27:47 +0000890 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000891}
892
893/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000894/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000895bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000896 MachineInstr *CPEMI, unsigned MaxDisp,
897 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000898 unsigned CPEOffset = GetOffsetOf(CPEMI);
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000899 assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000900
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000901 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000902 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
903 << " max delta=" << MaxDisp
904 << " insn address=" << UserOffset
905 << " CPE address=" << CPEOffset
906 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000907 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000908
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000909 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000910}
911
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000912#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000913/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
914/// unconditionally branches to its only successor.
915static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
916 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
917 return false;
918
919 MachineBasicBlock *Succ = *MBB->succ_begin();
920 MachineBasicBlock *Pred = *MBB->pred_begin();
921 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000922 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
923 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000924 return PredMI->getOperand(0).getMBB() == Succ;
925 return false;
926}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000927#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000928
Bob Wilson84945262009-05-12 17:09:30 +0000929void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000930 int delta) {
Chris Lattner7896c9f2009-12-03 00:50:42 +0000931 MachineFunction::iterator MBBI = BB; MBBI = llvm::next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000932 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
933 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000934 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000935 // If some existing blocks have padding, adjust the padding as needed, a
936 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000937 if (!isThumb)
938 continue;
939 MachineBasicBlock *MBB = MBBI;
Jim Grosbach4d8e90a2009-11-19 23:10:28 +0000940 if (!MBB->empty() && !HasInlineAsm) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000941 // Constant pool entries require padding.
942 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000943 unsigned OldOffset = BBOffsets[i] - delta;
944 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000945 // add new padding
946 BBSizes[i] += 2;
947 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000948 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000949 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000950 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000951 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000952 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000953 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000954 // Thumb1 jump tables require padding. They should be at the end;
955 // following unconditional branches are removed by AnalyzeBranch.
Evan Chengb1c857b2010-07-22 02:09:47 +0000956 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
Dale Johannesen8086d582010-07-23 22:50:23 +0000957 // table entries. So this code checks whether offset of tBR_JTr
958 // is aligned; if it is, the offset of the jump table following the
959 // instruction will not be aligned, and we need padding.
Evan Cheng78947622009-07-24 18:20:44 +0000960 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000961 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Dale Johannesen8086d582010-07-23 22:50:23 +0000962 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
Evan Cheng4a8ea212009-08-11 07:36:14 +0000963 unsigned OldMIOffset = NewMIOffset - delta;
964 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000965 // remove existing padding
966 BBSizes[i] -= 2;
967 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000968 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000969 // add new padding
970 BBSizes[i] += 2;
971 delta += 2;
972 }
973 }
974 if (delta==0)
975 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000976 }
Chris Lattner7896c9f2009-12-03 00:50:42 +0000977 MBBI = llvm::next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000978 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000979}
980
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000981/// DecrementOldEntry - find the constant pool entry with index CPI
982/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000983/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000984/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000985
Evan Chenged884f32007-04-03 23:39:48 +0000986bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000987 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000988 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
989 assert(CPE && "Unexpected!");
990 if (--CPE->RefCount == 0) {
991 RemoveDeadCPEMI(CPEMI);
992 CPE->CPEMI = NULL;
Dan Gohmanfe601042010-06-22 15:08:57 +0000993 --NumCPEs;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000994 return true;
995 }
996 return false;
997}
998
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000999/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1000/// if not, see if an in-range clone of the CPE is in range, and if so,
1001/// change the data structures so the user references the clone. Returns:
1002/// 0 = no existing entry found
1003/// 1 = entry found, and there were no code insertions or deletions
1004/// 2 = entry found, and there were code insertions or deletions
1005int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1006{
1007 MachineInstr *UserMI = U.MI;
1008 MachineInstr *CPEMI = U.CPEMI;
1009
1010 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001011 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001012 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001013 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +00001014 }
1015
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001016 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +00001017 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001018 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1019 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1020 // We already tried this one
1021 if (CPEs[i].CPEMI == CPEMI)
1022 continue;
1023 // Removing CPEs can leave empty entries, skip
1024 if (CPEs[i].CPEMI == NULL)
1025 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +00001026 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001027 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1028 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001029 // Point the CPUser node to the replacement
1030 U.CPEMI = CPEs[i].CPEMI;
1031 // Change the CPI in the instruction operand to refer to the clone.
1032 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +00001033 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001034 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001035 break;
1036 }
1037 // Adjust the refcount of the clone...
1038 CPEs[i].RefCount++;
1039 // ...and the original. If we didn't remove the old entry, none of the
1040 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +00001041 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001042 }
1043 }
1044 return 0;
1045}
1046
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001047/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1048/// the specific unconditional branch instruction.
1049static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +00001050 switch (Opc) {
1051 case ARM::tB:
1052 return ((1<<10)-1)*2;
1053 case ARM::t2B:
1054 return ((1<<23)-1)*2;
1055 default:
1056 break;
1057 }
Jim Grosbach764ab522009-08-11 15:33:49 +00001058
David Goodwin5e47a9a2009-06-30 18:04:13 +00001059 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001060}
1061
Bob Wilsonb9239532009-10-15 20:49:47 +00001062/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001063/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +00001064/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +00001065/// is set to the WaterList entry. For Thumb, prefer water that will not
1066/// introduce padding to water that will. To ensure that this pass
1067/// terminates, the CPE location for a particular CPUser is only allowed to
1068/// move to a lower address, so search backward from the end of the list and
1069/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001070bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +00001071 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +00001072 if (WaterList.empty())
1073 return false;
1074
Bob Wilson32c50e82009-10-12 20:45:53 +00001075 bool FoundWaterThatWouldPad = false;
1076 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +00001077 for (water_iterator IP = prior(WaterList.end()),
1078 B = WaterList.begin();; --IP) {
1079 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +00001080 // Check if water is in range and is either at a lower address than the
1081 // current "high water mark" or a new water block that was created since
1082 // the previous iteration by inserting an unconditional branch. In the
1083 // latter case, we want to allow resetting the high water mark back to
1084 // this new water since we haven't seen it before. Inserting branches
1085 // should be relatively uncommon and when it does happen, we want to be
1086 // sure to take advantage of it for all the CPEs near that block, so that
1087 // we don't insert more branches than necessary.
1088 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1089 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1090 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +00001091 unsigned WBBId = WaterBB->getNumber();
1092 if (isThumb &&
1093 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
1094 // This is valid Water, but would introduce padding. Remember
1095 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001096 if (!FoundWaterThatWouldPad) {
1097 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001098 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001099 }
Bob Wilson3b757352009-10-12 19:04:03 +00001100 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001101 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001102 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001103 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001104 }
Bob Wilson3b757352009-10-12 19:04:03 +00001105 if (IP == B)
1106 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001107 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001108 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001109 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001110 return true;
1111 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001112 return false;
1113}
1114
Bob Wilson84945262009-05-12 17:09:30 +00001115/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001116/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1117/// block is used if in range, and the conditional branch munged so control
1118/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001119/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001120/// block following which the new island can be inserted (the WaterList
1121/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001122void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001123 unsigned UserOffset,
1124 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001125 CPUser &U = CPUsers[CPUserIndex];
1126 MachineInstr *UserMI = U.MI;
1127 MachineInstr *CPEMI = U.CPEMI;
1128 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001129 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001130 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001131 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001132
Bob Wilson36fa5322009-10-15 05:10:36 +00001133 // If the block does not end in an unconditional branch already, and if the
1134 // end of the block is within range, make new water there. (The addition
1135 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1136 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001137 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001138 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001139 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1140 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001141 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001142 if (&UserMBB->back() == UserMI)
1143 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Chris Lattner7896c9f2009-12-03 00:50:42 +00001144 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001145 // Add an unconditional branch from UserMBB to fallthrough block.
1146 // Record it for branch lengthening; this new branch will not get out of
1147 // range, but if the preceding conditional branch is out of range, the
1148 // targets will be exchanged, and the altered branch may be out of
1149 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001150 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001151 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001152 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001153 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001154 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001155 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001156 BBSizes[UserMBB->getNumber()] += delta;
1157 AdjustBBOffsetsAfter(UserMBB, delta);
1158 } else {
1159 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001160 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001161 // and constant pool entries are 4 bytes: if instruction I references
1162 // island CPE, and instruction I+1 references CPE', it will
1163 // not work well to put CPE as far forward as possible, since then
1164 // CPE' cannot immediately follow it (that location is 2 bytes
1165 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001166 // a new island. So, we make a first guess, then walk through the
1167 // instructions between the one currently being looked at and the
1168 // possible insertion point, and make sure any other instructions
1169 // that reference CPEs will be able to use the same island area;
1170 // if not, we back up the insertion point.
1171
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001172 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001173 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001174 // island is handled inside OffsetIsInRange.
1175 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001176 // This could point off the end of the block if we've already got
1177 // constant pool entries following this block; only the last one is
1178 // in the water list. Back past any possible branches (allow for a
1179 // conditional and a maximally long unconditional).
1180 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001181 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001182 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001183 unsigned EndInsertOffset = BaseInsertOffset +
1184 CPEMI->getOperand(2).getImm();
1185 MachineBasicBlock::iterator MI = UserMI;
1186 ++MI;
1187 unsigned CPUIndex = CPUserIndex+1;
Evan Cheng719510a2010-08-12 20:30:05 +00001188 unsigned NumCPUsers = CPUsers.size();
1189 MachineInstr *LastIT = 0;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001190 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001191 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001192 Offset += TII->GetInstSizeInBytes(MI),
Evan Cheng719510a2010-08-12 20:30:05 +00001193 MI = llvm::next(MI)) {
1194 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001195 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001196 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001197 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1198 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1199 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001200 }
1201 // This is overly conservative, as we don't account for CPEMIs
1202 // being reused within the block, but it doesn't matter much.
1203 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1204 CPUIndex++;
1205 }
Evan Cheng719510a2010-08-12 20:30:05 +00001206
1207 // Remember the last IT instruction.
1208 if (MI->getOpcode() == ARM::t2IT)
1209 LastIT = MI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001210 }
Evan Cheng719510a2010-08-12 20:30:05 +00001211
Chris Lattner893e1c92009-08-23 06:49:22 +00001212 DEBUG(errs() << "Split in middle of big block\n");
Evan Cheng719510a2010-08-12 20:30:05 +00001213 --MI;
1214
1215 // Avoid splitting an IT block.
1216 if (LastIT) {
1217 unsigned PredReg = 0;
1218 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1219 if (CC != ARMCC::AL)
1220 MI = LastIT;
1221 }
1222 NewMBB = SplitBlockBeforeInstr(MI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001223 }
1224}
1225
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001226/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001227/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001228/// place in-range. Return true if we changed any addresses (thus must run
1229/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001230bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001231 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001232 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001233 MachineInstr *UserMI = U.MI;
1234 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001235 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001236 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001237 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001238 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001239 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001240
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001241 // See if the current entry is within range, or there is a clone of it
1242 // in range.
1243 int result = LookForExistingCPEntry(U, UserOffset);
1244 if (result==1) return false;
1245 else if (result==2) return true;
1246
1247 // No existing clone of this CPE is within range.
1248 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001249 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001250
Bob Wilsonf98032e2009-10-12 21:23:15 +00001251 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001252 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1253 MachineBasicBlock *NewMBB;
1254 water_iterator IP;
1255 if (LookForWater(U, UserOffset, IP)) {
1256 DEBUG(errs() << "found water in range\n");
1257 MachineBasicBlock *WaterBB = *IP;
1258
1259 // If the original WaterList entry was "new water" on this iteration,
1260 // propagate that to the new island. This is just keeping NewWaterList
1261 // updated to match the WaterList, which will be updated below.
1262 if (NewWaterList.count(WaterBB)) {
1263 NewWaterList.erase(WaterBB);
1264 NewWaterList.insert(NewIsland);
1265 }
1266 // The new CPE goes before the following block (NewMBB).
Chris Lattner7896c9f2009-12-03 00:50:42 +00001267 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
Bob Wilsonb9239532009-10-15 20:49:47 +00001268
1269 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001270 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001271 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001272 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001273
1274 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1275 // called while handling branches so that the water will be seen on the
1276 // next iteration for constant pools, but in this context, we don't want
1277 // it. Check for this so it will be removed from the WaterList.
1278 // Also remove any entry from NewWaterList.
1279 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1280 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1281 if (IP != WaterList.end())
1282 NewWaterList.erase(WaterBB);
1283
1284 // We are adding new water. Update NewWaterList.
1285 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001286 }
1287
Bob Wilsonb9239532009-10-15 20:49:47 +00001288 // Remove the original WaterList entry; we want subsequent insertions in
1289 // this vicinity to go after the one we're about to insert. This
1290 // considerably reduces the number of times we have to move the same CPE
1291 // more than once and is also important to ensure the algorithm terminates.
1292 if (IP != WaterList.end())
1293 WaterList.erase(IP);
1294
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001295 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001296 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001297
1298 // Update internal data structures to account for the newly inserted MBB.
1299 UpdateForInsertedWaterBlock(NewIsland);
1300
1301 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001302 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001303
1304 // Now that we have an island to add the CPE to, clone the original CPE and
1305 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001306 U.HighWaterMark = NewIsland;
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001307 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001308 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001309 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmanfe601042010-06-22 15:08:57 +00001310 ++NumCPEs;
Evan Chengc99ef082007-02-09 20:54:44 +00001311
Dale Johannesen8593e412007-04-29 19:19:30 +00001312 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001313 // Compensate for .align 2 in thumb mode.
Jim Grosbach4d8e90a2009-11-19 23:10:28 +00001314 if (isThumb && (BBOffsets[NewIsland->getNumber()]%4 != 0 || HasInlineAsm))
Dale Johannesen8593e412007-04-29 19:19:30 +00001315 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001316 // Increase the size of the island block to account for the new entry.
1317 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001318 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001319
Evan Chenga8e29892007-01-19 07:51:42 +00001320 // Finally, change the CPI in the instruction operand to be ID.
1321 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001322 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001323 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001324 break;
1325 }
Bob Wilson84945262009-05-12 17:09:30 +00001326
Chris Lattner705e07f2009-08-23 03:41:05 +00001327 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1328 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001329
Evan Chenga8e29892007-01-19 07:51:42 +00001330 return true;
1331}
1332
Evan Chenged884f32007-04-03 23:39:48 +00001333/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1334/// sizes and offsets of impacted basic blocks.
1335void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1336 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001337 unsigned Size = CPEMI->getOperand(2).getImm();
1338 CPEMI->eraseFromParent();
1339 BBSizes[CPEBB->getNumber()] -= Size;
1340 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001341 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001342 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001343 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001344 // empty, so fix this.
1345 // All succeeding offsets have the current size value added in, fix this.
1346 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001347 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001348 BBSizes[CPEBB->getNumber()] = 0;
1349 }
Evan Chenged884f32007-04-03 23:39:48 +00001350 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001351 AdjustBBOffsetsAfter(CPEBB, -Size);
1352 // An island has only one predecessor BB and one successor BB. Check if
1353 // this BB's predecessor jumps directly to this BB's successor. This
1354 // shouldn't happen currently.
1355 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1356 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001357}
1358
1359/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1360/// are zero.
1361bool ARMConstantIslands::RemoveUnusedCPEntries() {
1362 unsigned MadeChange = false;
1363 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1364 std::vector<CPEntry> &CPEs = CPEntries[i];
1365 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1366 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1367 RemoveDeadCPEMI(CPEs[j].CPEMI);
1368 CPEs[j].CPEMI = NULL;
1369 MadeChange = true;
1370 }
1371 }
Bob Wilson84945262009-05-12 17:09:30 +00001372 }
Evan Chenged884f32007-04-03 23:39:48 +00001373 return MadeChange;
1374}
1375
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001376/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001377/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001378bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1379 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001380 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001381 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001382 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001383
Chris Lattner705e07f2009-08-23 03:41:05 +00001384 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1385 << " from BB#" << MI->getParent()->getNumber()
1386 << " max delta=" << MaxDisp
1387 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1388 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001389
Dale Johannesen8593e412007-04-29 19:19:30 +00001390 if (BrOffset <= DestOffset) {
1391 // Branch before the Dest.
1392 if (DestOffset-BrOffset <= MaxDisp)
1393 return true;
1394 } else {
1395 if (BrOffset-DestOffset <= MaxDisp)
1396 return true;
1397 }
1398 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001399}
1400
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001401/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1402/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001403bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001404 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001405 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001406
Evan Chengc0dbec72007-01-31 19:57:44 +00001407 // Check to see if the DestBB is already in-range.
1408 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001409 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001410
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001411 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001412 return FixUpUnconditionalBr(MF, Br);
1413 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001414}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001415
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001416/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1417/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001418/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001419/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001420bool
Evan Cheng5657c012009-07-29 02:18:14 +00001421ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001422 MachineInstr *MI = Br.MI;
1423 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001424 if (!isThumb1)
1425 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001426
1427 // Use BL to implement far jump.
1428 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001429 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001430 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001431 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001432 HasFarJump = true;
Dan Gohmanfe601042010-06-22 15:08:57 +00001433 ++NumUBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001434
Chris Lattner705e07f2009-08-23 03:41:05 +00001435 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001436
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001437 return true;
1438}
1439
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001440/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001441/// far away to fit in its displacement field. It is converted to an inverse
1442/// conditional branch + an unconditional branch to the destination.
1443bool
Evan Cheng5657c012009-07-29 02:18:14 +00001444ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001445 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001446 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001447
Bob Wilson39bf0512009-05-12 17:35:29 +00001448 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001449 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001450 // blt L1
1451 // =>
1452 // bge L2
1453 // b L1
1454 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001455 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001456 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001457 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001458
1459 // If the branch is at the end of its MBB and that has a fall-through block,
1460 // direct the updated conditional branch to the fall-through block. Otherwise,
1461 // split the MBB before the next instruction.
1462 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001463 MachineInstr *BMI = &MBB->back();
1464 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001465
Dan Gohmanfe601042010-06-22 15:08:57 +00001466 ++NumCBrFixed;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001467 if (BMI != MI) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001468 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001469 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001470 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001471 // condition and swap destinations:
1472 // beq L1
1473 // b L2
1474 // =>
1475 // bne L2
1476 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001477 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001478 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001479 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1480 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001481 BMI->getOperand(0).setMBB(DestBB);
1482 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001483 MI->getOperand(1).setImm(CC);
1484 return true;
1485 }
1486 }
1487 }
1488
1489 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001490 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001491 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001492 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001493 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001494 BBSizes[MBB->getNumber()] -= delta;
Chris Lattner7896c9f2009-12-03 00:50:42 +00001495 MachineBasicBlock* SplitBB = llvm::next(MachineFunction::iterator(MBB));
Dale Johannesen8593e412007-04-29 19:19:30 +00001496 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001497 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001498 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001499 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001500 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001501
Chris Lattner893e1c92009-08-23 06:49:22 +00001502 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1503 << " also invert condition and change dest. to BB#"
1504 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001505
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001506 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001507 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001508 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesenb6728402009-02-13 02:25:56 +00001509 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001510 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001511 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001512 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001513 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001514 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001515 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001516
1517 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001518 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001519 MI->eraseFromParent();
1520
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001521 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001522 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001523 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001524 return true;
1525}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001526
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001527/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001528/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1529/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001530bool ARMConstantIslands::UndoLRSpillRestore() {
1531 bool MadeChange = false;
1532 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1533 MachineInstr *MI = PushPopMIs[i];
Bob Wilson815baeb2010-03-13 01:08:20 +00001534 // First two operands are predicates.
Evan Cheng44bec522007-05-15 01:29:07 +00001535 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson815baeb2010-03-13 01:08:20 +00001536 MI->getOperand(2).getReg() == ARM::PC &&
1537 MI->getNumExplicitOperands() == 3) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001538 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001539 MI->eraseFromParent();
1540 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001541 }
1542 }
1543 return MadeChange;
1544}
Evan Cheng5657c012009-07-29 02:18:14 +00001545
Evan Chenga1efbbd2009-08-14 00:32:16 +00001546bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1547 bool MadeChange = false;
1548
1549 // Shrink ADR and LDR from constantpool.
1550 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1551 CPUser &U = CPUsers[i];
1552 unsigned Opcode = U.MI->getOpcode();
1553 unsigned NewOpc = 0;
1554 unsigned Scale = 1;
1555 unsigned Bits = 0;
1556 switch (Opcode) {
1557 default: break;
Owen Anderson6b8719f2010-12-13 22:51:08 +00001558 case ARM::t2LEApcrel:
Evan Chenga1efbbd2009-08-14 00:32:16 +00001559 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1560 NewOpc = ARM::tLEApcrel;
1561 Bits = 8;
1562 Scale = 4;
1563 }
1564 break;
1565 case ARM::t2LDRpci:
1566 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1567 NewOpc = ARM::tLDRpci;
1568 Bits = 8;
1569 Scale = 4;
1570 }
1571 break;
1572 }
1573
1574 if (!NewOpc)
1575 continue;
1576
1577 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1578 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1579 // FIXME: Check if offset is multiple of scale if scale is not 4.
1580 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1581 U.MI->setDesc(TII->get(NewOpc));
1582 MachineBasicBlock *MBB = U.MI->getParent();
1583 BBSizes[MBB->getNumber()] -= 2;
1584 AdjustBBOffsetsAfter(MBB, -2);
1585 ++NumT2CPShrunk;
1586 MadeChange = true;
1587 }
1588 }
1589
Evan Chenga1efbbd2009-08-14 00:32:16 +00001590 MadeChange |= OptimizeThumb2Branches(MF);
Jim Grosbach01dec0e2009-11-12 03:28:35 +00001591 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001592 return MadeChange;
1593}
1594
1595bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001596 bool MadeChange = false;
1597
1598 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1599 ImmBranch &Br = ImmBranches[i];
1600 unsigned Opcode = Br.MI->getOpcode();
1601 unsigned NewOpc = 0;
1602 unsigned Scale = 1;
1603 unsigned Bits = 0;
1604 switch (Opcode) {
1605 default: break;
1606 case ARM::t2B:
1607 NewOpc = ARM::tB;
1608 Bits = 11;
1609 Scale = 2;
1610 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001611 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001612 NewOpc = ARM::tBcc;
1613 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001614 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001615 break;
1616 }
Evan Chengde17fb62009-10-31 23:46:45 +00001617 }
1618 if (NewOpc) {
1619 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1620 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1621 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1622 Br.MI->setDesc(TII->get(NewOpc));
1623 MachineBasicBlock *MBB = Br.MI->getParent();
1624 BBSizes[MBB->getNumber()] -= 2;
1625 AdjustBBOffsetsAfter(MBB, -2);
1626 ++NumT2BrShrunk;
1627 MadeChange = true;
1628 }
1629 }
1630
1631 Opcode = Br.MI->getOpcode();
1632 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001633 continue;
1634
Evan Chengde17fb62009-10-31 23:46:45 +00001635 NewOpc = 0;
1636 unsigned PredReg = 0;
1637 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1638 if (Pred == ARMCC::EQ)
1639 NewOpc = ARM::tCBZ;
1640 else if (Pred == ARMCC::NE)
1641 NewOpc = ARM::tCBNZ;
1642 if (!NewOpc)
1643 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001644 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001645 // Check if the distance is within 126. Subtract starting offset by 2
1646 // because the cmp will be eliminated.
1647 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1648 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1649 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1650 MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
Jim Grosbach97a884d2010-12-07 20:41:06 +00001651 if (CmpMI->getOpcode() == ARM::tCMPi8) {
Evan Chengde17fb62009-10-31 23:46:45 +00001652 unsigned Reg = CmpMI->getOperand(0).getReg();
1653 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1654 if (Pred == ARMCC::AL &&
1655 CmpMI->getOperand(1).getImm() == 0 &&
1656 isARMLowRegister(Reg)) {
1657 MachineBasicBlock *MBB = Br.MI->getParent();
1658 MachineInstr *NewBR =
1659 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1660 .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1661 CmpMI->eraseFromParent();
1662 Br.MI->eraseFromParent();
1663 Br.MI = NewBR;
1664 BBSizes[MBB->getNumber()] -= 2;
1665 AdjustBBOffsetsAfter(MBB, -2);
1666 ++NumCBZ;
1667 MadeChange = true;
1668 }
1669 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001670 }
1671 }
1672
1673 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001674}
1675
Evan Chenga1efbbd2009-08-14 00:32:16 +00001676/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1677/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001678bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1679 bool MadeChange = false;
1680
1681 // FIXME: After the tables are shrunk, can we get rid some of the
1682 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001683 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001684 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001685
Evan Cheng5657c012009-07-29 02:18:14 +00001686 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1687 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1688 MachineInstr *MI = T2JumpTables[i];
1689 const TargetInstrDesc &TID = MI->getDesc();
1690 unsigned NumOps = TID.getNumOperands();
1691 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1692 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1693 unsigned JTI = JTOP.getIndex();
1694 assert(JTI < JT.size());
1695
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001696 bool ByteOk = true;
1697 bool HalfWordOk = true;
Jim Grosbach80697d12009-11-12 17:25:07 +00001698 unsigned JTOffset = GetOffsetOf(MI) + 4;
1699 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Cheng5657c012009-07-29 02:18:14 +00001700 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1701 MachineBasicBlock *MBB = JTBBs[j];
1702 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001703 // Negative offset is not ok. FIXME: We should change BB layout to make
1704 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001705 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001706 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001707 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001708 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001709 HalfWordOk = false;
1710 if (!ByteOk && !HalfWordOk)
1711 break;
1712 }
1713
1714 if (ByteOk || HalfWordOk) {
1715 MachineBasicBlock *MBB = MI->getParent();
1716 unsigned BaseReg = MI->getOperand(0).getReg();
1717 bool BaseRegKill = MI->getOperand(0).isKill();
1718 if (!BaseRegKill)
1719 continue;
1720 unsigned IdxReg = MI->getOperand(1).getReg();
1721 bool IdxRegKill = MI->getOperand(1).isKill();
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001722
1723 // Scan backwards to find the instruction that defines the base
1724 // register. Due to post-RA scheduling, we can't count on it
1725 // immediately preceding the branch instruction.
Evan Cheng5657c012009-07-29 02:18:14 +00001726 MachineBasicBlock::iterator PrevI = MI;
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001727 MachineBasicBlock::iterator B = MBB->begin();
1728 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1729 --PrevI;
1730
1731 // If for some reason we didn't find it, we can't do anything, so
1732 // just skip this one.
1733 if (!PrevI->definesRegister(BaseReg))
Evan Cheng5657c012009-07-29 02:18:14 +00001734 continue;
1735
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001736 MachineInstr *AddrMI = PrevI;
Evan Cheng5657c012009-07-29 02:18:14 +00001737 bool OptOk = true;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001738 // Examine the instruction that calculates the jumptable entry address.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001739 // Make sure it only defines the base register and kills any uses
1740 // other than the index register.
Evan Cheng5657c012009-07-29 02:18:14 +00001741 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1742 const MachineOperand &MO = AddrMI->getOperand(k);
1743 if (!MO.isReg() || !MO.getReg())
1744 continue;
1745 if (MO.isDef() && MO.getReg() != BaseReg) {
1746 OptOk = false;
1747 break;
1748 }
1749 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1750 OptOk = false;
1751 break;
1752 }
1753 }
1754 if (!OptOk)
1755 continue;
1756
Owen Anderson6b8719f2010-12-13 22:51:08 +00001757 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001758 // that gave us the initial base register definition.
1759 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1760 ;
1761
Owen Anderson6b8719f2010-12-13 22:51:08 +00001762 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
Evan Chenga1efbbd2009-08-14 00:32:16 +00001763 // to delete it as well.
Jim Grosbachc7937ae2010-07-07 22:51:22 +00001764 MachineInstr *LeaMI = PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001765 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
Owen Anderson6b8719f2010-12-13 22:51:08 +00001766 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001767 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001768 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001769
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001770 if (!OptOk)
1771 continue;
1772
Jim Grosbachd092a872010-11-29 21:28:32 +00001773 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001774 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1775 .addReg(IdxReg, getKillRegState(IdxRegKill))
1776 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1777 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1778 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1779 // is 2-byte aligned. For now, asm printer will fix it up.
1780 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1781 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1782 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1783 OrigSize += TII->GetInstSizeInBytes(MI);
1784
1785 AddrMI->eraseFromParent();
1786 LeaMI->eraseFromParent();
1787 MI->eraseFromParent();
1788
1789 int delta = OrigSize - NewSize;
1790 BBSizes[MBB->getNumber()] -= delta;
1791 AdjustBBOffsetsAfter(MBB, -delta);
1792
1793 ++NumTBs;
1794 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001795 }
1796 }
1797
1798 return MadeChange;
1799}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001800
Jim Grosbach9249efe2009-11-16 18:55:47 +00001801/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1802/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach80697d12009-11-12 17:25:07 +00001803bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1804 bool MadeChange = false;
1805
1806 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Chris Lattnerb1e80392010-01-25 23:22:00 +00001807 if (MJTI == 0) return false;
Jim Grosbach26b8ef52010-07-07 21:06:51 +00001808
Jim Grosbach80697d12009-11-12 17:25:07 +00001809 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1810 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1811 MachineInstr *MI = T2JumpTables[i];
1812 const TargetInstrDesc &TID = MI->getDesc();
1813 unsigned NumOps = TID.getNumOperands();
1814 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1815 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1816 unsigned JTI = JTOP.getIndex();
1817 assert(JTI < JT.size());
1818
1819 // We prefer if target blocks for the jump table come after the jump
1820 // instruction so we can use TB[BH]. Loop through the target blocks
1821 // and try to adjust them such that that's true.
Jim Grosbach08cbda52009-11-16 18:58:52 +00001822 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001823 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1824 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1825 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach08cbda52009-11-16 18:58:52 +00001826 int DTNumber = MBB->getNumber();
Jim Grosbach80697d12009-11-12 17:25:07 +00001827
Jim Grosbach08cbda52009-11-16 18:58:52 +00001828 if (DTNumber < JTNumber) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001829 // The destination precedes the switch. Try to move the block forward
1830 // so we have a positive offset.
1831 MachineBasicBlock *NewBB =
1832 AdjustJTTargetBlockForward(MBB, MI->getParent());
1833 if (NewBB)
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001834 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach80697d12009-11-12 17:25:07 +00001835 MadeChange = true;
1836 }
1837 }
1838 }
1839
1840 return MadeChange;
1841}
1842
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001843MachineBasicBlock *ARMConstantIslands::
1844AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1845{
1846 MachineFunction &MF = *BB->getParent();
1847
Jim Grosbach03e2d442010-07-07 22:53:35 +00001848 // If the destination block is terminated by an unconditional branch,
Jim Grosbach80697d12009-11-12 17:25:07 +00001849 // try to move it; otherwise, create a new block following the jump
Jim Grosbach08cbda52009-11-16 18:58:52 +00001850 // table that branches back to the actual target. This is a very simple
1851 // heuristic. FIXME: We can definitely improve it.
Jim Grosbach80697d12009-11-12 17:25:07 +00001852 MachineBasicBlock *TBB = 0, *FBB = 0;
1853 SmallVector<MachineOperand, 4> Cond;
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001854 SmallVector<MachineOperand, 4> CondPrior;
1855 MachineFunction::iterator BBi = BB;
1856 MachineFunction::iterator OldPrior = prior(BBi);
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001857
Jim Grosbachca215e72009-11-16 17:10:56 +00001858 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001859 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbachca215e72009-11-16 17:10:56 +00001860
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001861 // If the block ends in an unconditional branch, move it. The prior block
1862 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach08cbda52009-11-16 18:58:52 +00001863 // and make sure we're not trying to move the entry block of the function.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001864 if (!B && Cond.empty() && BB != MF.begin() &&
1865 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach80697d12009-11-12 17:25:07 +00001866 BB->moveAfter(JTBB);
1867 OldPrior->updateTerminator();
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001868 BB->updateTerminator();
Jim Grosbach08cbda52009-11-16 18:58:52 +00001869 // Update numbering to account for the block being moved.
Jim Grosbacha0a95a32009-11-17 01:21:04 +00001870 MF.RenumberBlocks();
Jim Grosbach80697d12009-11-12 17:25:07 +00001871 ++NumJTMoved;
1872 return NULL;
1873 }
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001874
1875 // Create a new MBB for the code after the jump BB.
1876 MachineBasicBlock *NewBB =
1877 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1878 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1879 MF.insert(MBBI, NewBB);
1880
1881 // Add an unconditional branch from NewBB to BB.
1882 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1883 // correspond directly to anything in the source.
1884 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Chris Lattnerc7f3ace2010-04-02 20:16:16 +00001885 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB);
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001886
Jim Grosbach00a6a1f2009-11-14 20:10:18 +00001887 // Update internal data structures to account for the newly inserted MBB.
1888 MF.RenumberBlocks(NewBB);
1889
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001890 // Update the CFG.
1891 NewBB->addSuccessor(BB);
1892 JTBB->removeSuccessor(BB);
1893 JTBB->addSuccessor(NewBB);
1894
Jim Grosbach80697d12009-11-12 17:25:07 +00001895 ++NumJTInserted;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001896 return NewBB;
1897}