blob: 55c1684028c2add04535d69441885371e21177db [file] [log] [blame]
Bill Wendling18581a42010-12-21 01:54:40 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
Evan Cheng10043e22007-01-19 07:51:42 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Cheng10043e22007-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
Evan Cheng10043e22007-01-19 07:51:42 +000016#include "ARM.h"
Evan Cheng22c7cf52007-01-25 03:12:46 +000017#include "ARMMachineFunctionInfo.h"
Evan Chenga20cde32011-07-20 23:34:39 +000018#include "MCTargetDesc/ARMAddressingModes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "Thumb2InstrInfo.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
Evan Cheng10043e22007-01-19 07:51:42 +000024#include "llvm/CodeGen/MachineConstantPool.h"
25#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Chengc6d70ae2009-07-29 02:18:14 +000026#include "llvm/CodeGen/MachineJumpTableInfo.h"
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Support/CommandLine.h"
Evan Cheng10043e22007-01-19 07:51:42 +000030#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +000032#include "llvm/Support/Format.h"
Chris Lattnera6f074f2009-08-23 03:41:05 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetMachine.h"
Bob Wilson2f9be502009-10-15 20:49:47 +000035#include <algorithm>
Evan Cheng10043e22007-01-19 07:51:42 +000036using namespace llvm;
37
Chandler Carruth84e68b22014-04-22 02:41:26 +000038#define DEBUG_TYPE "arm-cp-islands"
39
Evan Chengdb73d682009-08-14 00:32:16 +000040STATISTIC(NumCPEs, "Number of constpool entries");
41STATISTIC(NumSplit, "Number of uncond branches inserted");
42STATISTIC(NumCBrFixed, "Number of cond branches fixed");
43STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
44STATISTIC(NumTBs, "Number of table branches generated");
45STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Chenge41903b2009-08-14 18:31:44 +000046STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Cheng6f29ad92009-10-31 23:46:45 +000047STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000048STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach5d577142009-11-12 17:25:07 +000049STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000050
51
52static cl::opt<bool>
Jim Grosbachcdde77c2009-11-17 21:24:11 +000053AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach8d92ec42009-11-11 02:47:19 +000054 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Cheng10043e22007-01-19 07:51:42 +000055
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +000056/// UnknownPadding - Return the worst case padding that could result from
57/// unknown offset bits. This does not include alignment padding caused by
58/// known offset bits.
59///
60/// @param LogAlign log2(alignment)
61/// @param KnownBits Number of known low offset bits.
62static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
63 if (KnownBits < LogAlign)
64 return (1u << LogAlign) - (1u << KnownBits);
65 return 0;
66}
67
Evan Cheng10043e22007-01-19 07:51:42 +000068namespace {
Dale Johannesene18b13b2007-02-23 05:02:36 +000069 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Cheng10043e22007-01-19 07:51:42 +000070 /// requires constant pool entries to be scattered among the instructions
71 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesene18b13b2007-02-23 05:02:36 +000072 /// constant pool; instead, it places constants wherever it feels like with
Evan Cheng10043e22007-01-19 07:51:42 +000073 /// special instructions.
74 ///
75 /// The terminology used in this pass includes:
76 /// Islands - Clumps of constants placed in the function.
77 /// Water - Potential places where an island could be formed.
78 /// CPE - A constant pool entry that has been placed somewhere, which
79 /// tracks a list of users.
Nick Lewycky02d5f772009-10-25 06:33:48 +000080 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000081 /// BasicBlockInfo - Information about the offset and size of a single
82 /// basic block.
83 struct BasicBlockInfo {
84 /// Offset - Distance from the beginning of the function to the beginning
85 /// of this basic block.
86 ///
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +000087 /// Offsets are computed assuming worst case padding before an aligned
88 /// block. This means that subtracting basic block offsets always gives a
89 /// conservative estimate of the real distance which may be smaller.
90 ///
91 /// Because worst case padding is used, the computed offset of an aligned
92 /// block may not actually be aligned.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000093 unsigned Offset;
Bob Wilson2f4e56f2009-05-12 17:09:30 +000094
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000095 /// Size - Size of the basic block in bytes. If the block contains
96 /// inline assembly, this is a worst case estimate.
97 ///
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +000098 /// The size does not include any alignment padding whether from the
99 /// beginning of the block, or from an aligned jump table at the end.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000100 unsigned Size;
101
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000102 /// KnownBits - The number of low bits in Offset that are known to be
103 /// exact. The remaining bits of Offset are an upper bound.
104 uint8_t KnownBits;
105
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000106 /// Unalign - When non-zero, the block contains instructions (inline asm)
107 /// of unknown size. The real size may be smaller than Size bytes by a
108 /// multiple of 1 << Unalign.
109 uint8_t Unalign;
110
111 /// PostAlign - When non-zero, the block terminator contains a .align
112 /// directive, so the end of the block is aligned to 1 << PostAlign
113 /// bytes.
114 uint8_t PostAlign;
115
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000116 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
117 PostAlign(0) {}
Jakob Stoklund Olesenaf748e12011-12-07 01:22:52 +0000118
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +0000119 /// Compute the number of known offset bits internally to this block.
120 /// This number should be used to predict worst case padding when
121 /// splitting the block.
122 unsigned internalKnownBits() const {
Jakob Stoklund Olesen8503ba92012-04-30 20:19:00 +0000123 unsigned Bits = Unalign ? Unalign : KnownBits;
124 // If the block size isn't a multiple of the known bits, assume the
125 // worst case padding.
126 if (Size & ((1u << Bits) - 1))
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000127 Bits = countTrailingZeros(Size);
Jakob Stoklund Olesen8503ba92012-04-30 20:19:00 +0000128 return Bits;
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +0000129 }
130
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000131 /// Compute the offset immediately following this block. If LogAlign is
132 /// specified, return the offset the successor block will get if it has
133 /// this alignment.
134 unsigned postOffset(unsigned LogAlign = 0) const {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000135 unsigned PO = Offset + Size;
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000136 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
137 if (!LA)
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000138 return PO;
139 // Add alignment padding from the terminator.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +0000140 return PO + UnknownPadding(LA, internalKnownBits());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000141 }
142
143 /// Compute the number of known low bits of postOffset. If this block
144 /// contains inline asm, the number of known bits drops to the
145 /// instruction alignment. An aligned terminator may increase the number
146 /// of know bits.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +0000147 /// If LogAlign is given, also consider the alignment of the next block.
148 unsigned postKnownBits(unsigned LogAlign = 0) const {
149 return std::max(std::max(unsigned(PostAlign), LogAlign),
150 internalKnownBits());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000151 }
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000152 };
153
154 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen01ee5752007-02-25 00:47:03 +0000155
Evan Cheng10043e22007-01-19 07:51:42 +0000156 /// WaterList - A sorted list of basic blocks where islands could be placed
157 /// (i.e. blocks that don't fall through to the following block, due
158 /// to a return, unreachable, or unconditional branch).
Evan Cheng540f5e02007-02-09 23:59:14 +0000159 std::vector<MachineBasicBlock*> WaterList;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000160
Bob Wilson2f9be502009-10-15 20:49:47 +0000161 /// NewWaterList - The subset of WaterList that was created since the
162 /// previous iteration by inserting unconditional branches.
163 SmallSet<MachineBasicBlock*, 4> NewWaterList;
164
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000165 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
166
Evan Cheng10043e22007-01-19 07:51:42 +0000167 /// CPUser - One user of a constant pool, keeping the machine instruction
168 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson68ead6c2009-10-15 05:52:29 +0000169 /// allowed from the instruction to the CP. The HighWaterMark records the
170 /// highest basic block where a new CPEntry can be placed. To ensure this
171 /// pass terminates, the CP entries are initially placed at the end of the
172 /// function and then move monotonically to lower addresses. The
173 /// exception to this rule is when the current CP entry for a particular
174 /// CPUser is out of range, but there is another CP entry for the same
175 /// constant value in range. We want to use the existing in-range CP
176 /// entry, but if it later moves out of range, the search for new water
177 /// should resume where it left off. The HighWaterMark is used to record
178 /// that point.
Evan Cheng10043e22007-01-19 07:51:42 +0000179 struct CPUser {
180 MachineInstr *MI;
181 MachineInstr *CPEMI;
Bob Wilson68ead6c2009-10-15 05:52:29 +0000182 MachineBasicBlock *HighWaterMark;
Evan Cheng10043e22007-01-19 07:51:42 +0000183 unsigned MaxDisp;
Evan Cheng87aaa192009-07-21 23:56:01 +0000184 bool NegOk;
Evan Chengd2919a12009-07-23 18:27:47 +0000185 bool IsSoImm;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000186 bool KnownAlignment;
Evan Chengd2919a12009-07-23 18:27:47 +0000187 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
188 bool neg, bool soimm)
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000189 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
190 KnownAlignment(false) {
Bob Wilson68ead6c2009-10-15 05:52:29 +0000191 HighWaterMark = CPEMI->getParent();
192 }
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000193 /// getMaxDisp - Returns the maximum displacement supported by MI.
194 /// Correct for unknown alignment.
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000195 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000196 unsigned getMaxDisp() const {
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000197 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000198 }
Evan Cheng10043e22007-01-19 07:51:42 +0000199 };
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000200
Evan Cheng10043e22007-01-19 07:51:42 +0000201 /// CPUsers - Keep track of all of the machine instructions that use various
202 /// constant pools and their max displacement.
Evan Cheng540f5e02007-02-09 23:59:14 +0000203 std::vector<CPUser> CPUsers;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000204
Evan Cheng8b7700f2007-02-09 20:54:44 +0000205 /// CPEntry - One per constant pool entry, keeping the machine instruction
206 /// pointer, the constpool index, and the number of CPUser's which
207 /// reference this entry.
208 struct CPEntry {
209 MachineInstr *CPEMI;
210 unsigned CPI;
211 unsigned RefCount;
212 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
213 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
214 };
215
216 /// CPEntries - Keep track of all of the constant pool entry machine
Tim Northovera603c402015-05-31 19:22:07 +0000217 /// instructions. For each original constpool index (i.e. those that existed
218 /// upon entry to this pass), it keeps a vector of entries. Original
219 /// elements are cloned as we go along; the clones are put in the vector of
220 /// the original element, but have distinct CPIs.
221 ///
222 /// The first half of CPEntries contains generic constants, the second half
223 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
224 /// which vector it will be in here.
Evan Cheng8b7700f2007-02-09 20:54:44 +0000225 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000226
Tim Northovera603c402015-05-31 19:22:07 +0000227 /// Maps a JT index to the offset in CPEntries containing copies of that
228 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
229 DenseMap<int, int> JumpTableEntryIndices;
230
231 /// Maps a JT index to the LEA that actually uses the index to calculate its
232 /// base address.
233 DenseMap<int, int> JumpTableUserIndices;
234
Evan Cheng22c7cf52007-01-25 03:12:46 +0000235 /// ImmBranch - One per immediate branch, keeping the machine instruction
236 /// pointer, conditional or unconditional, the max displacement,
237 /// and (if isCond is true) the corresponding unconditional branch
238 /// opcode.
239 struct ImmBranch {
240 MachineInstr *MI;
Evan Cheng010ae382007-01-25 23:18:59 +0000241 unsigned MaxDisp : 31;
242 bool isCond : 1;
Matthias Braunfa3872e2015-05-18 20:27:55 +0000243 unsigned UncondBr;
244 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
Evan Cheng010ae382007-01-25 23:18:59 +0000245 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Cheng22c7cf52007-01-25 03:12:46 +0000246 };
247
Evan Chengc95f95b2007-05-16 05:14:06 +0000248 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Cheng22c7cf52007-01-25 03:12:46 +0000249 ///
Evan Cheng540f5e02007-02-09 23:59:14 +0000250 std::vector<ImmBranch> ImmBranches;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000251
Evan Cheng7fa69642007-01-30 01:18:38 +0000252 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
253 ///
Evan Cheng8b7700f2007-02-09 20:54:44 +0000254 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Cheng7fa69642007-01-30 01:18:38 +0000255
Evan Chengc6d70ae2009-07-29 02:18:14 +0000256 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
257 SmallVector<MachineInstr*, 4> T2JumpTables;
258
Evan Cheng7fa69642007-01-30 01:18:38 +0000259 /// HasFarJump - True if any far jump instruction has been emitted during
260 /// the branch fix up pass.
261 bool HasFarJump;
262
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000263 MachineFunction *MF;
264 MachineConstantPool *MCP;
Craig Topper07720d82012-03-25 23:49:58 +0000265 const ARMBaseInstrInfo *TII;
Evan Chenge64f48b2009-08-01 06:13:52 +0000266 const ARMSubtarget *STI;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000267 ARMFunctionInfo *AFI;
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000268 bool isThumb;
Evan Chengd2919a12009-07-23 18:27:47 +0000269 bool isThumb1;
David Goodwin27303cd2009-06-30 18:04:13 +0000270 bool isThumb2;
Evan Cheng10043e22007-01-19 07:51:42 +0000271 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000272 static char ID;
Owen Andersona7aed182010-08-06 18:33:48 +0000273 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +0000274
Craig Topper6bc27bf2014-03-10 02:09:33 +0000275 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng10043e22007-01-19 07:51:42 +0000276
Craig Topper6bc27bf2014-03-10 02:09:33 +0000277 const char *getPassName() const override {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000278 return "ARM constant island placement and branch shortening pass";
Evan Cheng10043e22007-01-19 07:51:42 +0000279 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000280
Evan Cheng10043e22007-01-19 07:51:42 +0000281 private:
Tim Northovera603c402015-05-31 19:22:07 +0000282 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
283 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000284 bool BBHasFallthrough(MachineBasicBlock *MBB);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000285 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000286 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000287 void scanFunctionJumpTables();
288 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
289 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
290 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
291 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
292 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
Tim Northovera603c402015-05-31 19:22:07 +0000293 unsigned getCombinedIndex(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000294 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
295 bool findAvailableWater(CPUser&U, unsigned UserOffset,
296 water_iterator &WaterIter);
297 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000298 MachineBasicBlock *&NewMBB);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000299 bool handleConstantPoolUser(unsigned CPUserIndex);
300 void removeDeadCPEMI(MachineInstr *CPEMI);
301 bool removeUnusedCPEntries();
302 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
303 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
304 bool DoDump = false);
305 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000306 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000307 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
308 bool fixupImmediateBr(ImmBranch &Br);
309 bool fixupConditionalBr(ImmBranch &Br);
310 bool fixupUnconditionalBr(ImmBranch &Br);
311 bool undoLRSpillRestore();
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000312 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
Jim Grosbach190e7b62012-03-23 23:07:03 +0000313 bool optimizeThumb2Instructions();
314 bool optimizeThumb2Branches();
315 bool reorderThumb2JumpTables();
Tim Northovera603c402015-05-31 19:22:07 +0000316 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
317 unsigned &DeadSize, bool &CanDeleteLEA,
318 bool &BaseRegKill);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000319 bool optimizeThumb2JumpTables();
320 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000321 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000322
Jim Grosbach190e7b62012-03-23 23:07:03 +0000323 void computeBlockSize(MachineBasicBlock *MBB);
324 unsigned getOffsetOf(MachineInstr *MI) const;
325 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000326 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000327 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000328
Jim Grosbach190e7b62012-03-23 23:07:03 +0000329 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000330 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000331 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000332 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000333 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000334 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000335 }
Evan Cheng10043e22007-01-19 07:51:42 +0000336 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000337 char ARMConstantIslands::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000338}
Evan Cheng10043e22007-01-19 07:51:42 +0000339
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000340/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000341void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000342#ifndef NDEBUG
Craig Toppere30b8ca2016-01-03 19:43:40 +0000343 assert(std::is_sorted(MF->begin(), MF->end(),
344 [this](const MachineBasicBlock &LHS,
345 const MachineBasicBlock &RHS) {
346 return BBInfo[LHS.getNumber()].postOffset() <
347 BBInfo[RHS.getNumber()].postOffset();
348 }));
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000349 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000350 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
351 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000352 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000353 // Verify offset using the real max displacement without the safety
354 // adjustment.
355 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000356 /* DoDump = */ true)) {
357 DEBUG(dbgs() << "OK\n");
358 continue;
359 }
360 DEBUG(dbgs() << "Out of range.\n");
361 dumpBBs();
362 DEBUG(MF->dump());
363 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000364 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000365#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000366}
367
368/// print block size and offset information - debugging
369void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000370 DEBUG({
371 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
372 const BasicBlockInfo &BBI = BBInfo[J];
373 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
374 << " kb=" << unsigned(BBI.KnownBits)
375 << " ua=" << unsigned(BBI.Unalign)
376 << " pa=" << unsigned(BBI.PostAlign)
377 << format(" size=%#x\n", BBInfo[J].Size);
378 }
379 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000380}
381
Evan Cheng22c7cf52007-01-25 03:12:46 +0000382/// createARMConstantIslandPass - returns an instance of the constpool
383/// island pass.
Evan Cheng10043e22007-01-19 07:51:42 +0000384FunctionPass *llvm::createARMConstantIslandPass() {
385 return new ARMConstantIslands();
386}
387
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000388bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
389 MF = &mf;
390 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000391
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000392 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000393 << MCP->getConstants().size() << " CP entries, aligned to "
394 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000395
Eric Christopher1b21f002015-01-29 00:19:33 +0000396 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
397 TII = STI->getInstrInfo();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000398 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000399
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000400 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000401 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000402 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000403
404 HasFarJump = false;
405
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000406 // This pass invalidates liveness information when it splits basic blocks.
407 MF->getRegInfo().invalidateLiveness();
408
Evan Cheng10043e22007-01-19 07:51:42 +0000409 // Renumber all of the machine basic blocks in the function, guaranteeing that
410 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000411 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000412
Jim Grosbach5d577142009-11-12 17:25:07 +0000413 // Try to reorder and otherwise adjust the block layout to make good use
414 // of the TB[BH] instructions.
415 bool MadeChange = false;
416 if (isThumb2 && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000417 scanFunctionJumpTables();
418 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000419 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000420 T2JumpTables.clear();
421 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000422 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000423 }
424
Evan Cheng10043e22007-01-19 07:51:42 +0000425 // Perform the initial placement of the constant pool entries. To start with,
426 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000427 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000428 if (!MCP->isEmpty())
Tim Northovera603c402015-05-31 19:22:07 +0000429 doInitialConstPlacement(CPEMIs);
430
431 if (MF->getJumpTableInfo())
432 doInitialJumpTablePlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000433
Evan Cheng10043e22007-01-19 07:51:42 +0000434 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000435 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000436
Evan Cheng10043e22007-01-19 07:51:42 +0000437 // Do the initial scan of the function, building up information about the
438 // sizes of each block, the location of all the water, and finding all of the
439 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000440 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000441 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000442 DEBUG(dumpBBs());
443
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000444 // Functions with jump tables need an alignment of 4 because they use the ADR
445 // instruction, which aligns the PC to 4 bytes before adding an offset.
446 if (!T2JumpTables.empty())
447 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000448
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000449 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000450 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000451
Evan Cheng7fa69642007-01-30 01:18:38 +0000452 // Iteratively place constant pool entries and fix up branches until there
453 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000454 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000455 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000456 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000457 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000458 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000459 CPChange |= handleConstantPoolUser(i);
Evan Cheng82ff0222009-08-07 07:35:21 +0000460 if (CPChange && ++NoCPIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000461 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000462 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000463
Bob Wilson2f9be502009-10-15 20:49:47 +0000464 // Clear NewWaterList now. If we split a block for branches, it should
465 // appear as "new water" for the next iteration of constant pool placement.
466 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000467
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000468 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000469 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000470 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000471 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000472 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000473 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000474 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000475
476 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000477 break;
478 MadeChange = true;
479 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000480
Evan Chengdb73d682009-08-14 00:32:16 +0000481 // Shrink 32-bit Thumb2 branch, load, and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000482 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000483 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000484
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000485 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000486 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000487
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000488 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
489 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000490 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000491 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000492
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000493 // Save the mapping between original and cloned constpool entries.
494 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
495 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
496 const CPEntry & CPE = CPEntries[i][j];
Tim Northovera603c402015-05-31 19:22:07 +0000497 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
498 AFI->recordCPEClone(i, CPE.CPI);
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000499 }
500 }
501
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000502 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000503
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000504 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000505 WaterList.clear();
506 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000507 CPEntries.clear();
Tim Northovera603c402015-05-31 19:22:07 +0000508 JumpTableEntryIndices.clear();
509 JumpTableUserIndices.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000510 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000511 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000512 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000513
514 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000515}
516
Tim Northovera603c402015-05-31 19:22:07 +0000517/// \brief Perform the initial placement of the regular constant pool entries.
518/// To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000519void
Tim Northovera603c402015-05-31 19:22:07 +0000520ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000521 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000522 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
523 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000524
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000525 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000526 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000527
528 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000529 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000530
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000531 // The function needs to be as aligned as the basic blocks. The linker may
532 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000533 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000534
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000535 // Order the entries in BB by descending alignment. That ensures correct
536 // alignment of all entries as long as BB is sufficiently aligned. Keep
537 // track of the insertion point for each alignment. We are going to bucket
538 // sort the entries as they are created.
539 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000540
Evan Cheng10043e22007-01-19 07:51:42 +0000541 // Add all of the constants from the constant pool to the end block, use an
542 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000543 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000544
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000545 const DataLayout &TD = MF->getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000546 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000547 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000548 assert(Size >= 4 && "Too small constant pool entry");
549 unsigned Align = CPs[i].getAlignment();
550 assert(isPowerOf2_32(Align) && "Invalid alignment");
551 // Verify that all constant pool entries are a multiple of their alignment.
552 // If not, we would have to pad them out so that instructions stay aligned.
553 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
554
555 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
556 unsigned LogAlign = Log2_32(Align);
557 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000558 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000559 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000560 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000561 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000562
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000563 // Ensure that future entries with higher alignment get inserted before
564 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000565 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000566 if (InsPoint[a] == InsAt)
567 InsPoint[a] = CPEMI;
568
Evan Cheng8b7700f2007-02-09 20:54:44 +0000569 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000570 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000571 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000572 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
573 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000574 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000575 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000576}
577
Tim Northovera603c402015-05-31 19:22:07 +0000578/// \brief Do initial placement of the jump tables. Because Thumb2's TBB and TBH
579/// instructions can be made more efficient if the jump table immediately
580/// follows the instruction, it's best to place them immediately next to their
581/// jumps to begin with. In almost all cases they'll never be moved from that
582/// position.
583void ARMConstantIslands::doInitialJumpTablePlacement(
584 std::vector<MachineInstr *> &CPEMIs) {
585 unsigned i = CPEntries.size();
586 auto MJTI = MF->getJumpTableInfo();
587 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
588
589 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
590 for (MachineBasicBlock &MBB : *MF) {
591 auto MI = MBB.getLastNonDebugInstr();
Petr Pavlua7703792015-11-16 16:41:13 +0000592 if (MI == MBB.end())
593 continue;
Tim Northovera603c402015-05-31 19:22:07 +0000594
595 unsigned JTOpcode;
596 switch (MI->getOpcode()) {
597 default:
598 continue;
599 case ARM::BR_JTadd:
600 case ARM::BR_JTr:
601 case ARM::tBR_JTr:
602 case ARM::BR_JTm:
603 JTOpcode = ARM::JUMPTABLE_ADDRS;
604 break;
605 case ARM::t2BR_JT:
606 JTOpcode = ARM::JUMPTABLE_INSTS;
607 break;
608 case ARM::t2TBB_JT:
609 JTOpcode = ARM::JUMPTABLE_TBB;
610 break;
611 case ARM::t2TBH_JT:
612 JTOpcode = ARM::JUMPTABLE_TBH;
613 break;
614 }
615
616 unsigned NumOps = MI->getDesc().getNumOperands();
617 MachineOperand JTOp =
618 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
619 unsigned JTI = JTOp.getIndex();
620 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
621 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
622 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
623 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
624 DebugLoc(), TII->get(JTOpcode))
625 .addImm(i++)
626 .addJumpTableIndex(JTI)
627 .addImm(Size);
628 CPEMIs.push_back(CPEMI);
629 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
630 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
631 if (!LastCorrectlyNumberedBB)
632 LastCorrectlyNumberedBB = &MBB;
633 }
634
635 // If we did anything then we need to renumber the subsequent blocks.
636 if (LastCorrectlyNumberedBB)
637 MF->RenumberBlocks(LastCorrectlyNumberedBB);
638}
639
Dale Johannesene18b13b2007-02-23 05:02:36 +0000640/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000641/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000642bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000643 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000644 MachineFunction::iterator MBBI = MBB->getIterator();
Jim Grosbach84511e12010-06-02 21:53:11 +0000645 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000646 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000647 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000648
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000649 MachineBasicBlock *NextBB = &*std::next(MBBI);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000650 if (std::find(MBB->succ_begin(), MBB->succ_end(), NextBB) == MBB->succ_end())
651 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000652
Tim Northoverab85dcc2014-11-13 17:58:51 +0000653 // Try to analyze the end of the block. A potential fallthrough may already
654 // have an unconditional branch for whatever reason.
655 MachineBasicBlock *TBB, *FBB;
656 SmallVector<MachineOperand, 4> Cond;
657 bool TooDifficult = TII->AnalyzeBranch(*MBB, TBB, FBB, Cond);
658 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000659}
660
Evan Cheng8b7700f2007-02-09 20:54:44 +0000661/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
662/// look up the corresponding CPEntry.
663ARMConstantIslands::CPEntry
664*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
665 const MachineInstr *CPEMI) {
666 std::vector<CPEntry> &CPEs = CPEntries[CPI];
667 // Number of entries per constpool index should be small, just do a
668 // linear search.
669 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
670 if (CPEs[i].CPEMI == CPEMI)
671 return &CPEs[i];
672 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000673 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000674}
675
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000676/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000677/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000678unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
Tim Northovera603c402015-05-31 19:22:07 +0000679 switch (CPEMI->getOpcode()) {
680 case ARM::CONSTPOOL_ENTRY:
681 break;
682 case ARM::JUMPTABLE_TBB:
683 return 0;
684 case ARM::JUMPTABLE_TBH:
685 case ARM::JUMPTABLE_INSTS:
686 return 1;
687 case ARM::JUMPTABLE_ADDRS:
688 return 2;
689 default:
690 llvm_unreachable("unknown constpool entry kind");
691 }
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000692
Tim Northovera603c402015-05-31 19:22:07 +0000693 unsigned CPI = getCombinedIndex(CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000694 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
695 unsigned Align = MCP->getConstants()[CPI].getAlignment();
696 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
697 return Log2_32(Align);
698}
699
Jim Grosbach190e7b62012-03-23 23:07:03 +0000700/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000701/// information about the sizes of each block and the locations of all
702/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000703void ARMConstantIslands::scanFunctionJumpTables() {
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000704 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Jim Grosbach5d577142009-11-12 17:25:07 +0000705 MBBI != E; ++MBBI) {
706 MachineBasicBlock &MBB = *MBBI;
707
Jim Grosbach5d577142009-11-12 17:25:07 +0000708 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
Jim Grosbach9785e592009-11-16 18:58:52 +0000709 I != E; ++I)
Evan Cheng7f8e5632011-12-07 07:15:52 +0000710 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
Jim Grosbach9785e592009-11-16 18:58:52 +0000711 T2JumpTables.push_back(I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000712 }
713}
714
Jim Grosbach190e7b62012-03-23 23:07:03 +0000715/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000716/// information about the sizes of each block, the location of all the water,
717/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000718void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000719initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000720 BBInfo.clear();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000721 BBInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000722
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000723 // First thing, compute the size of all basic blocks, and see if the function
724 // has any inline assembly in it. If so, we have to be conservative about
725 // alignment assumptions, as we don't know for sure the size of any
726 // instructions in the inline assembly.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000727 for (MachineBasicBlock &MBB : *MF)
728 computeBlockSize(&MBB);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000729
730 // The known bits of the entry block offset are determined by the function
731 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000732 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000733
734 // Compute block offsets and known bits.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000735 adjustBBOffsetsAfter(&MF->front());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000736
Bill Wendling18581a42010-12-21 01:54:40 +0000737 // Now go back through the instructions and build up our data structures.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000738 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Evan Cheng10043e22007-01-19 07:51:42 +0000739 MBBI != E; ++MBBI) {
740 MachineBasicBlock &MBB = *MBBI;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000741
Evan Cheng10043e22007-01-19 07:51:42 +0000742 // If this block doesn't fall through into the next MBB, then this is
743 // 'water' that a constant pool island could be placed.
744 if (!BBHasFallthrough(&MBB))
745 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000746
Evan Cheng10043e22007-01-19 07:51:42 +0000747 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
748 I != E; ++I) {
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000749 if (I->isDebugValue())
750 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000751
Matthias Braunfa3872e2015-05-18 20:27:55 +0000752 unsigned Opc = I->getOpcode();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000753 if (I->isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000754 bool isCond = false;
755 unsigned Bits = 0;
756 unsigned Scale = 1;
757 int UOpc = Opc;
758 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000759 default:
760 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000761 case ARM::t2BR_JT:
762 T2JumpTables.push_back(I);
763 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000764 case ARM::Bcc:
765 isCond = true;
766 UOpc = ARM::B;
767 // Fallthrough
768 case ARM::B:
769 Bits = 24;
770 Scale = 4;
771 break;
772 case ARM::tBcc:
773 isCond = true;
774 UOpc = ARM::tB;
775 Bits = 8;
776 Scale = 2;
777 break;
778 case ARM::tB:
779 Bits = 11;
780 Scale = 2;
781 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000782 case ARM::t2Bcc:
783 isCond = true;
784 UOpc = ARM::t2B;
785 Bits = 20;
786 Scale = 2;
787 break;
788 case ARM::t2B:
789 Bits = 24;
790 Scale = 2;
791 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000792 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000793
794 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000795 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengf9a4c692007-02-01 10:16:15 +0000796 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000797 }
798
Evan Cheng7fa69642007-01-30 01:18:38 +0000799 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
800 PushPopMIs.push_back(I);
801
Tim Northovera603c402015-05-31 19:22:07 +0000802 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
803 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
804 Opc == ARM::JUMPTABLE_TBH)
Evan Chengd2919a12009-07-23 18:27:47 +0000805 continue;
806
Evan Cheng10043e22007-01-19 07:51:42 +0000807 // Scan the instructions for constant pool operands.
808 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Tim Northovera603c402015-05-31 19:22:07 +0000809 if (I->getOperand(op).isCPI() || I->getOperand(op).isJTI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000810 // We found one. The addressing mode tells us the max displacement
811 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000812
Evan Cheng10043e22007-01-19 07:51:42 +0000813 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000814 unsigned Bits = 0;
815 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000816 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000817 bool IsSoImm = false;
818
819 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000820 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000821 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000822
823 // Taking the address of a CP entry.
824 case ARM::LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000825 case ARM::LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000826 // This takes a SoImm, which is 8 bit immediate rotated. We'll
827 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000828 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000829 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000830 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000831 Scale = 4;
832 NegOk = true;
833 IsSoImm = true;
834 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000835 case ARM::t2LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000836 case ARM::t2LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000837 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000838 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000839 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000840 case ARM::tLEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000841 case ARM::tLEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000842 Bits = 8;
843 Scale = 4;
844 break;
845
David Majnemer452f1f92013-06-04 17:46:15 +0000846 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000847 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000848 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000849 case ARM::t2LDRpci:
Evan Chengfd522992007-02-01 20:44:52 +0000850 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000851 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000852 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000853
854 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000855 Bits = 8;
856 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000857 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000858
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000859 case ARM::VLDRD:
860 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000861 Bits = 8;
862 Scale = 4; // +-(offset_8*4)
863 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000864 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000865 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000866
Evan Cheng10043e22007-01-19 07:51:42 +0000867 // Remember that this is a user of a CP entry.
Chris Lattnera5bb3702007-12-30 23:10:15 +0000868 unsigned CPI = I->getOperand(op).getIndex();
Tim Northovera603c402015-05-31 19:22:07 +0000869 if (I->getOperand(op).isJTI()) {
870 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
871 CPI = JumpTableEntryIndices[CPI];
872 }
873
Evan Cheng8b7700f2007-02-09 20:54:44 +0000874 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000875 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd2919a12009-07-23 18:27:47 +0000876 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000877
878 // Increment corresponding CPEntry reference count.
879 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
880 assert(CPE && "Cannot find a corresponding CPEntry!");
881 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000882
Evan Cheng10043e22007-01-19 07:51:42 +0000883 // Instructions can only use one CP entry, don't bother scanning the
884 // rest of the operands.
885 break;
886 }
887 }
Evan Cheng10043e22007-01-19 07:51:42 +0000888 }
889}
890
Jim Grosbach190e7b62012-03-23 23:07:03 +0000891/// computeBlockSize - Compute the size and some alignment information for MBB.
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000892/// This function updates BBInfo directly.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000893void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000894 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
895 BBI.Size = 0;
896 BBI.Unalign = 0;
897 BBI.PostAlign = 0;
898
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000899 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
900 ++I) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000901 BBI.Size += TII->GetInstSizeInBytes(I);
902 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
903 // The actual size may be smaller, but still a multiple of the instr size.
Jakob Stoklund Olesen14e024d2011-12-08 01:22:39 +0000904 if (I->isInlineAsm())
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000905 BBI.Unalign = isThumb ? 1 : 2;
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +0000906 // Also consider instructions that may be shrunk later.
907 else if (isThumb && mayOptimizeThumb2Instruction(I))
908 BBI.Unalign = 1;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000909 }
910
911 // tBR_JTr contains a .align 2 directive.
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000912 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000913 BBI.PostAlign = 2;
Chad Rosier73b02822012-07-06 23:13:38 +0000914 MBB->getParent()->ensureAlignment(2);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000915 }
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000916}
917
Jim Grosbach190e7b62012-03-23 23:07:03 +0000918/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000919/// from the start of the function. This offset changes as stuff is moved
920/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000921unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000922 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000923
Evan Cheng10043e22007-01-19 07:51:42 +0000924 // The offset is composed of two things: the sum of the sizes of all MBB's
925 // before this instruction's block, and the offset from the start of the block
926 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000927 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000928
929 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000930 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000931 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +0000932 Offset += TII->GetInstSizeInBytes(I);
Evan Cheng10043e22007-01-19 07:51:42 +0000933 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000934 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000935}
936
937/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
938/// ID.
939static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
940 const MachineBasicBlock *RHS) {
941 return LHS->getNumber() < RHS->getNumber();
942}
943
Jim Grosbach190e7b62012-03-23 23:07:03 +0000944/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000945/// machine function, it upsets all of the block numbers. Renumber the blocks
946/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000947void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000948 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000949 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000950
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000951 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000952 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000953 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000954
955 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000956 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000957 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000958 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
959 CompareMBBNumbers);
960 WaterList.insert(IP, NewBB);
961}
962
963
964/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000965/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000966/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000967MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000968 MachineBasicBlock *OrigBB = MI->getParent();
969
970 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000971 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000972 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000973 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000974 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000975
Evan Cheng10043e22007-01-19 07:51:42 +0000976 // Splice the instructions starting with MI over to NewBB.
977 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000978
Evan Cheng10043e22007-01-19 07:51:42 +0000979 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000980 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000981 // There doesn't seem to be meaningful DebugInfo available; this doesn't
982 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000983 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000984 if (!isThumb)
985 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
986 else
987 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
988 .addImm(ARMCC::AL).addReg(0);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000989 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000990
Evan Cheng10043e22007-01-19 07:51:42 +0000991 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000992 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000993
Evan Cheng10043e22007-01-19 07:51:42 +0000994 // OrigBB branches to NewBB.
995 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000996
Evan Cheng10043e22007-01-19 07:51:42 +0000997 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000998 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000999 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001000 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001001
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001002 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +00001003 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001004 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +00001005
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001006 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +00001007 // available water after it (but not if it's already there, which happens
1008 // when splitting before a conditional branch that is followed by an
1009 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +00001010 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +00001011 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
1012 CompareMBBNumbers);
1013 MachineBasicBlock* WaterBB = *IP;
1014 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001015 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001016 else
1017 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001018 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001019
Dale Johannesenc17dd572010-07-23 22:50:23 +00001020 // Figure out how large the OrigBB is. As the first half of the original
1021 // block, it cannot contain a tablejump. The size includes
1022 // the new jump we added. (It should be possible to do this without
1023 // recounting everything, but it's very confusing, and this is rarely
1024 // executed.)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001025 computeBlockSize(OrigBB);
Dale Johannesen01ee5752007-02-25 00:47:03 +00001026
Dale Johannesenc17dd572010-07-23 22:50:23 +00001027 // Figure out how large the NewMBB is. As the second half of the original
1028 // block, it may contain a tablejump.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001029 computeBlockSize(NewBB);
Dale Johannesenc17dd572010-07-23 22:50:23 +00001030
Dale Johannesen01ee5752007-02-25 00:47:03 +00001031 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001032 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +00001033
1034 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +00001035}
1036
Jim Grosbach190e7b62012-03-23 23:07:03 +00001037/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001038/// displacement computation. Update U.KnownAlignment to match its current
1039/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001040unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
1041 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001042 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
1043 unsigned KnownBits = BBI.internalKnownBits();
1044
1045 // The value read from PC is offset from the actual instruction address.
1046 UserOffset += (isThumb ? 4 : 8);
1047
1048 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
1049 // Make sure U.getMaxDisp() returns a constrained range.
1050 U.KnownAlignment = (KnownBits >= 2);
1051
1052 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
1053 // purposes of the displacement computation; compensate for that here.
1054 // For unknown alignments, getMaxDisp() constrains the range instead.
1055 if (isThumb && U.KnownAlignment)
1056 UserOffset &= ~3u;
1057
1058 return UserOffset;
1059}
1060
Jim Grosbach190e7b62012-03-23 23:07:03 +00001061/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001062/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001063/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001064/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001065/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
1066/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001067bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +00001068 unsigned TrialOffset, unsigned MaxDisp,
1069 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +00001070 if (UserOffset <= TrialOffset) {
1071 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +00001072 if (TrialOffset - UserOffset <= MaxDisp)
1073 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +00001074 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +00001075 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +00001076 if (UserOffset - TrialOffset <= MaxDisp)
1077 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +00001078 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +00001079 }
1080 return false;
1081}
1082
Jim Grosbach190e7b62012-03-23 23:07:03 +00001083/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +00001084/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001085///
1086/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001087bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001088 MachineBasicBlock* Water, CPUser &U,
1089 unsigned &Growth) {
1090 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1091 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1092 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001093 MachineFunction::const_iterator NextBlock = Water->getIterator();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001094 if (++NextBlock == MF->end()) {
1095 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1096 NextBlockAlignment = 0;
1097 } else {
1098 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1099 NextBlockAlignment = NextBlock->getAlignment();
1100 }
1101 unsigned Size = U.CPEMI->getOperand(2).getImm();
1102 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001103
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001104 // The CPE may be able to hide in the alignment padding before the next
1105 // block. It may also cause more padding to be required if it is more aligned
1106 // that the next block.
1107 if (CPEEnd > NextBlockOffset) {
1108 Growth = CPEEnd - NextBlockOffset;
1109 // Compute the padding that would go at the end of the CPE to align the next
1110 // block.
1111 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1112
1113 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001114 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001115 // in blocks between CPE and the user.
1116 if (CPEOffset < UserOffset)
1117 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1118 } else
1119 // CPE fits in existing padding.
1120 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001121
Jim Grosbach190e7b62012-03-23 23:07:03 +00001122 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001123}
1124
Jim Grosbach190e7b62012-03-23 23:07:03 +00001125/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001126/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001127bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001128 MachineInstr *CPEMI, unsigned MaxDisp,
1129 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001130 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001131
Dale Johannesene18b13b2007-02-23 05:02:36 +00001132 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001133 DEBUG({
1134 unsigned Block = MI->getParent()->getNumber();
1135 const BasicBlockInfo &BBI = BBInfo[Block];
1136 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1137 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001138 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001139 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001140 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1141 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1142 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001143 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001144 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001145
Jim Grosbach190e7b62012-03-23 23:07:03 +00001146 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001147}
1148
Evan Chenge4510972009-01-28 00:53:34 +00001149#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001150/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1151/// unconditionally branches to its only successor.
1152static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1153 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1154 return false;
1155
1156 MachineBasicBlock *Succ = *MBB->succ_begin();
1157 MachineBasicBlock *Pred = *MBB->pred_begin();
1158 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001159 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1160 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001161 return PredMI->getOperand(0).getMBB() == Succ;
1162 return false;
1163}
Evan Chenge4510972009-01-28 00:53:34 +00001164#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001165
Jim Grosbach190e7b62012-03-23 23:07:03 +00001166void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001167 unsigned BBNum = BB->getNumber();
1168 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001169 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001170 // Include the alignment of the current block.
1171 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1172 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1173 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001174
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001175 // This is where block i begins. Stop if the offset is already correct,
1176 // and we have updated 2 blocks. This is the maximum number of blocks
1177 // changed before calling this function.
1178 if (i > BBNum + 2 &&
1179 BBInfo[i].Offset == Offset &&
1180 BBInfo[i].KnownBits == KnownBits)
1181 break;
1182
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001183 BBInfo[i].Offset = Offset;
1184 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001185 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001186}
1187
Jim Grosbach190e7b62012-03-23 23:07:03 +00001188/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001189/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001190/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001191/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001192
Jim Grosbach190e7b62012-03-23 23:07:03 +00001193bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1194 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001195 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001196 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1197 assert(CPE && "Unexpected!");
1198 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001199 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001200 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001201 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001202 return true;
1203 }
1204 return false;
1205}
1206
Tim Northovera603c402015-05-31 19:22:07 +00001207unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1208 if (CPEMI->getOperand(1).isCPI())
1209 return CPEMI->getOperand(1).getIndex();
1210
1211 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1212}
1213
Dale Johannesene18b13b2007-02-23 05:02:36 +00001214/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1215/// if not, see if an in-range clone of the CPE is in range, and if so,
1216/// change the data structures so the user references the clone. Returns:
1217/// 0 = no existing entry found
1218/// 1 = entry found, and there were no code insertions or deletions
1219/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001220int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001221{
1222 MachineInstr *UserMI = U.MI;
1223 MachineInstr *CPEMI = U.CPEMI;
1224
1225 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001226 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1227 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001228 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001229 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001230 }
1231
Dale Johannesene18b13b2007-02-23 05:02:36 +00001232 // No. Look for previously created clones of the CPE that are in range.
Tim Northovera603c402015-05-31 19:22:07 +00001233 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001234 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1235 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1236 // We already tried this one
1237 if (CPEs[i].CPEMI == CPEMI)
1238 continue;
1239 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001240 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001241 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001242 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001243 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001244 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001245 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001246 // Point the CPUser node to the replacement
1247 U.CPEMI = CPEs[i].CPEMI;
1248 // Change the CPI in the instruction operand to refer to the clone.
1249 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001250 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001251 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001252 break;
1253 }
1254 // Adjust the refcount of the clone...
1255 CPEs[i].RefCount++;
1256 // ...and the original. If we didn't remove the old entry, none of the
1257 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001258 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001259 }
1260 }
1261 return 0;
1262}
1263
Dale Johannesen440995b2007-02-28 18:41:23 +00001264/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1265/// the specific unconditional branch instruction.
1266static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001267 switch (Opc) {
1268 case ARM::tB:
1269 return ((1<<10)-1)*2;
1270 case ARM::t2B:
1271 return ((1<<23)-1)*2;
1272 default:
1273 break;
1274 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001275
David Goodwin27303cd2009-06-30 18:04:13 +00001276 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001277}
1278
Jim Grosbach190e7b62012-03-23 23:07:03 +00001279/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001280/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001281/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001282/// is set to the WaterList entry. For Thumb, prefer water that will not
1283/// introduce padding to water that will. To ensure that this pass
1284/// terminates, the CPE location for a particular CPUser is only allowed to
1285/// move to a lower address, so search backward from the end of the list and
1286/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001287bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Bob Wilson2f9be502009-10-15 20:49:47 +00001288 water_iterator &WaterIter) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001289 if (WaterList.empty())
1290 return false;
1291
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001292 unsigned BestGrowth = ~0u;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001293 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001294 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001295 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001296 // Check if water is in range and is either at a lower address than the
1297 // current "high water mark" or a new water block that was created since
1298 // the previous iteration by inserting an unconditional branch. In the
1299 // latter case, we want to allow resetting the high water mark back to
1300 // this new water since we haven't seen it before. Inserting branches
1301 // should be relatively uncommon and when it does happen, we want to be
1302 // sure to take advantage of it for all the CPEs near that block, so that
1303 // we don't insert more branches than necessary.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001304 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001305 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001306 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001307 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1308 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001309 // This is the least amount of required padding seen so far.
1310 BestGrowth = Growth;
1311 WaterIter = IP;
1312 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1313 << " Growth=" << Growth << '\n');
1314
1315 // Keep looking unless it is perfect.
1316 if (BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001317 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001318 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001319 if (IP == B)
1320 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001321 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001322 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001323}
1324
Jim Grosbach190e7b62012-03-23 23:07:03 +00001325/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001326/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1327/// block is used if in range, and the conditional branch munged so control
1328/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001329/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001330/// block following which the new island can be inserted (the WaterList
1331/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001332void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001333 unsigned UserOffset,
1334 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001335 CPUser &U = CPUsers[CPUserIndex];
1336 MachineInstr *UserMI = U.MI;
1337 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001338 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001339 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001340 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001341
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001342 // If the block does not end in an unconditional branch already, and if the
1343 // end of the block is within range, make new water there. (The addition
1344 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001345 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001346 if (BBHasFallthrough(UserMBB)) {
1347 // Size of branch to insert.
1348 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001349 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001350 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001351
Jim Grosbach190e7b62012-03-23 23:07:03 +00001352 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001353 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1354 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001355 NewMBB = &*++UserMBB->getIterator();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001356 // Add an unconditional branch from UserMBB to fallthrough block. Record
1357 // it for branch lengthening; this new branch will not get out of range,
1358 // but if the preceding conditional branch is out of range, the targets
1359 // will be exchanged, and the altered branch may be out of range, so the
1360 // machinery has to know about it.
1361 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1362 if (!isThumb)
1363 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1364 else
1365 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1366 .addImm(ARMCC::AL).addReg(0);
1367 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1368 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1369 MaxDisp, false, UncondBr));
Akira Hatanaka442b40c2015-01-08 20:44:50 +00001370 computeBlockSize(UserMBB);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001371 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001372 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001373 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001374 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001375
1376 // What a big block. Find a place within the block to split it. This is a
1377 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1378 // entries are 4 bytes: if instruction I references island CPE, and
1379 // instruction I+1 references CPE', it will not work well to put CPE as far
1380 // forward as possible, since then CPE' cannot immediately follow it (that
1381 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1382 // need to create a new island. So, we make a first guess, then walk through
1383 // the instructions between the one currently being looked at and the
1384 // possible insertion point, and make sure any other instructions that
1385 // reference CPEs will be able to use the same island area; if not, we back
1386 // up the insertion point.
1387
1388 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001389 // point where we can add a 4-byte branch instruction, and then align to
1390 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001391 unsigned LogAlign = MF->getAlignment();
1392 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1393 unsigned KnownBits = UserBBI.internalKnownBits();
1394 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001395 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001396 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1397 BaseInsertOffset));
1398
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001399 // The 4 in the following is for the unconditional branch we'll be inserting
1400 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001401 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001402 BaseInsertOffset -= 4;
1403
1404 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1405 << " la=" << LogAlign
1406 << " kb=" << KnownBits
1407 << " up=" << UPad << '\n');
1408
1409 // This could point off the end of the block if we've already got constant
1410 // pool entries following this block; only the last one is in the water list.
1411 // Back past any possible branches (allow for a conditional and a maximally
1412 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001413 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001414 // Ensure BaseInsertOffset is larger than the offset of the instruction
1415 // following UserMI so that the loop which searches for the split point
1416 // iterates at least once.
1417 BaseInsertOffset =
1418 std::max(UserBBI.postOffset() - UPad - 8,
1419 UserOffset + TII->GetInstSizeInBytes(UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001420 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1421 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001422 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001423 CPEMI->getOperand(2).getImm();
1424 MachineBasicBlock::iterator MI = UserMI;
1425 ++MI;
1426 unsigned CPUIndex = CPUserIndex+1;
1427 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001428 MachineInstr *LastIT = nullptr;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001429 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1430 Offset < BaseInsertOffset;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001431 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001432 assert(MI != UserMBB->end() && "Fell off end of block");
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001433 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1434 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001435 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001436 // Shift intertion point by one unit of alignment so it is within reach.
1437 BaseInsertOffset -= 1u << LogAlign;
1438 EndInsertOffset -= 1u << LogAlign;
1439 }
1440 // This is overly conservative, as we don't account for CPEMIs being
1441 // reused within the block, but it doesn't matter much. Also assume CPEs
1442 // are added in order with alignment padding. We may eventually be able
1443 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001444 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001445 CPUIndex++;
1446 }
1447
1448 // Remember the last IT instruction.
1449 if (MI->getOpcode() == ARM::t2IT)
1450 LastIT = MI;
1451 }
1452
1453 --MI;
1454
1455 // Avoid splitting an IT block.
1456 if (LastIT) {
1457 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001458 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001459 if (CC != ARMCC::AL)
1460 MI = LastIT;
1461 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001462
1463 // We really must not split an IT block.
1464 DEBUG(unsigned PredReg;
1465 assert(!isThumb || getITInstrPredicate(MI, PredReg) == ARMCC::AL));
1466
Jim Grosbach190e7b62012-03-23 23:07:03 +00001467 NewMBB = splitBlockBeforeInstr(MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001468}
1469
Jim Grosbach190e7b62012-03-23 23:07:03 +00001470/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001471/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001472/// place in-range. Return true if we changed any addresses (thus must run
1473/// another pass of branch lengthening), false otherwise.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001474bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001475 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001476 MachineInstr *UserMI = U.MI;
1477 MachineInstr *CPEMI = U.CPEMI;
Tim Northovera603c402015-05-31 19:22:07 +00001478 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001479 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001480 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001481 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001482
Dale Johannesene18b13b2007-02-23 05:02:36 +00001483 // See if the current entry is within range, or there is a clone of it
1484 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001485 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001486 if (result==1) return false;
1487 else if (result==2) return true;
1488
1489 // No existing clone of this CPE is within range.
1490 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001491 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001492
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001493 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001494 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001495 MachineBasicBlock *NewMBB;
1496 water_iterator IP;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001497 if (findAvailableWater(U, UserOffset, IP)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001498 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001499 MachineBasicBlock *WaterBB = *IP;
1500
1501 // If the original WaterList entry was "new water" on this iteration,
1502 // propagate that to the new island. This is just keeping NewWaterList
1503 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001504 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001505 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001506
Bob Wilson2f9be502009-10-15 20:49:47 +00001507 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001508 NewMBB = &*++WaterBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001509 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001510 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001511 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001512 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001513
Jim Grosbach190e7b62012-03-23 23:07:03 +00001514 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001515 // called while handling branches so that the water will be seen on the
1516 // next iteration for constant pools, but in this context, we don't want
1517 // it. Check for this so it will be removed from the WaterList.
1518 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001519 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001520 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1521 if (IP != WaterList.end())
1522 NewWaterList.erase(WaterBB);
1523
1524 // We are adding new water. Update NewWaterList.
1525 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001526 }
1527
Bob Wilson2f9be502009-10-15 20:49:47 +00001528 // Remove the original WaterList entry; we want subsequent insertions in
1529 // this vicinity to go after the one we're about to insert. This
1530 // considerably reduces the number of times we have to move the same CPE
1531 // more than once and is also important to ensure the algorithm terminates.
1532 if (IP != WaterList.end())
1533 WaterList.erase(IP);
1534
Dale Johannesene18b13b2007-02-23 05:02:36 +00001535 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001536 MF->insert(NewMBB->getIterator(), NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001537
1538 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001539 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001540
Dale Johannesene18b13b2007-02-23 05:02:36 +00001541 // Now that we have an island to add the CPE to, clone the original CPE and
1542 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001543 U.HighWaterMark = NewIsland;
Tim Northovera603c402015-05-31 19:22:07 +00001544 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
1545 .addImm(ID).addOperand(CPEMI->getOperand(1)).addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001546 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001547 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001548
Tim Northovera603c402015-05-31 19:22:07 +00001549 // Decrement the old entry, and remove it if refcount becomes 0.
1550 decrementCPEReferenceCount(CPI, CPEMI);
1551
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001552 // Mark the basic block as aligned as required by the const-pool entry.
1553 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001554
Evan Cheng10043e22007-01-19 07:51:42 +00001555 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001556 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001557 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001558
Evan Cheng10043e22007-01-19 07:51:42 +00001559 // Finally, change the CPI in the instruction operand to be ID.
1560 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001561 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001562 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001563 break;
1564 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001565
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001566 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001567 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001568
Evan Cheng10043e22007-01-19 07:51:42 +00001569 return true;
1570}
1571
Jim Grosbach190e7b62012-03-23 23:07:03 +00001572/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001573/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001574void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001575 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001576 unsigned Size = CPEMI->getOperand(2).getImm();
1577 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001578 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001579 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001580 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001581 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001582
Evan Chengab28b9a2013-02-21 18:37:54 +00001583 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001584 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001585 } else
1586 // Entries are sorted by descending alignment, so realign from the front.
1587 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1588
Jim Grosbach190e7b62012-03-23 23:07:03 +00001589 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001590 // An island has only one predecessor BB and one successor BB. Check if
1591 // this BB's predecessor jumps directly to this BB's successor. This
1592 // shouldn't happen currently.
1593 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1594 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001595}
1596
Jim Grosbach190e7b62012-03-23 23:07:03 +00001597/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001598/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001599bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001600 unsigned MadeChange = false;
1601 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1602 std::vector<CPEntry> &CPEs = CPEntries[i];
1603 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1604 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001605 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001606 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001607 MadeChange = true;
1608 }
1609 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001610 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001611 return MadeChange;
1612}
1613
Jim Grosbach190e7b62012-03-23 23:07:03 +00001614/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001615/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001616bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001617 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001618 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001619 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001620 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001621
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001622 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001623 << " from BB#" << MI->getParent()->getNumber()
1624 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001625 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001626 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001627
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001628 if (BrOffset <= DestOffset) {
1629 // Branch before the Dest.
1630 if (DestOffset-BrOffset <= MaxDisp)
1631 return true;
1632 } else {
1633 if (BrOffset-DestOffset <= MaxDisp)
1634 return true;
1635 }
1636 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001637}
1638
Jim Grosbach190e7b62012-03-23 23:07:03 +00001639/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001640/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001641bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001642 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001643 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001644
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001645 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001646 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001647 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001648
Evan Cheng7fa69642007-01-30 01:18:38 +00001649 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001650 return fixupUnconditionalBr(Br);
1651 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001652}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001653
Jim Grosbach190e7b62012-03-23 23:07:03 +00001654/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001655/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001656/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001657/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001658bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001659ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001660 MachineInstr *MI = Br.MI;
1661 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001662 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001663 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001664
1665 // Use BL to implement far jump.
1666 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001667 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001668 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001669 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001670 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001671 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001672
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001673 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001674
Evan Cheng7fa69642007-01-30 01:18:38 +00001675 return true;
1676}
1677
Jim Grosbach190e7b62012-03-23 23:07:03 +00001678/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001679/// far away to fit in its displacement field. It is converted to an inverse
1680/// conditional branch + an unconditional branch to the destination.
1681bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001682ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001683 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001684 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001685
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001686 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001687 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001688 // blt L1
1689 // =>
1690 // bge L2
1691 // b L1
1692 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001693 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001694 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001695 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001696
1697 // If the branch is at the end of its MBB and that has a fall-through block,
1698 // direct the updated conditional branch to the fall-through block. Otherwise,
1699 // split the MBB before the next instruction.
1700 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001701 MachineInstr *BMI = &MBB->back();
1702 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001703
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001704 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001705 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001706 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001707 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001708 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001709 // condition and swap destinations:
1710 // beq L1
1711 // b L2
1712 // =>
1713 // bne L2
1714 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001715 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001716 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001717 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001718 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001719 BMI->getOperand(0).setMBB(DestBB);
1720 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001721 MI->getOperand(1).setImm(CC);
1722 return true;
1723 }
1724 }
1725 }
1726
1727 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001728 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001729 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001730 // branch to the destination.
Nicolas Geoffrayae84bbd2008-04-16 20:10:13 +00001731 int delta = TII->GetInstSizeInBytes(&MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001732 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001733 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001734 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001735 }
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001736 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001737
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001738 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001739 << " also invert condition and change dest. to BB#"
1740 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001741
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001742 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001743 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001744 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001745 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001746 Br.MI = &MBB->back();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001747 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001748 if (isThumb)
1749 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1750 .addImm(ARMCC::AL).addReg(0);
1751 else
1752 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001753 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001754 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001755 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001756
1757 // Remove the old conditional branch. It may or may not still be in MBB.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001758 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001759 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001760 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001761 return true;
1762}
Evan Cheng7fa69642007-01-30 01:18:38 +00001763
Jim Grosbach190e7b62012-03-23 23:07:03 +00001764/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001765/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1766/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001767bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001768 bool MadeChange = false;
1769 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1770 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001771 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001772 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001773 MI->getOperand(2).getReg() == ARM::PC &&
1774 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001775 // Create the new insn and copy the predicate from the old.
1776 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1777 .addOperand(MI->getOperand(0))
1778 .addOperand(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001779 MI->eraseFromParent();
1780 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001781 }
1782 }
1783 return MadeChange;
1784}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001785
Jim Grosbach190e7b62012-03-23 23:07:03 +00001786// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001787// below may shrink MI.
1788bool
1789ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1790 switch(MI->getOpcode()) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001791 // optimizeThumb2Instructions.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001792 case ARM::t2LEApcrel:
1793 case ARM::t2LDRpci:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001794 // optimizeThumb2Branches.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001795 case ARM::t2B:
1796 case ARM::t2Bcc:
1797 case ARM::tBcc:
Jim Grosbach190e7b62012-03-23 23:07:03 +00001798 // optimizeThumb2JumpTables.
Jakob Stoklund Olesen20f1dd52012-01-10 22:32:14 +00001799 case ARM::t2BR_JT:
1800 return true;
1801 }
1802 return false;
1803}
1804
Jim Grosbach190e7b62012-03-23 23:07:03 +00001805bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001806 bool MadeChange = false;
1807
1808 // Shrink ADR and LDR from constantpool.
1809 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1810 CPUser &U = CPUsers[i];
1811 unsigned Opcode = U.MI->getOpcode();
1812 unsigned NewOpc = 0;
1813 unsigned Scale = 1;
1814 unsigned Bits = 0;
1815 switch (Opcode) {
1816 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001817 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001818 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1819 NewOpc = ARM::tLEApcrel;
1820 Bits = 8;
1821 Scale = 4;
1822 }
1823 break;
1824 case ARM::t2LDRpci:
1825 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1826 NewOpc = ARM::tLDRpci;
1827 Bits = 8;
1828 Scale = 4;
1829 }
1830 break;
1831 }
1832
1833 if (!NewOpc)
1834 continue;
1835
Jim Grosbach190e7b62012-03-23 23:07:03 +00001836 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001837 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001838
1839 // Be conservative with inline asm.
1840 if (!U.KnownAlignment)
1841 MaxOffs -= 2;
1842
Evan Chengdb73d682009-08-14 00:32:16 +00001843 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001844 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001845 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001846 U.MI->setDesc(TII->get(NewOpc));
1847 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001848 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001849 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001850 ++NumT2CPShrunk;
1851 MadeChange = true;
1852 }
1853 }
1854
Jim Grosbach190e7b62012-03-23 23:07:03 +00001855 MadeChange |= optimizeThumb2Branches();
1856 MadeChange |= optimizeThumb2JumpTables();
Evan Chengdb73d682009-08-14 00:32:16 +00001857 return MadeChange;
1858}
1859
Jim Grosbach190e7b62012-03-23 23:07:03 +00001860bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001861 bool MadeChange = false;
1862
Peter Collingbourne167668f2015-04-23 20:31:35 +00001863 // The order in which branches appear in ImmBranches is approximately their
1864 // order within the function body. By visiting later branches first, we reduce
1865 // the distance between earlier forward branches and their targets, making it
1866 // more likely that the cbn?z optimization, which can only apply to forward
1867 // branches, will succeed.
1868 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1869 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001870 unsigned Opcode = Br.MI->getOpcode();
1871 unsigned NewOpc = 0;
1872 unsigned Scale = 1;
1873 unsigned Bits = 0;
1874 switch (Opcode) {
1875 default: break;
1876 case ARM::t2B:
1877 NewOpc = ARM::tB;
1878 Bits = 11;
1879 Scale = 2;
1880 break;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001881 case ARM::t2Bcc: {
Evan Chenge41903b2009-08-14 18:31:44 +00001882 NewOpc = ARM::tBcc;
1883 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001884 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001885 break;
1886 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001887 }
1888 if (NewOpc) {
1889 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1890 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001891 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001892 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001893 Br.MI->setDesc(TII->get(NewOpc));
1894 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001895 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001896 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001897 ++NumT2BrShrunk;
1898 MadeChange = true;
1899 }
1900 }
1901
1902 Opcode = Br.MI->getOpcode();
1903 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001904 continue;
1905
Evan Cheng6bb95252012-01-14 01:53:46 +00001906 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1907 // so this transformation is not safe.
1908 if (!Br.MI->killsRegister(ARM::CPSR))
1909 continue;
1910
Evan Cheng6f29ad92009-10-31 23:46:45 +00001911 NewOpc = 0;
1912 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001913 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001914 if (Pred == ARMCC::EQ)
1915 NewOpc = ARM::tCBZ;
1916 else if (Pred == ARMCC::NE)
1917 NewOpc = ARM::tCBNZ;
1918 if (!NewOpc)
1919 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001920 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001921 // Check if the distance is within 126. Subtract starting offset by 2
1922 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001923 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001924 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001925 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001926 MachineBasicBlock::iterator CmpMI = Br.MI;
1927 if (CmpMI != Br.MI->getParent()->begin()) {
1928 --CmpMI;
1929 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1930 unsigned Reg = CmpMI->getOperand(0).getReg();
Craig Topperf6e7e122012-03-27 07:21:54 +00001931 Pred = getInstrPredicate(CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001932 if (Pred == ARMCC::AL &&
1933 CmpMI->getOperand(1).getImm() == 0 &&
1934 isARMLowRegister(Reg)) {
1935 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001936 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001937 MachineInstr *NewBR =
1938 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1939 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1940 CmpMI->eraseFromParent();
1941 Br.MI->eraseFromParent();
1942 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001943 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001944 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001945 ++NumCBZ;
1946 MadeChange = true;
1947 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001948 }
1949 }
Evan Chenge41903b2009-08-14 18:31:44 +00001950 }
1951 }
1952
1953 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001954}
1955
Tim Northovera603c402015-05-31 19:22:07 +00001956static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1957 unsigned BaseReg) {
1958 if (I.getOpcode() != ARM::t2ADDrs)
1959 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001960
Tim Northovera603c402015-05-31 19:22:07 +00001961 if (I.getOperand(0).getReg() != EntryReg)
1962 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001963
Tim Northovera603c402015-05-31 19:22:07 +00001964 if (I.getOperand(1).getReg() != BaseReg)
1965 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001966
Tim Northovera603c402015-05-31 19:22:07 +00001967 // FIXME: what about CC and IdxReg?
1968 return true;
1969}
Tim Northover688f7bb2015-05-13 20:28:32 +00001970
Tim Northovera603c402015-05-31 19:22:07 +00001971/// \brief While trying to form a TBB/TBH instruction, we may (if the table
1972/// doesn't immediately follow the BR_JT) need access to the start of the
1973/// jump-table. We know one instruction that produces such a register; this
1974/// function works out whether that definition can be preserved to the BR_JT,
1975/// possibly by removing an intervening addition (which is usually needed to
1976/// calculate the actual entry to jump to).
1977bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
1978 MachineInstr *LEAMI,
1979 unsigned &DeadSize,
1980 bool &CanDeleteLEA,
1981 bool &BaseRegKill) {
1982 if (JumpMI->getParent() != LEAMI->getParent())
1983 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001984
Tim Northovera603c402015-05-31 19:22:07 +00001985 // Now we hope that we have at least these instructions in the basic block:
1986 // BaseReg = t2LEA ...
1987 // [...]
1988 // EntryReg = t2ADDrs BaseReg, ...
1989 // [...]
1990 // t2BR_JT EntryReg
1991 //
1992 // We have to be very conservative about what we recognise here though. The
1993 // main perturbing factors to watch out for are:
1994 // + Spills at any point in the chain: not direct problems but we would
1995 // expect a blocking Def of the spilled register so in practice what we
1996 // can do is limited.
1997 // + EntryReg == BaseReg: this is the one situation we should allow a Def
1998 // of BaseReg, but only if the t2ADDrs can be removed.
1999 // + Some instruction other than t2ADDrs computing the entry. Not seen in
2000 // the wild, but we should be careful.
2001 unsigned EntryReg = JumpMI->getOperand(0).getReg();
2002 unsigned BaseReg = LEAMI->getOperand(0).getReg();
2003
2004 CanDeleteLEA = true;
2005 BaseRegKill = false;
2006 MachineInstr *RemovableAdd = nullptr;
2007 MachineBasicBlock::iterator I(LEAMI);
2008 for (++I; &*I != JumpMI; ++I) {
2009 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
2010 RemovableAdd = &*I;
2011 break;
2012 }
2013
2014 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
2015 const MachineOperand &MO = I->getOperand(K);
2016 if (!MO.isReg() || !MO.getReg())
2017 continue;
2018 if (MO.isDef() && MO.getReg() == BaseReg)
2019 return false;
2020 if (MO.isUse() && MO.getReg() == BaseReg) {
2021 BaseRegKill = BaseRegKill || MO.isKill();
2022 CanDeleteLEA = false;
2023 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002024 }
2025 }
2026
Tim Northovera603c402015-05-31 19:22:07 +00002027 if (!RemovableAdd)
2028 return true;
Tim Northover688f7bb2015-05-13 20:28:32 +00002029
Tim Northovera603c402015-05-31 19:22:07 +00002030 // Check the add really is removable, and that nothing else in the block
2031 // clobbers BaseReg.
2032 for (++I; &*I != JumpMI; ++I) {
2033 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
2034 const MachineOperand &MO = I->getOperand(K);
2035 if (!MO.isReg() || !MO.getReg())
2036 continue;
2037 if (MO.isDef() && MO.getReg() == BaseReg)
2038 return false;
2039 if (MO.isUse() && MO.getReg() == EntryReg)
2040 RemovableAdd = nullptr;
2041 }
2042 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002043
Tim Northovera603c402015-05-31 19:22:07 +00002044 if (RemovableAdd) {
2045 RemovableAdd->eraseFromParent();
2046 DeadSize += 4;
2047 } else if (BaseReg == EntryReg) {
2048 // The add wasn't removable, but clobbered the base for the TBB. So we can't
2049 // preserve it.
2050 return false;
2051 }
Tim Northover688f7bb2015-05-13 20:28:32 +00002052
Tim Northovera603c402015-05-31 19:22:07 +00002053 // We reached the end of the block without seeing another definition of
2054 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
2055 // used in the TBB/TBH if necessary.
2056 return true;
2057}
Tim Northover688f7bb2015-05-13 20:28:32 +00002058
Tim Northovera603c402015-05-31 19:22:07 +00002059/// \brief Returns whether CPEMI is the first instruction in the block
2060/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
2061/// we can switch the first register to PC and usually remove the address
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002062/// calculation that preceded it.
Tim Northovera603c402015-05-31 19:22:07 +00002063static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002064 MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
Tim Northovera603c402015-05-31 19:22:07 +00002065 MachineFunction *MF = MBB->getParent();
2066 ++MBB;
2067
2068 return MBB != MF->end() && MBB->begin() != MBB->end() &&
2069 &*MBB->begin() == CPEMI;
Tim Northover688f7bb2015-05-13 20:28:32 +00002070}
2071
Jim Grosbach190e7b62012-03-23 23:07:03 +00002072/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00002073/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002074bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00002075 bool MadeChange = false;
2076
2077 // FIXME: After the tables are shrunk, can we get rid some of the
2078 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002079 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002080 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002081
Evan Chengc6d70ae2009-07-29 02:18:14 +00002082 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2083 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2084 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002085 const MCInstrDesc &MCID = MI->getDesc();
2086 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002087 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Evan Chengc6d70ae2009-07-29 02:18:14 +00002088 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2089 unsigned JTI = JTOP.getIndex();
2090 assert(JTI < JT.size());
2091
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002092 bool ByteOk = true;
2093 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00002094 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00002095 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002096 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2097 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00002098 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00002099 // Negative offset is not ok. FIXME: We should change BB layout to make
2100 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00002101 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002102 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00002103 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00002104 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002105 HalfWordOk = false;
2106 if (!ByteOk && !HalfWordOk)
2107 break;
2108 }
2109
Tim Northovera603c402015-05-31 19:22:07 +00002110 if (!ByteOk && !HalfWordOk)
2111 continue;
Jim Grosbach40eda102010-07-07 22:51:22 +00002112
Tim Northovera603c402015-05-31 19:22:07 +00002113 MachineBasicBlock *MBB = MI->getParent();
2114 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2115 continue;
2116 unsigned IdxReg = MI->getOperand(1).getReg();
2117 bool IdxRegKill = MI->getOperand(1).isKill();
2118
2119 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
2120 unsigned DeadSize = 0;
2121 bool CanDeleteLEA = false;
2122 bool BaseRegKill = false;
2123 bool PreservedBaseReg =
2124 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
2125
2126 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2127 continue;
2128
2129 DEBUG(dbgs() << "Shrink JT: " << *MI);
2130 MachineInstr *CPEMI = User.CPEMI;
2131 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
2132 MachineBasicBlock::iterator MI_JT = MI;
2133 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00002134 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Tim Northovera603c402015-05-31 19:22:07 +00002135 .addReg(User.MI->getOperand(0).getReg(),
2136 getKillRegState(BaseRegKill))
2137 .addReg(IdxReg, getKillRegState(IdxRegKill))
2138 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2139 .addImm(CPEMI->getOperand(0).getImm());
2140 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00002141
Tim Northovera603c402015-05-31 19:22:07 +00002142 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2143 CPEMI->setDesc(TII->get(JTOpc));
Evan Chenge64f48b2009-08-01 06:13:52 +00002144
Tim Northovera603c402015-05-31 19:22:07 +00002145 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2146 NewJTMI->getOperand(0).setReg(ARM::PC);
2147 NewJTMI->getOperand(0).setIsKill(false);
2148
2149 if (CanDeleteLEA) {
2150 User.MI->eraseFromParent();
2151 DeadSize += 4;
2152
2153 // The LEA was eliminated, the TBB instruction becomes the only new user
2154 // of the jump table.
2155 User.MI = NewJTMI;
2156 User.MaxDisp = 4;
2157 User.NegOk = false;
2158 User.IsSoImm = false;
2159 User.KnownAlignment = false;
2160 } else {
2161 // The LEA couldn't be eliminated, so we must add another CPUser to
2162 // record the TBB or TBH use.
2163 int CPEntryIdx = JumpTableEntryIndices[JTI];
2164 auto &CPEs = CPEntries[CPEntryIdx];
2165 auto Entry = std::find_if(CPEs.begin(), CPEs.end(), [&](CPEntry &E) {
2166 return E.CPEMI == User.CPEMI;
2167 });
2168 ++Entry->RefCount;
2169 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2170 }
Evan Chengc6d70ae2009-07-29 02:18:14 +00002171 }
Tim Northovera603c402015-05-31 19:22:07 +00002172
2173 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
2174 unsigned OrigSize = TII->GetInstSizeInBytes(MI);
2175 MI->eraseFromParent();
2176
2177 int Delta = OrigSize - NewSize + DeadSize;
2178 BBInfo[MBB->getNumber()].Size -= Delta;
2179 adjustBBOffsetsAfter(MBB);
2180
2181 ++NumTBs;
2182 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002183 }
2184
2185 return MadeChange;
2186}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002187
Jim Grosbach190e7b62012-03-23 23:07:03 +00002188/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00002189/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002190bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00002191 bool MadeChange = false;
2192
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002193 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002194 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002195
Jim Grosbach5d577142009-11-12 17:25:07 +00002196 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2197 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2198 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002199 const MCInstrDesc &MCID = MI->getDesc();
2200 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002201 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002202 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2203 unsigned JTI = JTOP.getIndex();
2204 assert(JTI < JT.size());
2205
2206 // We prefer if target blocks for the jump table come after the jump
2207 // instruction so we can use TB[BH]. Loop through the target blocks
2208 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002209 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002210 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2211 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2212 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002213 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002214
Jim Grosbach9785e592009-11-16 18:58:52 +00002215 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002216 // The destination precedes the switch. Try to move the block forward
2217 // so we have a positive offset.
2218 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002219 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002220 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002221 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002222 MadeChange = true;
2223 }
2224 }
2225 }
2226
2227 return MadeChange;
2228}
2229
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002230MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002231adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002232 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002233 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002234 // table that branches back to the actual target. This is a very simple
2235 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002236 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002237 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002238 SmallVector<MachineOperand, 4> CondPrior;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002239 MachineFunction::iterator BBi = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002240 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002241
Jim Grosbach47d5e332009-11-16 17:10:56 +00002242 // If the block terminator isn't analyzable, don't try to move the block
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002243 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002244
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002245 // If the block ends in an unconditional branch, move it. The prior block
2246 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002247 // and make sure we're not trying to move the entry block of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002248 if (!B && Cond.empty() && BB != MF->begin() &&
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002249 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002250 BB->moveAfter(JTBB);
2251 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002252 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002253 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002254 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002255 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002256 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002257 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002258
2259 // Create a new MBB for the code after the jump BB.
2260 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002261 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002262 MachineFunction::iterator MBBI = ++JTBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002263 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002264
2265 // Add an unconditional branch from NewBB to BB.
2266 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2267 // correspond directly to anything in the source.
2268 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
Owen Anderson29cfe6c2011-09-09 21:48:23 +00002269 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2270 .addImm(ARMCC::AL).addReg(0);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002271
Jim Grosbach43d21082009-11-14 20:10:18 +00002272 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002273 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002274
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002275 // Update the CFG.
2276 NewBB->addSuccessor(BB);
Cong Houd97c1002015-12-01 05:29:22 +00002277 JTBB->replaceSuccessor(BB, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002278
Jim Grosbach5d577142009-11-12 17:25:07 +00002279 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002280 return NewBB;
2281}