blob: 981962522db5e2993477194cc5718c9126aaae26 [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chenga8e29892007-01-19 07:51:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengd3d9d662009-07-23 18:27:47 +000018#include "ARMAddressingModes.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000019#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000020#include "ARMInstrInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000029#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000031#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000034#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000035using namespace llvm;
36
Evan Chenga1efbbd2009-08-14 00:32:16 +000037STATISTIC(NumCPEs, "Number of constpool entries");
38STATISTIC(NumSplit, "Number of uncond branches inserted");
39STATISTIC(NumCBrFixed, "Number of cond branches fixed");
40STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
41STATISTIC(NumTBs, "Number of table branches generated");
42STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000043STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000044STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Evan Chenga8e29892007-01-19 07:51:42 +000045
46namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000047 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000048 /// requires constant pool entries to be scattered among the instructions
49 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000050 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000051 /// special instructions.
52 ///
53 /// The terminology used in this pass includes:
54 /// Islands - Clumps of constants placed in the function.
55 /// Water - Potential places where an island could be formed.
56 /// CPE - A constant pool entry that has been placed somewhere, which
57 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000058 class ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000059 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000060 /// by MBB Number. The two-byte pads required for Thumb alignment are
61 /// counted as part of the following block (i.e., the offset and size for
62 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000063 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000064
Dale Johannesen99c49a42007-02-25 00:47:03 +000065 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000066 /// The two-byte pads required for Thumb alignment are counted as part of
67 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000068 std::vector<unsigned> BBOffsets;
69
Evan Chenga8e29892007-01-19 07:51:42 +000070 /// WaterList - A sorted list of basic blocks where islands could be placed
71 /// (i.e. blocks that don't fall through to the following block, due
72 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000073 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000074
Bob Wilsonb9239532009-10-15 20:49:47 +000075 /// NewWaterList - The subset of WaterList that was created since the
76 /// previous iteration by inserting unconditional branches.
77 SmallSet<MachineBasicBlock*, 4> NewWaterList;
78
Bob Wilson034de5f2009-10-12 18:52:13 +000079 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
80
Evan Chenga8e29892007-01-19 07:51:42 +000081 /// CPUser - One user of a constant pool, keeping the machine instruction
82 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +000083 /// allowed from the instruction to the CP. The HighWaterMark records the
84 /// highest basic block where a new CPEntry can be placed. To ensure this
85 /// pass terminates, the CP entries are initially placed at the end of the
86 /// function and then move monotonically to lower addresses. The
87 /// exception to this rule is when the current CP entry for a particular
88 /// CPUser is out of range, but there is another CP entry for the same
89 /// constant value in range. We want to use the existing in-range CP
90 /// entry, but if it later moves out of range, the search for new water
91 /// should resume where it left off. The HighWaterMark is used to record
92 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +000093 struct CPUser {
94 MachineInstr *MI;
95 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +000096 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +000097 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +000098 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +000099 bool IsSoImm;
100 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
101 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000102 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
103 HighWaterMark = CPEMI->getParent();
104 }
Evan Chenga8e29892007-01-19 07:51:42 +0000105 };
Bob Wilson84945262009-05-12 17:09:30 +0000106
Evan Chenga8e29892007-01-19 07:51:42 +0000107 /// CPUsers - Keep track of all of the machine instructions that use various
108 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000109 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000110
Evan Chengc99ef082007-02-09 20:54:44 +0000111 /// CPEntry - One per constant pool entry, keeping the machine instruction
112 /// pointer, the constpool index, and the number of CPUser's which
113 /// reference this entry.
114 struct CPEntry {
115 MachineInstr *CPEMI;
116 unsigned CPI;
117 unsigned RefCount;
118 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
119 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
120 };
121
122 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000123 /// instructions. For each original constpool index (i.e. those that
124 /// existed upon entry to this pass), it keeps a vector of entries.
125 /// Original elements are cloned as we go along; the clones are
126 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000127 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000128
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000129 /// ImmBranch - One per immediate branch, keeping the machine instruction
130 /// pointer, conditional or unconditional, the max displacement,
131 /// and (if isCond is true) the corresponding unconditional branch
132 /// opcode.
133 struct ImmBranch {
134 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000135 unsigned MaxDisp : 31;
136 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000137 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000138 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
139 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000140 };
141
Evan Cheng2706f972007-05-16 05:14:06 +0000142 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000143 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000144 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000145
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000146 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
147 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000148 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000149
Evan Cheng5657c012009-07-29 02:18:14 +0000150 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
151 SmallVector<MachineInstr*, 4> T2JumpTables;
152
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000153 /// HasFarJump - True if any far jump instruction has been emitted during
154 /// the branch fix up pass.
155 bool HasFarJump;
156
Evan Chenga8e29892007-01-19 07:51:42 +0000157 const TargetInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000158 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000159 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000160 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000161 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000162 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000163 public:
Devang Patel19974732007-05-03 01:11:54 +0000164 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000165 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000166
Evan Cheng5657c012009-07-29 02:18:14 +0000167 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000168
169 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000170 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000171 }
Bob Wilson84945262009-05-12 17:09:30 +0000172
Evan Chenga8e29892007-01-19 07:51:42 +0000173 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000174 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000175 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000176 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng5657c012009-07-29 02:18:14 +0000177 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000178 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000179 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000180 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000181 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000182 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000183 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000184 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000185 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000186 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000187 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000188 void RemoveDeadCPEMI(MachineInstr *CPEMI);
189 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000190 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000191 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
192 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000193 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000194 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000195 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000196 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000197 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000198 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
199 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
200 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000201 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000202 bool OptimizeThumb2Instructions(MachineFunction &MF);
203 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000204 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000205
Evan Chenga8e29892007-01-19 07:51:42 +0000206 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000207 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000208 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000209 };
Devang Patel19974732007-05-03 01:11:54 +0000210 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000211}
212
Dale Johannesen8593e412007-04-29 19:19:30 +0000213/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000214void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000215 assert(BBOffsets.size() == BBSizes.size());
216 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
217 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000218 if (!isThumb)
219 return;
220#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000221 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000222 MBBI != E; ++MBBI) {
223 MachineBasicBlock *MBB = MBBI;
224 if (!MBB->empty() &&
225 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
226 unsigned MBBId = MBB->getNumber();
227 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
228 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000229 }
230 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000231#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000232}
233
234/// print block size and offset information - debugging
235void ARMConstantIslands::dumpBBs() {
236 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000237 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
238 << " size " << BBSizes[J] << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000239 }
240}
241
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000242/// createARMConstantIslandPass - returns an instance of the constpool
243/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000244FunctionPass *llvm::createARMConstantIslandPass() {
245 return new ARMConstantIslands();
246}
247
Evan Cheng5657c012009-07-29 02:18:14 +0000248bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
249 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000250
Evan Cheng5657c012009-07-29 02:18:14 +0000251 TII = MF.getTarget().getInstrInfo();
252 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000253 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
254
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000255 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000256 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000257 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000258
259 HasFarJump = false;
260
Evan Chenga8e29892007-01-19 07:51:42 +0000261 // Renumber all of the machine basic blocks in the function, guaranteeing that
262 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000263 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000264
Evan Chengd26b14c2009-07-31 18:28:05 +0000265 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000266 // This is so we can keep exact track of where the alignment padding goes.
267
Evan Chengd26b14c2009-07-31 18:28:05 +0000268 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000269 // aligned.
270 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000271
Evan Chenga8e29892007-01-19 07:51:42 +0000272 // Perform the initial placement of the constant pool entries. To start with,
273 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000274 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000275 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000276 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000277 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000278 AFI->setAlign(2U);
279 }
Bob Wilson84945262009-05-12 17:09:30 +0000280
Evan Chenga8e29892007-01-19 07:51:42 +0000281 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000282 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000283
Evan Chenga8e29892007-01-19 07:51:42 +0000284 // Do the initial scan of the function, building up information about the
285 // sizes of each block, the location of all the water, and finding all of the
286 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000287 InitialFunctionScan(MF, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000288 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000289
Evan Chenged884f32007-04-03 23:39:48 +0000290 /// Remove dead constant pool entries.
291 RemoveUnusedCPEntries();
292
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000293 // Iteratively place constant pool entries and fix up branches until there
294 // is no change.
295 bool MadeChange = false;
Evan Chengb6879b22009-08-07 07:35:21 +0000296 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000297 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000298 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000299 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000300 CPChange |= HandleConstantPoolUser(MF, i);
301 if (CPChange && ++NoCPIters > 30)
302 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000303 DEBUG(dumpBBs());
Bob Wilsonb9239532009-10-15 20:49:47 +0000304
305 // Clear NewWaterList now. If we split a block for branches, it should
306 // appear as "new water" for the next iteration of constant pool placement.
307 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000308
309 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000310 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000311 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
312 if (BRChange && ++NoBRIters > 30)
313 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000314 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000315
316 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000317 break;
318 MadeChange = true;
319 }
Evan Chenged884f32007-04-03 23:39:48 +0000320
Evan Chenga1efbbd2009-08-14 00:32:16 +0000321 // Shrink 32-bit Thumb2 branch, load, and store instructions.
322 if (isThumb2)
323 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000324
Dale Johannesen8593e412007-04-29 19:19:30 +0000325 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000326 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000327
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000328 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
329 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000330 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000331 MadeChange |= UndoLRSpillRestore();
332
Evan Chenga8e29892007-01-19 07:51:42 +0000333 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000334 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000335 WaterList.clear();
336 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000337 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000338 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000339 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000340 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000341
342 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000343}
344
345/// DoInitialPlacement - Perform the initial placement of the constant pool
346/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000347void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000348 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000349 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000350 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
351 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000352
Evan Chenga8e29892007-01-19 07:51:42 +0000353 // Add all of the constants from the constant pool to the end block, use an
354 // identity mapping of CPI's to CPE's.
355 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000356 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000357
Evan Cheng5657c012009-07-29 02:18:14 +0000358 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000359 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000360 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000361 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
362 // we would have to pad them out or something so that instructions stay
363 // aligned.
364 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
365 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000366 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000367 .addImm(i).addConstantPoolIndex(i).addImm(Size);
368 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000369
370 // Add a new CPEntry, but no corresponding CPUser yet.
371 std::vector<CPEntry> CPEs;
372 CPEs.push_back(CPEntry(CPEMI, i));
373 CPEntries.push_back(CPEs);
374 NumCPEs++;
Chris Lattner893e1c92009-08-23 06:49:22 +0000375 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
376 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000377 }
378}
379
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000380/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000381/// into the block immediately after it.
382static bool BBHasFallthrough(MachineBasicBlock *MBB) {
383 // Get the next machine basic block in the function.
384 MachineFunction::iterator MBBI = MBB;
385 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
386 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000387
Evan Chenga8e29892007-01-19 07:51:42 +0000388 MachineBasicBlock *NextBB = next(MBBI);
389 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
390 E = MBB->succ_end(); I != E; ++I)
391 if (*I == NextBB)
392 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000393
Evan Chenga8e29892007-01-19 07:51:42 +0000394 return false;
395}
396
Evan Chengc99ef082007-02-09 20:54:44 +0000397/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
398/// look up the corresponding CPEntry.
399ARMConstantIslands::CPEntry
400*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
401 const MachineInstr *CPEMI) {
402 std::vector<CPEntry> &CPEs = CPEntries[CPI];
403 // Number of entries per constpool index should be small, just do a
404 // linear search.
405 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
406 if (CPEs[i].CPEMI == CPEMI)
407 return &CPEs[i];
408 }
409 return NULL;
410}
411
Evan Chenga8e29892007-01-19 07:51:42 +0000412/// InitialFunctionScan - Do the initial scan of the function, building up
413/// information about the sizes of each block, the location of all the water,
414/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000415void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000416 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000417 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000418 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000419 MBBI != E; ++MBBI) {
420 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000421
Evan Chenga8e29892007-01-19 07:51:42 +0000422 // If this block doesn't fall through into the next MBB, then this is
423 // 'water' that a constant pool island could be placed.
424 if (!BBHasFallthrough(&MBB))
425 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000426
Evan Chenga8e29892007-01-19 07:51:42 +0000427 unsigned MBBSize = 0;
428 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
429 I != E; ++I) {
430 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000431 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000432
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000433 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000434 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000435 bool isCond = false;
436 unsigned Bits = 0;
437 unsigned Scale = 1;
438 int UOpc = Opc;
439 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000440 default:
441 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000442 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000443 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000444 // be right, functions containing these must be 4-byte aligned.
445 AFI->setAlign(2U);
446 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000447 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000448 MBBSize += 2; // padding
449 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000450 case ARM::t2BR_JT:
451 T2JumpTables.push_back(I);
452 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000453 case ARM::Bcc:
454 isCond = true;
455 UOpc = ARM::B;
456 // Fallthrough
457 case ARM::B:
458 Bits = 24;
459 Scale = 4;
460 break;
461 case ARM::tBcc:
462 isCond = true;
463 UOpc = ARM::tB;
464 Bits = 8;
465 Scale = 2;
466 break;
467 case ARM::tB:
468 Bits = 11;
469 Scale = 2;
470 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000471 case ARM::t2Bcc:
472 isCond = true;
473 UOpc = ARM::t2B;
474 Bits = 20;
475 Scale = 2;
476 break;
477 case ARM::t2B:
478 Bits = 24;
479 Scale = 2;
480 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000481 }
Evan Chengb43216e2007-02-01 10:16:15 +0000482
483 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000484 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000485 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000486 }
487
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000488 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
489 PushPopMIs.push_back(I);
490
Evan Chengd3d9d662009-07-23 18:27:47 +0000491 if (Opc == ARM::CONSTPOOL_ENTRY)
492 continue;
493
Evan Chenga8e29892007-01-19 07:51:42 +0000494 // Scan the instructions for constant pool operands.
495 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000496 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000497 // We found one. The addressing mode tells us the max displacement
498 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000499
Evan Chenga8e29892007-01-19 07:51:42 +0000500 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000501 unsigned Bits = 0;
502 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000503 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000504 bool IsSoImm = false;
505
506 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000507 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000508 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000509 break;
510
511 // Taking the address of a CP entry.
512 case ARM::LEApcrel:
513 // This takes a SoImm, which is 8 bit immediate rotated. We'll
514 // pretend the maximum offset is 255 * 4. Since each instruction
515 // 4 byte wide, this is always correct. We'llc heck for other
516 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000517 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000518 Scale = 4;
519 NegOk = true;
520 IsSoImm = true;
521 break;
522 case ARM::t2LEApcrel:
523 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000524 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000525 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000526 case ARM::tLEApcrel:
527 Bits = 8;
528 Scale = 4;
529 break;
530
531 case ARM::LDR:
532 case ARM::LDRcp:
533 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000534 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000535 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000536 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000537
538 case ARM::tLDRpci:
539 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000540 Bits = 8;
541 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000542 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000543
544 case ARM::FLDD:
545 case ARM::FLDS:
546 Bits = 8;
547 Scale = 4; // +-(offset_8*4)
548 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000549 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000550 }
Evan Chengb43216e2007-02-01 10:16:15 +0000551
Evan Chenga8e29892007-01-19 07:51:42 +0000552 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000553 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000554 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000555 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000556 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000557
558 // Increment corresponding CPEntry reference count.
559 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
560 assert(CPE && "Cannot find a corresponding CPEntry!");
561 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000562
Evan Chenga8e29892007-01-19 07:51:42 +0000563 // Instructions can only use one CP entry, don't bother scanning the
564 // rest of the operands.
565 break;
566 }
567 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000568
Dale Johannesen8593e412007-04-29 19:19:30 +0000569 // In thumb mode, if this block is a constpool island, we may need padding
570 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000571 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000572 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000573 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
574 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000575 MBBSize += 2;
576
Evan Chenga8e29892007-01-19 07:51:42 +0000577 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000578 BBOffsets.push_back(Offset);
579 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000580 }
581}
582
Evan Chenga8e29892007-01-19 07:51:42 +0000583/// GetOffsetOf - Return the current offset of the specified machine instruction
584/// from the start of the function. This offset changes as stuff is moved
585/// around inside the function.
586unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
587 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000588
Evan Chenga8e29892007-01-19 07:51:42 +0000589 // The offset is composed of two things: the sum of the sizes of all MBB's
590 // before this instruction's block, and the offset from the start of the block
591 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000592 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000593
Dale Johannesen8593e412007-04-29 19:19:30 +0000594 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
595 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000596 if (isThumb &&
597 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000598 Offset%4 != 0)
599 Offset += 2;
600
Evan Chenga8e29892007-01-19 07:51:42 +0000601 // Sum instructions before MI in MBB.
602 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
603 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
604 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000605 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000606 }
607}
608
609/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
610/// ID.
611static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
612 const MachineBasicBlock *RHS) {
613 return LHS->getNumber() < RHS->getNumber();
614}
615
616/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
617/// machine function, it upsets all of the block numbers. Renumber the blocks
618/// and update the arrays that parallel this numbering.
619void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
620 // Renumber the MBB's to keep them consequtive.
621 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000622
Evan Chenga8e29892007-01-19 07:51:42 +0000623 // Insert a size into BBSizes to align it properly with the (newly
624 // renumbered) block numbers.
625 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000626
627 // Likewise for BBOffsets.
628 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000629
630 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000631 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000632 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000633 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
634 CompareMBBNumbers);
635 WaterList.insert(IP, NewBB);
636}
637
638
639/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000640/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000641/// account for this change and returns the newly created block.
642MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000643 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000644 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000645
646 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000647 MachineBasicBlock *NewBB =
648 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000649 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000650 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000651
Evan Chenga8e29892007-01-19 07:51:42 +0000652 // Splice the instructions starting with MI over to NewBB.
653 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000654
Evan Chenga8e29892007-01-19 07:51:42 +0000655 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000656 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000657 // There doesn't seem to be meaningful DebugInfo available; this doesn't
658 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000659 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
660 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000661 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000662
Evan Chenga8e29892007-01-19 07:51:42 +0000663 // Update the CFG. All succs of OrigBB are now succs of NewBB.
664 while (!OrigBB->succ_empty()) {
665 MachineBasicBlock *Succ = *OrigBB->succ_begin();
666 OrigBB->removeSuccessor(Succ);
667 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000668
Evan Chenga8e29892007-01-19 07:51:42 +0000669 // This pass should be run after register allocation, so there should be no
670 // PHI nodes to update.
671 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
672 && "PHI nodes should be eliminated by now!");
673 }
Bob Wilson84945262009-05-12 17:09:30 +0000674
Evan Chenga8e29892007-01-19 07:51:42 +0000675 // OrigBB branches to NewBB.
676 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000677
Evan Chenga8e29892007-01-19 07:51:42 +0000678 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000679 // This is almost the same as UpdateForInsertedWaterBlock, except that
680 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000681 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000682
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000683 // Insert a size into BBSizes to align it properly with the (newly
684 // renumbered) block numbers.
685 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000686
Dale Johannesen99c49a42007-02-25 00:47:03 +0000687 // Likewise for BBOffsets.
688 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
689
Bob Wilson84945262009-05-12 17:09:30 +0000690 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000691 // available water after it (but not if it's already there, which happens
692 // when splitting before a conditional branch that is followed by an
693 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000694 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000695 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
696 CompareMBBNumbers);
697 MachineBasicBlock* WaterBB = *IP;
698 if (WaterBB == OrigBB)
699 WaterList.insert(next(IP), NewBB);
700 else
701 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000702 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000703
Dale Johannesen8593e412007-04-29 19:19:30 +0000704 // Figure out how large the first NewMBB is. (It cannot
705 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000706 unsigned NewBBSize = 0;
707 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
708 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000709 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000710
Dale Johannesen99c49a42007-02-25 00:47:03 +0000711 unsigned OrigBBI = OrigBB->getNumber();
712 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000713 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000714 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000715
Evan Chenga8e29892007-01-19 07:51:42 +0000716 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000717 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000718 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000719 BBSizes[OrigBBI] -= NewBBSize - delta;
720
721 // ...and adjust BBOffsets for NewBB accordingly.
722 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
723
724 // All BBOffsets following these blocks must be modified.
725 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000726
727 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000728}
729
Dale Johannesen8593e412007-04-29 19:19:30 +0000730/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000731/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000732/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000733bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000734 unsigned TrialOffset, unsigned MaxDisp,
735 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000736 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
737 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000738 // Effectively, the valid range of displacements is 2 bytes smaller for such
739 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000740 unsigned TotalAdj = 0;
741 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000742 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000743 TotalAdj = 2;
744 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000745 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000746 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000747 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000748 TotalAdj += 2;
749 }
750
751 // In Thumb2 mode, later branch adjustments can shift instructions up and
752 // cause alignment change. In the worst case scenario this can cause the
753 // user's effective address to be subtracted by 2 and the CPE's address to
754 // be plus 2.
755 if (isThumb2 && TotalAdj != 4)
756 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000757
Dale Johannesen99c49a42007-02-25 00:47:03 +0000758 if (UserOffset <= TrialOffset) {
759 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000760 if (TrialOffset - UserOffset <= MaxDisp)
761 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000762 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000763 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000764 if (UserOffset - TrialOffset <= MaxDisp)
765 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000766 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000767 }
768 return false;
769}
770
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000771/// WaterIsInRange - Returns true if a CPE placed after the specified
772/// Water (a basic block) will be in range for the specific MI.
773
774bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000775 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000776 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000777 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000778 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000779
Dale Johannesend959aa42007-04-02 20:31:06 +0000780 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000781 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000782 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000783 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000784
Evan Chengd3d9d662009-07-23 18:27:47 +0000785 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000786}
787
788/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000789/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000790bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000791 MachineInstr *CPEMI, unsigned MaxDisp,
792 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000793 unsigned CPEOffset = GetOffsetOf(CPEMI);
794 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000795
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000796 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000797 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
798 << " max delta=" << MaxDisp
799 << " insn address=" << UserOffset
800 << " CPE address=" << CPEOffset
801 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000802 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000803
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000804 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000805}
806
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000807#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000808/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
809/// unconditionally branches to its only successor.
810static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
811 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
812 return false;
813
814 MachineBasicBlock *Succ = *MBB->succ_begin();
815 MachineBasicBlock *Pred = *MBB->pred_begin();
816 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000817 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
818 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000819 return PredMI->getOperand(0).getMBB() == Succ;
820 return false;
821}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000822#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000823
Bob Wilson84945262009-05-12 17:09:30 +0000824void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000825 int delta) {
826 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000827 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
828 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000829 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000830 // If some existing blocks have padding, adjust the padding as needed, a
831 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000832 if (!isThumb)
833 continue;
834 MachineBasicBlock *MBB = MBBI;
835 if (!MBB->empty()) {
836 // Constant pool entries require padding.
837 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000838 unsigned OldOffset = BBOffsets[i] - delta;
839 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000840 // add new padding
841 BBSizes[i] += 2;
842 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000843 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000844 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000845 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000846 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000847 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000848 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000849 // Thumb1 jump tables require padding. They should be at the end;
850 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000851 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000852 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000853 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
854 unsigned OldMIOffset = NewMIOffset - delta;
855 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000856 // remove existing padding
857 BBSizes[i] -= 2;
858 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000859 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000860 // add new padding
861 BBSizes[i] += 2;
862 delta += 2;
863 }
864 }
865 if (delta==0)
866 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000867 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000868 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000869 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000870}
871
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000872/// DecrementOldEntry - find the constant pool entry with index CPI
873/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000874/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000875/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000876
Evan Chenged884f32007-04-03 23:39:48 +0000877bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000878 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000879 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
880 assert(CPE && "Unexpected!");
881 if (--CPE->RefCount == 0) {
882 RemoveDeadCPEMI(CPEMI);
883 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000884 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000885 return true;
886 }
887 return false;
888}
889
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000890/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
891/// if not, see if an in-range clone of the CPE is in range, and if so,
892/// change the data structures so the user references the clone. Returns:
893/// 0 = no existing entry found
894/// 1 = entry found, and there were no code insertions or deletions
895/// 2 = entry found, and there were code insertions or deletions
896int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
897{
898 MachineInstr *UserMI = U.MI;
899 MachineInstr *CPEMI = U.CPEMI;
900
901 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000902 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000903 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000904 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000905 }
906
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000907 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000908 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000909 std::vector<CPEntry> &CPEs = CPEntries[CPI];
910 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
911 // We already tried this one
912 if (CPEs[i].CPEMI == CPEMI)
913 continue;
914 // Removing CPEs can leave empty entries, skip
915 if (CPEs[i].CPEMI == NULL)
916 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000917 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000918 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
919 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000920 // Point the CPUser node to the replacement
921 U.CPEMI = CPEs[i].CPEMI;
922 // Change the CPI in the instruction operand to refer to the clone.
923 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000924 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000925 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000926 break;
927 }
928 // Adjust the refcount of the clone...
929 CPEs[i].RefCount++;
930 // ...and the original. If we didn't remove the old entry, none of the
931 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000932 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000933 }
934 }
935 return 0;
936}
937
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000938/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
939/// the specific unconditional branch instruction.
940static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000941 switch (Opc) {
942 case ARM::tB:
943 return ((1<<10)-1)*2;
944 case ARM::t2B:
945 return ((1<<23)-1)*2;
946 default:
947 break;
948 }
Jim Grosbach764ab522009-08-11 15:33:49 +0000949
David Goodwin5e47a9a2009-06-30 18:04:13 +0000950 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000951}
952
Bob Wilsonb9239532009-10-15 20:49:47 +0000953/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000954/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +0000955/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +0000956/// is set to the WaterList entry. For Thumb, prefer water that will not
957/// introduce padding to water that will. To ensure that this pass
958/// terminates, the CPE location for a particular CPUser is only allowed to
959/// move to a lower address, so search backward from the end of the list and
960/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000961bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +0000962 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +0000963 if (WaterList.empty())
964 return false;
965
Bob Wilson32c50e82009-10-12 20:45:53 +0000966 bool FoundWaterThatWouldPad = false;
967 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +0000968 for (water_iterator IP = prior(WaterList.end()),
969 B = WaterList.begin();; --IP) {
970 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +0000971 // Check if water is in range and is either at a lower address than the
972 // current "high water mark" or a new water block that was created since
973 // the previous iteration by inserting an unconditional branch. In the
974 // latter case, we want to allow resetting the high water mark back to
975 // this new water since we haven't seen it before. Inserting branches
976 // should be relatively uncommon and when it does happen, we want to be
977 // sure to take advantage of it for all the CPEs near that block, so that
978 // we don't insert more branches than necessary.
979 if (WaterIsInRange(UserOffset, WaterBB, U) &&
980 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
981 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +0000982 unsigned WBBId = WaterBB->getNumber();
983 if (isThumb &&
984 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
985 // This is valid Water, but would introduce padding. Remember
986 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +0000987 if (!FoundWaterThatWouldPad) {
988 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +0000989 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000990 }
Bob Wilson3b757352009-10-12 19:04:03 +0000991 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +0000992 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +0000993 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +0000994 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000995 }
Bob Wilson3b757352009-10-12 19:04:03 +0000996 if (IP == B)
997 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000998 }
Bob Wilson32c50e82009-10-12 20:45:53 +0000999 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001000 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001001 return true;
1002 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001003 return false;
1004}
1005
Bob Wilson84945262009-05-12 17:09:30 +00001006/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001007/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1008/// block is used if in range, and the conditional branch munged so control
1009/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001010/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001011/// block following which the new island can be inserted (the WaterList
1012/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001013void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001014 unsigned UserOffset,
1015 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001016 CPUser &U = CPUsers[CPUserIndex];
1017 MachineInstr *UserMI = U.MI;
1018 MachineInstr *CPEMI = U.CPEMI;
1019 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001020 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001021 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001022 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001023
Bob Wilson36fa5322009-10-15 05:10:36 +00001024 // If the block does not end in an unconditional branch already, and if the
1025 // end of the block is within range, make new water there. (The addition
1026 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1027 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001028 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001029 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001030 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1031 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001032 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001033 if (&UserMBB->back() == UserMI)
1034 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Bob Wilson757652c2009-10-12 21:39:43 +00001035 NewMBB = next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001036 // Add an unconditional branch from UserMBB to fallthrough block.
1037 // Record it for branch lengthening; this new branch will not get out of
1038 // range, but if the preceding conditional branch is out of range, the
1039 // targets will be exchanged, and the altered branch may be out of
1040 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001041 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001042 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
Bob Wilson757652c2009-10-12 21:39:43 +00001043 TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001044 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001045 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001046 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001047 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001048 BBSizes[UserMBB->getNumber()] += delta;
1049 AdjustBBOffsetsAfter(UserMBB, delta);
1050 } else {
1051 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001052 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001053 // and constant pool entries are 4 bytes: if instruction I references
1054 // island CPE, and instruction I+1 references CPE', it will
1055 // not work well to put CPE as far forward as possible, since then
1056 // CPE' cannot immediately follow it (that location is 2 bytes
1057 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001058 // a new island. So, we make a first guess, then walk through the
1059 // instructions between the one currently being looked at and the
1060 // possible insertion point, and make sure any other instructions
1061 // that reference CPEs will be able to use the same island area;
1062 // if not, we back up the insertion point.
1063
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001064 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001065 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001066 // island is handled inside OffsetIsInRange.
1067 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001068 // This could point off the end of the block if we've already got
1069 // constant pool entries following this block; only the last one is
1070 // in the water list. Back past any possible branches (allow for a
1071 // conditional and a maximally long unconditional).
1072 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001073 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001074 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001075 unsigned EndInsertOffset = BaseInsertOffset +
1076 CPEMI->getOperand(2).getImm();
1077 MachineBasicBlock::iterator MI = UserMI;
1078 ++MI;
1079 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001080 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001081 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001082 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001083 MI = next(MI)) {
1084 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001085 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001086 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001087 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1088 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1089 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001090 }
1091 // This is overly conservative, as we don't account for CPEMIs
1092 // being reused within the block, but it doesn't matter much.
1093 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1094 CPUIndex++;
1095 }
1096 }
Chris Lattner893e1c92009-08-23 06:49:22 +00001097 DEBUG(errs() << "Split in middle of big block\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001098 NewMBB = SplitBlockBeforeInstr(prior(MI));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001099 }
1100}
1101
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001102/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001103/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001104/// place in-range. Return true if we changed any addresses (thus must run
1105/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001106bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001107 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001108 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001109 MachineInstr *UserMI = U.MI;
1110 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001111 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001112 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001113 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001114 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001115 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001116
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001117 // See if the current entry is within range, or there is a clone of it
1118 // in range.
1119 int result = LookForExistingCPEntry(U, UserOffset);
1120 if (result==1) return false;
1121 else if (result==2) return true;
1122
1123 // No existing clone of this CPE is within range.
1124 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001125 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001126
Bob Wilsonf98032e2009-10-12 21:23:15 +00001127 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001128 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1129 MachineBasicBlock *NewMBB;
1130 water_iterator IP;
1131 if (LookForWater(U, UserOffset, IP)) {
1132 DEBUG(errs() << "found water in range\n");
1133 MachineBasicBlock *WaterBB = *IP;
1134
1135 // If the original WaterList entry was "new water" on this iteration,
1136 // propagate that to the new island. This is just keeping NewWaterList
1137 // updated to match the WaterList, which will be updated below.
1138 if (NewWaterList.count(WaterBB)) {
1139 NewWaterList.erase(WaterBB);
1140 NewWaterList.insert(NewIsland);
1141 }
1142 // The new CPE goes before the following block (NewMBB).
1143 NewMBB = next(MachineFunction::iterator(WaterBB));
1144
1145 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001146 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001147 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001148 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001149
1150 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1151 // called while handling branches so that the water will be seen on the
1152 // next iteration for constant pools, but in this context, we don't want
1153 // it. Check for this so it will be removed from the WaterList.
1154 // Also remove any entry from NewWaterList.
1155 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1156 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1157 if (IP != WaterList.end())
1158 NewWaterList.erase(WaterBB);
1159
1160 // We are adding new water. Update NewWaterList.
1161 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001162 }
1163
Bob Wilsonb9239532009-10-15 20:49:47 +00001164 // Remove the original WaterList entry; we want subsequent insertions in
1165 // this vicinity to go after the one we're about to insert. This
1166 // considerably reduces the number of times we have to move the same CPE
1167 // more than once and is also important to ensure the algorithm terminates.
1168 if (IP != WaterList.end())
1169 WaterList.erase(IP);
1170
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001171 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001172 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001173
1174 // Update internal data structures to account for the newly inserted MBB.
1175 UpdateForInsertedWaterBlock(NewIsland);
1176
1177 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001178 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001179
1180 // Now that we have an island to add the CPE to, clone the original CPE and
1181 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001182 U.HighWaterMark = NewIsland;
Dale Johannesenb6728402009-02-13 02:25:56 +00001183 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1184 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001185 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001186 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001187 NumCPEs++;
1188
Dale Johannesen8593e412007-04-29 19:19:30 +00001189 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001190 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001191 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001192 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001193 // Increase the size of the island block to account for the new entry.
1194 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001195 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001196
Evan Chenga8e29892007-01-19 07:51:42 +00001197 // Finally, change the CPI in the instruction operand to be ID.
1198 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001199 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001200 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001201 break;
1202 }
Bob Wilson84945262009-05-12 17:09:30 +00001203
Chris Lattner705e07f2009-08-23 03:41:05 +00001204 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1205 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001206
Evan Chenga8e29892007-01-19 07:51:42 +00001207 return true;
1208}
1209
Evan Chenged884f32007-04-03 23:39:48 +00001210/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1211/// sizes and offsets of impacted basic blocks.
1212void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1213 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001214 unsigned Size = CPEMI->getOperand(2).getImm();
1215 CPEMI->eraseFromParent();
1216 BBSizes[CPEBB->getNumber()] -= Size;
1217 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001218 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001219 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001220 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001221 // empty, so fix this.
1222 // All succeeding offsets have the current size value added in, fix this.
1223 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001224 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001225 BBSizes[CPEBB->getNumber()] = 0;
1226 }
Evan Chenged884f32007-04-03 23:39:48 +00001227 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001228 AdjustBBOffsetsAfter(CPEBB, -Size);
1229 // An island has only one predecessor BB and one successor BB. Check if
1230 // this BB's predecessor jumps directly to this BB's successor. This
1231 // shouldn't happen currently.
1232 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1233 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001234}
1235
1236/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1237/// are zero.
1238bool ARMConstantIslands::RemoveUnusedCPEntries() {
1239 unsigned MadeChange = false;
1240 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1241 std::vector<CPEntry> &CPEs = CPEntries[i];
1242 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1243 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1244 RemoveDeadCPEMI(CPEs[j].CPEMI);
1245 CPEs[j].CPEMI = NULL;
1246 MadeChange = true;
1247 }
1248 }
Bob Wilson84945262009-05-12 17:09:30 +00001249 }
Evan Chenged884f32007-04-03 23:39:48 +00001250 return MadeChange;
1251}
1252
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001253/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001254/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001255bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1256 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001257 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001258 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001259 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001260
Chris Lattner705e07f2009-08-23 03:41:05 +00001261 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1262 << " from BB#" << MI->getParent()->getNumber()
1263 << " max delta=" << MaxDisp
1264 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1265 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001266
Dale Johannesen8593e412007-04-29 19:19:30 +00001267 if (BrOffset <= DestOffset) {
1268 // Branch before the Dest.
1269 if (DestOffset-BrOffset <= MaxDisp)
1270 return true;
1271 } else {
1272 if (BrOffset-DestOffset <= MaxDisp)
1273 return true;
1274 }
1275 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001276}
1277
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001278/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1279/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001280bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001281 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001282 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001283
Evan Chengc0dbec72007-01-31 19:57:44 +00001284 // Check to see if the DestBB is already in-range.
1285 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001286 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001287
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001288 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001289 return FixUpUnconditionalBr(MF, Br);
1290 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001291}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001292
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001293/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1294/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001295/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001296/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001297bool
Evan Cheng5657c012009-07-29 02:18:14 +00001298ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001299 MachineInstr *MI = Br.MI;
1300 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001301 if (!isThumb1)
1302 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001303
1304 // Use BL to implement far jump.
1305 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001306 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001307 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001308 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001309 HasFarJump = true;
1310 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001311
Chris Lattner705e07f2009-08-23 03:41:05 +00001312 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001313
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001314 return true;
1315}
1316
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001317/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001318/// far away to fit in its displacement field. It is converted to an inverse
1319/// conditional branch + an unconditional branch to the destination.
1320bool
Evan Cheng5657c012009-07-29 02:18:14 +00001321ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001322 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001323 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001324
Bob Wilson39bf0512009-05-12 17:35:29 +00001325 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001326 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001327 // blt L1
1328 // =>
1329 // bge L2
1330 // b L1
1331 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001332 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001333 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001334 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001335
1336 // If the branch is at the end of its MBB and that has a fall-through block,
1337 // direct the updated conditional branch to the fall-through block. Otherwise,
1338 // split the MBB before the next instruction.
1339 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001340 MachineInstr *BMI = &MBB->back();
1341 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001342
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001343 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001344 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001345 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001346 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001347 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001348 // condition and swap destinations:
1349 // beq L1
1350 // b L2
1351 // =>
1352 // bne L2
1353 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001354 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001355 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001356 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1357 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001358 BMI->getOperand(0).setMBB(DestBB);
1359 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001360 MI->getOperand(1).setImm(CC);
1361 return true;
1362 }
1363 }
1364 }
1365
1366 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001367 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001368 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001369 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001370 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001371 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001372 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1373 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001374 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001375 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001376 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001377 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001378
Chris Lattner893e1c92009-08-23 06:49:22 +00001379 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1380 << " also invert condition and change dest. to BB#"
1381 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001382
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001383 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001384 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001385 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1386 TII->get(MI->getOpcode()))
1387 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001388 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001389 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001390 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001391 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001392 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001393 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001394
1395 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001396 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001397 MI->eraseFromParent();
1398
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001399 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001400 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001401 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001402 return true;
1403}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001404
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001405/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001406/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1407/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001408bool ARMConstantIslands::UndoLRSpillRestore() {
1409 bool MadeChange = false;
1410 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1411 MachineInstr *MI = PushPopMIs[i];
Evan Cheng10469f82009-10-01 20:54:53 +00001412 // First two operands are predicates, the third is a zero since there
1413 // is no writeback.
Evan Cheng44bec522007-05-15 01:29:07 +00001414 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng10469f82009-10-01 20:54:53 +00001415 MI->getOperand(3).getReg() == ARM::PC &&
1416 MI->getNumExplicitOperands() == 4) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001417 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001418 MI->eraseFromParent();
1419 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001420 }
1421 }
1422 return MadeChange;
1423}
Evan Cheng5657c012009-07-29 02:18:14 +00001424
Evan Chenga1efbbd2009-08-14 00:32:16 +00001425bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1426 bool MadeChange = false;
1427
1428 // Shrink ADR and LDR from constantpool.
1429 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1430 CPUser &U = CPUsers[i];
1431 unsigned Opcode = U.MI->getOpcode();
1432 unsigned NewOpc = 0;
1433 unsigned Scale = 1;
1434 unsigned Bits = 0;
1435 switch (Opcode) {
1436 default: break;
1437 case ARM::t2LEApcrel:
1438 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1439 NewOpc = ARM::tLEApcrel;
1440 Bits = 8;
1441 Scale = 4;
1442 }
1443 break;
1444 case ARM::t2LDRpci:
1445 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1446 NewOpc = ARM::tLDRpci;
1447 Bits = 8;
1448 Scale = 4;
1449 }
1450 break;
1451 }
1452
1453 if (!NewOpc)
1454 continue;
1455
1456 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1457 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1458 // FIXME: Check if offset is multiple of scale if scale is not 4.
1459 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1460 U.MI->setDesc(TII->get(NewOpc));
1461 MachineBasicBlock *MBB = U.MI->getParent();
1462 BBSizes[MBB->getNumber()] -= 2;
1463 AdjustBBOffsetsAfter(MBB, -2);
1464 ++NumT2CPShrunk;
1465 MadeChange = true;
1466 }
1467 }
1468
Evan Chenga1efbbd2009-08-14 00:32:16 +00001469 MadeChange |= OptimizeThumb2Branches(MF);
Evan Cheng31b99dd2009-08-14 18:31:44 +00001470 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga1efbbd2009-08-14 00:32:16 +00001471 return MadeChange;
1472}
1473
1474bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001475 bool MadeChange = false;
1476
1477 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1478 ImmBranch &Br = ImmBranches[i];
1479 unsigned Opcode = Br.MI->getOpcode();
1480 unsigned NewOpc = 0;
1481 unsigned Scale = 1;
1482 unsigned Bits = 0;
1483 switch (Opcode) {
1484 default: break;
1485 case ARM::t2B:
1486 NewOpc = ARM::tB;
1487 Bits = 11;
1488 Scale = 2;
1489 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001490 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001491 NewOpc = ARM::tBcc;
1492 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001493 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001494 break;
1495 }
Evan Chengde17fb62009-10-31 23:46:45 +00001496 }
1497 if (NewOpc) {
1498 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1499 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1500 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1501 Br.MI->setDesc(TII->get(NewOpc));
1502 MachineBasicBlock *MBB = Br.MI->getParent();
1503 BBSizes[MBB->getNumber()] -= 2;
1504 AdjustBBOffsetsAfter(MBB, -2);
1505 ++NumT2BrShrunk;
1506 MadeChange = true;
1507 }
1508 }
1509
1510 Opcode = Br.MI->getOpcode();
1511 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001512 continue;
1513
Evan Chengde17fb62009-10-31 23:46:45 +00001514 NewOpc = 0;
1515 unsigned PredReg = 0;
1516 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1517 if (Pred == ARMCC::EQ)
1518 NewOpc = ARM::tCBZ;
1519 else if (Pred == ARMCC::NE)
1520 NewOpc = ARM::tCBNZ;
1521 if (!NewOpc)
1522 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001523 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001524 // Check if the distance is within 126. Subtract starting offset by 2
1525 // because the cmp will be eliminated.
1526 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1527 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1528 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1529 MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
1530 if (CmpMI->getOpcode() == ARM::tCMPzi8) {
1531 unsigned Reg = CmpMI->getOperand(0).getReg();
1532 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1533 if (Pred == ARMCC::AL &&
1534 CmpMI->getOperand(1).getImm() == 0 &&
1535 isARMLowRegister(Reg)) {
1536 MachineBasicBlock *MBB = Br.MI->getParent();
1537 MachineInstr *NewBR =
1538 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1539 .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1540 CmpMI->eraseFromParent();
1541 Br.MI->eraseFromParent();
1542 Br.MI = NewBR;
1543 BBSizes[MBB->getNumber()] -= 2;
1544 AdjustBBOffsetsAfter(MBB, -2);
1545 ++NumCBZ;
1546 MadeChange = true;
1547 }
1548 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001549 }
1550 }
1551
1552 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001553}
1554
1555
1556/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1557/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001558bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1559 bool MadeChange = false;
1560
1561 // FIXME: After the tables are shrunk, can we get rid some of the
1562 // constantpool tables?
1563 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1564 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1565 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1566 MachineInstr *MI = T2JumpTables[i];
1567 const TargetInstrDesc &TID = MI->getDesc();
1568 unsigned NumOps = TID.getNumOperands();
1569 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1570 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1571 unsigned JTI = JTOP.getIndex();
1572 assert(JTI < JT.size());
1573
1574 bool ByteOk = true;
1575 bool HalfWordOk = true;
1576 unsigned JTOffset = GetOffsetOf(MI) + 4;
1577 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1578 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1579 MachineBasicBlock *MBB = JTBBs[j];
1580 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001581 // Negative offset is not ok. FIXME: We should change BB layout to make
1582 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001583 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001584 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001585 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001586 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001587 HalfWordOk = false;
1588 if (!ByteOk && !HalfWordOk)
1589 break;
1590 }
1591
1592 if (ByteOk || HalfWordOk) {
1593 MachineBasicBlock *MBB = MI->getParent();
1594 unsigned BaseReg = MI->getOperand(0).getReg();
1595 bool BaseRegKill = MI->getOperand(0).isKill();
1596 if (!BaseRegKill)
1597 continue;
1598 unsigned IdxReg = MI->getOperand(1).getReg();
1599 bool IdxRegKill = MI->getOperand(1).isKill();
1600 MachineBasicBlock::iterator PrevI = MI;
1601 if (PrevI == MBB->begin())
1602 continue;
1603
1604 MachineInstr *AddrMI = --PrevI;
1605 bool OptOk = true;
1606 // Examine the instruction that calculate the jumptable entry address.
1607 // If it's not the one just before the t2BR_JT, we won't delete it, then
1608 // it's not worth doing the optimization.
1609 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1610 const MachineOperand &MO = AddrMI->getOperand(k);
1611 if (!MO.isReg() || !MO.getReg())
1612 continue;
1613 if (MO.isDef() && MO.getReg() != BaseReg) {
1614 OptOk = false;
1615 break;
1616 }
1617 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1618 OptOk = false;
1619 break;
1620 }
1621 }
1622 if (!OptOk)
1623 continue;
1624
Evan Chenga1efbbd2009-08-14 00:32:16 +00001625 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1626 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001627 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001628 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1629 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001630 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001631 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001632
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001633 if (!OptOk)
1634 continue;
1635
1636 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1637 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1638 .addReg(IdxReg, getKillRegState(IdxRegKill))
1639 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1640 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1641 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1642 // is 2-byte aligned. For now, asm printer will fix it up.
1643 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1644 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1645 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1646 OrigSize += TII->GetInstSizeInBytes(MI);
1647
1648 AddrMI->eraseFromParent();
1649 LeaMI->eraseFromParent();
1650 MI->eraseFromParent();
1651
1652 int delta = OrigSize - NewSize;
1653 BBSizes[MBB->getNumber()] -= delta;
1654 AdjustBBOffsetsAfter(MBB, -delta);
1655
1656 ++NumTBs;
1657 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001658 }
1659 }
1660
1661 return MadeChange;
1662}