blob: 70746c6ea65b476dad0309294dd81a9f3b466ce8 [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"
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +000017#include "ARMBasicBlockInfo.h"
Evan Cheng22c7cf52007-01-25 03:12:46 +000018#include "ARMMachineFunctionInfo.h"
Evan Chenga20cde32011-07-20 23:34:39 +000019#include "MCTargetDesc/ARMAddressingModes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "Thumb2InstrInfo.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Statistic.h"
Evan Cheng10043e22007-01-19 07:51:42 +000025#include "llvm/CodeGen/MachineConstantPool.h"
26#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Chengc6d70ae2009-07-29 02:18:14 +000027#include "llvm/CodeGen/MachineJumpTableInfo.h"
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DataLayout.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Support/CommandLine.h"
Evan Cheng10043e22007-01-19 07:51:42 +000031#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +000033#include "llvm/Support/Format.h"
Chris Lattnera6f074f2009-08-23 03:41:05 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetMachine.h"
Bob Wilson2f9be502009-10-15 20:49:47 +000036#include <algorithm>
Evan Cheng10043e22007-01-19 07:51:42 +000037using namespace llvm;
38
Chandler Carruth84e68b22014-04-22 02:41:26 +000039#define DEBUG_TYPE "arm-cp-islands"
40
Evan Chengdb73d682009-08-14 00:32:16 +000041STATISTIC(NumCPEs, "Number of constpool entries");
42STATISTIC(NumSplit, "Number of uncond branches inserted");
43STATISTIC(NumCBrFixed, "Number of cond branches fixed");
44STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
45STATISTIC(NumTBs, "Number of table branches generated");
46STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Chenge41903b2009-08-14 18:31:44 +000047STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Cheng6f29ad92009-10-31 23:46:45 +000048STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000049STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
Jim Grosbach5d577142009-11-12 17:25:07 +000050STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
Jim Grosbach8d92ec42009-11-11 02:47:19 +000051
52
53static cl::opt<bool>
Jim Grosbachcdde77c2009-11-17 21:24:11 +000054AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
Jim Grosbach8d92ec42009-11-11 02:47:19 +000055 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Cheng10043e22007-01-19 07:51:42 +000056
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +000057static cl::opt<unsigned>
58CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30),
59 cl::desc("The max number of iteration for converge"));
60
James Molloy70a3d6d2016-11-01 13:37:41 +000061static cl::opt<bool> SynthesizeThumb1TBB(
62 "arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true),
63 cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an "
64 "equivalent to the TBB/TBH instructions"));
65
Evan Cheng10043e22007-01-19 07:51:42 +000066namespace {
Dale Johannesene18b13b2007-02-23 05:02:36 +000067 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Cheng10043e22007-01-19 07:51:42 +000068 /// requires constant pool entries to be scattered among the instructions
69 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesene18b13b2007-02-23 05:02:36 +000070 /// constant pool; instead, it places constants wherever it feels like with
Evan Cheng10043e22007-01-19 07:51:42 +000071 /// special instructions.
72 ///
73 /// The terminology used in this pass includes:
74 /// Islands - Clumps of constants placed in the function.
75 /// Water - Potential places where an island could be formed.
76 /// CPE - A constant pool entry that has been placed somewhere, which
77 /// tracks a list of users.
Nick Lewycky02d5f772009-10-25 06:33:48 +000078 class ARMConstantIslands : public MachineFunctionPass {
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +000079
80 std::vector<BasicBlockInfo> BBInfo;
Dale Johannesen01ee5752007-02-25 00:47:03 +000081
Evan Cheng10043e22007-01-19 07:51:42 +000082 /// WaterList - A sorted list of basic blocks where islands could be placed
83 /// (i.e. blocks that don't fall through to the following block, due
84 /// to a return, unreachable, or unconditional branch).
Evan Cheng540f5e02007-02-09 23:59:14 +000085 std::vector<MachineBasicBlock*> WaterList;
Evan Cheng8b7700f2007-02-09 20:54:44 +000086
Bob Wilson2f9be502009-10-15 20:49:47 +000087 /// NewWaterList - The subset of WaterList that was created since the
88 /// previous iteration by inserting unconditional branches.
89 SmallSet<MachineBasicBlock*, 4> NewWaterList;
90
Bob Wilsonc7a3cf42009-10-12 18:52:13 +000091 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
92
Evan Cheng10043e22007-01-19 07:51:42 +000093 /// CPUser - One user of a constant pool, keeping the machine instruction
94 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson68ead6c2009-10-15 05:52:29 +000095 /// allowed from the instruction to the CP. The HighWaterMark records the
96 /// highest basic block where a new CPEntry can be placed. To ensure this
97 /// pass terminates, the CP entries are initially placed at the end of the
98 /// function and then move monotonically to lower addresses. The
99 /// exception to this rule is when the current CP entry for a particular
100 /// CPUser is out of range, but there is another CP entry for the same
101 /// constant value in range. We want to use the existing in-range CP
102 /// entry, but if it later moves out of range, the search for new water
103 /// should resume where it left off. The HighWaterMark is used to record
104 /// that point.
Evan Cheng10043e22007-01-19 07:51:42 +0000105 struct CPUser {
106 MachineInstr *MI;
107 MachineInstr *CPEMI;
Bob Wilson68ead6c2009-10-15 05:52:29 +0000108 MachineBasicBlock *HighWaterMark;
Evan Cheng10043e22007-01-19 07:51:42 +0000109 unsigned MaxDisp;
Evan Cheng87aaa192009-07-21 23:56:01 +0000110 bool NegOk;
Evan Chengd2919a12009-07-23 18:27:47 +0000111 bool IsSoImm;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000112 bool KnownAlignment;
Evan Chengd2919a12009-07-23 18:27:47 +0000113 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
114 bool neg, bool soimm)
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000115 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
116 KnownAlignment(false) {
Bob Wilson68ead6c2009-10-15 05:52:29 +0000117 HighWaterMark = CPEMI->getParent();
118 }
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000119 /// getMaxDisp - Returns the maximum displacement supported by MI.
120 /// Correct for unknown alignment.
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000121 /// Conservatively subtract 2 bytes to handle weird alignment effects.
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000122 unsigned getMaxDisp() const {
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000123 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000124 }
Evan Cheng10043e22007-01-19 07:51:42 +0000125 };
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000126
Evan Cheng10043e22007-01-19 07:51:42 +0000127 /// CPUsers - Keep track of all of the machine instructions that use various
128 /// constant pools and their max displacement.
Evan Cheng540f5e02007-02-09 23:59:14 +0000129 std::vector<CPUser> CPUsers;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000130
Evan Cheng8b7700f2007-02-09 20:54:44 +0000131 /// CPEntry - One per constant pool entry, keeping the machine instruction
132 /// pointer, the constpool index, and the number of CPUser's which
133 /// reference this entry.
134 struct CPEntry {
135 MachineInstr *CPEMI;
136 unsigned CPI;
137 unsigned RefCount;
138 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
139 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
140 };
141
142 /// CPEntries - Keep track of all of the constant pool entry machine
Tim Northovera603c402015-05-31 19:22:07 +0000143 /// instructions. For each original constpool index (i.e. those that existed
144 /// upon entry to this pass), it keeps a vector of entries. Original
145 /// elements are cloned as we go along; the clones are put in the vector of
146 /// the original element, but have distinct CPIs.
147 ///
148 /// The first half of CPEntries contains generic constants, the second half
149 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
150 /// which vector it will be in here.
Evan Cheng8b7700f2007-02-09 20:54:44 +0000151 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000152
Tim Northovera603c402015-05-31 19:22:07 +0000153 /// Maps a JT index to the offset in CPEntries containing copies of that
154 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
155 DenseMap<int, int> JumpTableEntryIndices;
156
157 /// Maps a JT index to the LEA that actually uses the index to calculate its
158 /// base address.
159 DenseMap<int, int> JumpTableUserIndices;
160
Evan Cheng22c7cf52007-01-25 03:12:46 +0000161 /// ImmBranch - One per immediate branch, keeping the machine instruction
162 /// pointer, conditional or unconditional, the max displacement,
163 /// and (if isCond is true) the corresponding unconditional branch
164 /// opcode.
165 struct ImmBranch {
166 MachineInstr *MI;
Evan Cheng010ae382007-01-25 23:18:59 +0000167 unsigned MaxDisp : 31;
168 bool isCond : 1;
Matthias Braunfa3872e2015-05-18 20:27:55 +0000169 unsigned UncondBr;
170 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
Evan Cheng010ae382007-01-25 23:18:59 +0000171 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Cheng22c7cf52007-01-25 03:12:46 +0000172 };
173
Evan Chengc95f95b2007-05-16 05:14:06 +0000174 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Cheng22c7cf52007-01-25 03:12:46 +0000175 ///
Evan Cheng540f5e02007-02-09 23:59:14 +0000176 std::vector<ImmBranch> ImmBranches;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000177
Evan Cheng7fa69642007-01-30 01:18:38 +0000178 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
179 ///
Evan Cheng8b7700f2007-02-09 20:54:44 +0000180 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Cheng7fa69642007-01-30 01:18:38 +0000181
Evan Chengc6d70ae2009-07-29 02:18:14 +0000182 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
183 SmallVector<MachineInstr*, 4> T2JumpTables;
184
Evan Cheng7fa69642007-01-30 01:18:38 +0000185 /// HasFarJump - True if any far jump instruction has been emitted during
186 /// the branch fix up pass.
187 bool HasFarJump;
188
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000189 MachineFunction *MF;
190 MachineConstantPool *MCP;
Craig Topper07720d82012-03-25 23:49:58 +0000191 const ARMBaseInstrInfo *TII;
Evan Chenge64f48b2009-08-01 06:13:52 +0000192 const ARMSubtarget *STI;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000193 ARMFunctionInfo *AFI;
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000194 bool isThumb;
Evan Chengd2919a12009-07-23 18:27:47 +0000195 bool isThumb1;
David Goodwin27303cd2009-06-30 18:04:13 +0000196 bool isThumb2;
James Molloy70a3d6d2016-11-01 13:37:41 +0000197 bool isPositionIndependentOrROPI;
Evan Cheng10043e22007-01-19 07:51:42 +0000198 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000199 static char ID;
Owen Andersona7aed182010-08-06 18:33:48 +0000200 ARMConstantIslands() : MachineFunctionPass(ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +0000201
Craig Topper6bc27bf2014-03-10 02:09:33 +0000202 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng10043e22007-01-19 07:51:42 +0000203
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000204 MachineFunctionProperties getRequiredProperties() const override {
205 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000206 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000207 }
208
Mehdi Amini117296c2016-10-01 02:56:57 +0000209 StringRef getPassName() const override {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000210 return "ARM constant island placement and branch shortening pass";
Evan Cheng10043e22007-01-19 07:51:42 +0000211 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000212
Evan Cheng10043e22007-01-19 07:51:42 +0000213 private:
Tim Northovera603c402015-05-31 19:22:07 +0000214 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
215 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000216 bool BBHasFallthrough(MachineBasicBlock *MBB);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000217 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000218 unsigned getCPELogAlign(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000219 void scanFunctionJumpTables();
220 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
221 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
222 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
223 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
224 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
Tim Northovera603c402015-05-31 19:22:07 +0000225 unsigned getCombinedIndex(const MachineInstr *CPEMI);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000226 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
227 bool findAvailableWater(CPUser&U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000228 water_iterator &WaterIter, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000229 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson3250e772009-10-12 21:39:43 +0000230 MachineBasicBlock *&NewMBB);
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000231 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000232 void removeDeadCPEMI(MachineInstr *CPEMI);
233 bool removeUnusedCPEntries();
234 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
235 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
236 bool DoDump = false);
237 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000238 CPUser &U, unsigned &Growth);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000239 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
240 bool fixupImmediateBr(ImmBranch &Br);
241 bool fixupConditionalBr(ImmBranch &Br);
242 bool fixupUnconditionalBr(ImmBranch &Br);
243 bool undoLRSpillRestore();
Jim Grosbach190e7b62012-03-23 23:07:03 +0000244 bool optimizeThumb2Instructions();
245 bool optimizeThumb2Branches();
246 bool reorderThumb2JumpTables();
Tim Northovera603c402015-05-31 19:22:07 +0000247 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
248 unsigned &DeadSize, bool &CanDeleteLEA,
249 bool &BaseRegKill);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000250 bool optimizeThumb2JumpTables();
251 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
Jim Grosbach8d92ec42009-11-11 02:47:19 +0000252 MachineBasicBlock *JTBB);
Evan Cheng10043e22007-01-19 07:51:42 +0000253
Jim Grosbach190e7b62012-03-23 23:07:03 +0000254 unsigned getOffsetOf(MachineInstr *MI) const;
255 unsigned getUserOffset(CPUser&) const;
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000256 void dumpBBs();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000257 void verify();
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000258
Jim Grosbach190e7b62012-03-23 23:07:03 +0000259 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000260 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Jim Grosbach190e7b62012-03-23 23:07:03 +0000261 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000262 const CPUser &U) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000263 return isOffsetInRange(UserOffset, TrialOffset,
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000264 U.getMaxDisp(), U.NegOk, U.IsSoImm);
Jakob Stoklund Olesenf8572362011-12-09 19:44:39 +0000265 }
Evan Cheng10043e22007-01-19 07:51:42 +0000266 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000267 char ARMConstantIslands::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000268}
Evan Cheng10043e22007-01-19 07:51:42 +0000269
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000270/// verify - check BBOffsets, BBSizes, alignment of islands
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000271void ARMConstantIslands::verify() {
Evan Chengd2919a12009-07-23 18:27:47 +0000272#ifndef NDEBUG
Craig Toppere30b8ca2016-01-03 19:43:40 +0000273 assert(std::is_sorted(MF->begin(), MF->end(),
274 [this](const MachineBasicBlock &LHS,
275 const MachineBasicBlock &RHS) {
276 return BBInfo[LHS.getNumber()].postOffset() <
277 BBInfo[RHS.getNumber()].postOffset();
278 }));
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000279 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000280 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
281 CPUser &U = CPUsers[i];
Jim Grosbach190e7b62012-03-23 23:07:03 +0000282 unsigned UserOffset = getUserOffset(U);
Jakob Stoklund Olesend9155032012-03-31 00:06:44 +0000283 // Verify offset using the real max displacement without the safety
284 // adjustment.
285 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +0000286 /* DoDump = */ true)) {
287 DEBUG(dbgs() << "OK\n");
288 continue;
289 }
290 DEBUG(dbgs() << "Out of range.\n");
291 dumpBBs();
292 DEBUG(MF->dump());
293 llvm_unreachable("Constant pool entry out of range!");
Jim Grosbachb73918c2009-11-19 23:10:28 +0000294 }
Jim Grosbach6c3b7112009-11-20 19:37:38 +0000295#endif
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000296}
297
298/// print block size and offset information - debugging
299void ARMConstantIslands::dumpBBs() {
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000300 DEBUG({
301 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
302 const BasicBlockInfo &BBI = BBInfo[J];
303 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
304 << " kb=" << unsigned(BBI.KnownBits)
305 << " ua=" << unsigned(BBI.Unalign)
306 << " pa=" << unsigned(BBI.PostAlign)
307 << format(" size=%#x\n", BBInfo[J].Size);
308 }
309 });
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000310}
311
Evan Cheng22c7cf52007-01-25 03:12:46 +0000312/// createARMConstantIslandPass - returns an instance of the constpool
313/// island pass.
Evan Cheng10043e22007-01-19 07:51:42 +0000314FunctionPass *llvm::createARMConstantIslandPass() {
315 return new ARMConstantIslands();
316}
317
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000318bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
319 MF = &mf;
320 MCP = mf.getConstantPool();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000321
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000322 DEBUG(dbgs() << "***** ARMConstantIslands: "
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000323 << MCP->getConstants().size() << " CP entries, aligned to "
324 << MCP->getConstantPoolAlignment() << " bytes *****\n");
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +0000325
Eric Christopher1b21f002015-01-29 00:19:33 +0000326 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
327 TII = STI->getInstrInfo();
James Molloy70a3d6d2016-11-01 13:37:41 +0000328 isPositionIndependentOrROPI =
329 STI->getTargetLowering()->isPositionIndependent() || STI->isROPI();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000330 AFI = MF->getInfo<ARMFunctionInfo>();
Evan Chenge64f48b2009-08-01 06:13:52 +0000331
Dale Johannesen962fa8e2007-02-28 23:20:38 +0000332 isThumb = AFI->isThumbFunction();
Evan Chengd2919a12009-07-23 18:27:47 +0000333 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin27303cd2009-06-30 18:04:13 +0000334 isThumb2 = AFI->isThumb2Function();
Evan Cheng7fa69642007-01-30 01:18:38 +0000335
336 HasFarJump = false;
James Molloy70a3d6d2016-11-01 13:37:41 +0000337 bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB);
Evan Cheng7fa69642007-01-30 01:18:38 +0000338
Jakob Stoklund Olesend8af9a52012-03-29 23:14:26 +0000339 // This pass invalidates liveness information when it splits basic blocks.
340 MF->getRegInfo().invalidateLiveness();
341
Evan Cheng10043e22007-01-19 07:51:42 +0000342 // Renumber all of the machine basic blocks in the function, guaranteeing that
343 // the numbers agree with the position of the block in the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000344 MF->RenumberBlocks();
Evan Cheng10043e22007-01-19 07:51:42 +0000345
Jim Grosbach5d577142009-11-12 17:25:07 +0000346 // Try to reorder and otherwise adjust the block layout to make good use
347 // of the TB[BH] instructions.
348 bool MadeChange = false;
James Molloy70a3d6d2016-11-01 13:37:41 +0000349 if (GenerateTBB && AdjustJumpTableBlocks) {
Jim Grosbach190e7b62012-03-23 23:07:03 +0000350 scanFunctionJumpTables();
351 MadeChange |= reorderThumb2JumpTables();
Jim Grosbach5d577142009-11-12 17:25:07 +0000352 // Data is out of date, so clear it. It'll be re-computed later.
Jim Grosbach5d577142009-11-12 17:25:07 +0000353 T2JumpTables.clear();
354 // Blocks may have shifted around. Keep the numbering up to date.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000355 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +0000356 }
357
Evan Cheng10043e22007-01-19 07:51:42 +0000358 // Perform the initial placement of the constant pool entries. To start with,
359 // we put them all at the end of the function.
Evan Cheng540f5e02007-02-09 23:59:14 +0000360 std::vector<MachineInstr*> CPEMIs;
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000361 if (!MCP->isEmpty())
Tim Northovera603c402015-05-31 19:22:07 +0000362 doInitialConstPlacement(CPEMIs);
363
364 if (MF->getJumpTableInfo())
365 doInitialJumpTablePlacement(CPEMIs);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000366
Evan Cheng10043e22007-01-19 07:51:42 +0000367 /// The next UID to take is the first unused one.
Evan Chengdfce83c2011-01-17 08:03:18 +0000368 AFI->initPICLabelUId(CPEMIs.size());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000369
Evan Cheng10043e22007-01-19 07:51:42 +0000370 // Do the initial scan of the function, building up information about the
371 // sizes of each block, the location of all the water, and finding all of the
372 // constant pool users.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000373 initializeFunctionInfo(CPEMIs);
Evan Cheng10043e22007-01-19 07:51:42 +0000374 CPEMIs.clear();
Dale Johannesenc17dd572010-07-23 22:50:23 +0000375 DEBUG(dumpBBs());
376
Peter Collingbourned27d3a12015-05-01 18:05:59 +0000377 // Functions with jump tables need an alignment of 4 because they use the ADR
378 // instruction, which aligns the PC to 4 bytes before adding an offset.
379 if (!T2JumpTables.empty())
380 MF->ensureAlignment(2);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000381
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000382 /// Remove dead constant pool entries.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000383 MadeChange |= removeUnusedCPEntries();
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000384
Evan Cheng7fa69642007-01-30 01:18:38 +0000385 // Iteratively place constant pool entries and fix up branches until there
386 // is no change.
Evan Cheng82ff0222009-08-07 07:35:21 +0000387 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Cheng7fa69642007-01-30 01:18:38 +0000388 while (true) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000389 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000390 bool CPChange = false;
Evan Cheng10043e22007-01-19 07:51:42 +0000391 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000392 // For most inputs, it converges in no more than 5 iterations.
David Majnemer68318e02016-04-22 06:37:48 +0000393 // If it doesn't end in 10, the input may have huge BB or many CPEs.
394 // In this case, we will try different heuristics.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +0000395 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
396 if (CPChange && ++NoCPIters > CPMaxIteration)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000397 report_fatal_error("Constant Island pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000398 DEBUG(dumpBBs());
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000399
Bob Wilson2f9be502009-10-15 20:49:47 +0000400 // Clear NewWaterList now. If we split a block for branches, it should
401 // appear as "new water" for the next iteration of constant pool placement.
402 NewWaterList.clear();
Evan Cheng82ff0222009-08-07 07:35:21 +0000403
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000404 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
Evan Cheng82ff0222009-08-07 07:35:21 +0000405 bool BRChange = false;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000406 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Jim Grosbach190e7b62012-03-23 23:07:03 +0000407 BRChange |= fixupImmediateBr(ImmBranches[i]);
Evan Cheng82ff0222009-08-07 07:35:21 +0000408 if (BRChange && ++NoBRIters > 30)
Jakob Stoklund Olesen1a80e3a2012-01-09 22:16:24 +0000409 report_fatal_error("Branch Fix Up pass failed to converge!");
Evan Cheng94579db2007-07-10 22:00:16 +0000410 DEBUG(dumpBBs());
Evan Cheng82ff0222009-08-07 07:35:21 +0000411
412 if (!CPChange && !BRChange)
Evan Cheng7fa69642007-01-30 01:18:38 +0000413 break;
414 MadeChange = true;
415 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +0000416
Bradley Smitha1189102016-01-15 10:26:17 +0000417 // Shrink 32-bit Thumb2 load and store instructions.
Evan Chengce8fb682010-08-09 18:35:19 +0000418 if (isThumb2 && !STI->prefers32BitThumb())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000419 MadeChange |= optimizeThumb2Instructions();
Evan Chenge64f48b2009-08-01 06:13:52 +0000420
Bradley Smitha1189102016-01-15 10:26:17 +0000421 // Shrink 32-bit branch instructions.
422 if (isThumb && STI->hasV8MBaselineOps())
423 MadeChange |= optimizeThumb2Branches();
424
425 // Optimize jump tables using TBB / TBH.
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000426 if (GenerateTBB && !STI->genExecuteOnly())
Bradley Smitha1189102016-01-15 10:26:17 +0000427 MadeChange |= optimizeThumb2JumpTables();
428
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000429 // After a while, this might be made debug-only, but it is not expensive.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000430 verify();
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000431
Jim Grosbache4ba2aa2010-07-07 21:06:51 +0000432 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
433 // undo the spill / restore of LR if possible.
Evan Chengc6d70ae2009-07-29 02:18:14 +0000434 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Jim Grosbach190e7b62012-03-23 23:07:03 +0000435 MadeChange |= undoLRSpillRestore();
Evan Cheng7fa69642007-01-30 01:18:38 +0000436
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000437 // Save the mapping between original and cloned constpool entries.
438 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
439 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
440 const CPEntry & CPE = CPEntries[i][j];
Tim Northovera603c402015-05-31 19:22:07 +0000441 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
442 AFI->recordCPEClone(i, CPE.CPI);
Anton Korobeynikov221f4fa2011-01-30 22:07:39 +0000443 }
444 }
445
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +0000446 DEBUG(dbgs() << '\n'; dumpBBs());
Evan Cheng3fabe072010-07-22 02:09:47 +0000447
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000448 BBInfo.clear();
Evan Cheng10043e22007-01-19 07:51:42 +0000449 WaterList.clear();
450 CPUsers.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000451 CPEntries.clear();
Tim Northovera603c402015-05-31 19:22:07 +0000452 JumpTableEntryIndices.clear();
453 JumpTableUserIndices.clear();
Evan Cheng22c7cf52007-01-25 03:12:46 +0000454 ImmBranches.clear();
Evan Cheng8b7700f2007-02-09 20:54:44 +0000455 PushPopMIs.clear();
Evan Chengc6d70ae2009-07-29 02:18:14 +0000456 T2JumpTables.clear();
Evan Cheng7fa69642007-01-30 01:18:38 +0000457
458 return MadeChange;
Evan Cheng10043e22007-01-19 07:51:42 +0000459}
460
Tim Northovera603c402015-05-31 19:22:07 +0000461/// \brief Perform the initial placement of the regular constant pool entries.
462/// To start with, we put them all at the end of the function.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000463void
Tim Northovera603c402015-05-31 19:22:07 +0000464ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000465 // Create the basic block to hold the CPE's.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000466 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
467 MF->push_back(BB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000468
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000469 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000470 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000471
472 // Mark the basic block as required by the const-pool.
Peter Collingbourne12139182015-04-23 20:31:22 +0000473 BB->setAlignment(MaxAlign);
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000474
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000475 // The function needs to be as aligned as the basic blocks. The linker may
476 // move functions around based on their alignment.
Chad Rosier73b02822012-07-06 23:13:38 +0000477 MF->ensureAlignment(BB->getAlignment());
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000478
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000479 // Order the entries in BB by descending alignment. That ensures correct
480 // alignment of all entries as long as BB is sufficiently aligned. Keep
481 // track of the insertion point for each alignment. We are going to bucket
482 // sort the entries as they are created.
483 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +0000484
Evan Cheng10043e22007-01-19 07:51:42 +0000485 // Add all of the constants from the constant pool to the end block, use an
486 // identity mapping of CPI's to CPE's.
Jakob Stoklund Olesene5585e82011-12-14 18:49:13 +0000487 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000488
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000489 const DataLayout &TD = MF->getDataLayout();
Evan Cheng10043e22007-01-19 07:51:42 +0000490 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000491 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000492 assert(Size >= 4 && "Too small constant pool entry");
493 unsigned Align = CPs[i].getAlignment();
494 assert(isPowerOf2_32(Align) && "Invalid alignment");
495 // Verify that all constant pool entries are a multiple of their alignment.
496 // If not, we would have to pad them out so that instructions stay aligned.
497 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
498
499 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
500 unsigned LogAlign = Log2_32(Align);
501 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
Evan Cheng10043e22007-01-19 07:51:42 +0000502 MachineInstr *CPEMI =
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000503 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Chris Lattner6f306d72010-04-02 20:16:16 +0000504 .addImm(i).addConstantPoolIndex(i).addImm(Size);
Evan Cheng10043e22007-01-19 07:51:42 +0000505 CPEMIs.push_back(CPEMI);
Evan Cheng8b7700f2007-02-09 20:54:44 +0000506
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000507 // Ensure that future entries with higher alignment get inserted before
508 // CPEMI. This is bucket sort with iterators.
Jakob Stoklund Olesen97901872011-12-16 23:00:05 +0000509 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000510 if (InsPoint[a] == InsAt)
511 InsPoint[a] = CPEMI;
512
Evan Cheng8b7700f2007-02-09 20:54:44 +0000513 // Add a new CPEntry, but no corresponding CPUser yet.
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000514 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000515 ++NumCPEs;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000516 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
517 << Size << ", align = " << Align <<'\n');
Evan Cheng10043e22007-01-19 07:51:42 +0000518 }
Jakob Stoklund Olesenb5f52aa2011-12-12 16:49:37 +0000519 DEBUG(BB->dump());
Evan Cheng10043e22007-01-19 07:51:42 +0000520}
521
Tim Northovera603c402015-05-31 19:22:07 +0000522/// \brief Do initial placement of the jump tables. Because Thumb2's TBB and TBH
523/// instructions can be made more efficient if the jump table immediately
524/// follows the instruction, it's best to place them immediately next to their
525/// jumps to begin with. In almost all cases they'll never be moved from that
526/// position.
527void ARMConstantIslands::doInitialJumpTablePlacement(
528 std::vector<MachineInstr *> &CPEMIs) {
529 unsigned i = CPEntries.size();
530 auto MJTI = MF->getJumpTableInfo();
531 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
532
533 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
534 for (MachineBasicBlock &MBB : *MF) {
535 auto MI = MBB.getLastNonDebugInstr();
Petr Pavlua7703792015-11-16 16:41:13 +0000536 if (MI == MBB.end())
537 continue;
Tim Northovera603c402015-05-31 19:22:07 +0000538
539 unsigned JTOpcode;
540 switch (MI->getOpcode()) {
541 default:
542 continue;
543 case ARM::BR_JTadd:
544 case ARM::BR_JTr:
545 case ARM::tBR_JTr:
546 case ARM::BR_JTm:
547 JTOpcode = ARM::JUMPTABLE_ADDRS;
548 break;
549 case ARM::t2BR_JT:
550 JTOpcode = ARM::JUMPTABLE_INSTS;
551 break;
James Molloy70a3d6d2016-11-01 13:37:41 +0000552 case ARM::tTBB_JT:
Tim Northovera603c402015-05-31 19:22:07 +0000553 case ARM::t2TBB_JT:
554 JTOpcode = ARM::JUMPTABLE_TBB;
555 break;
James Molloy70a3d6d2016-11-01 13:37:41 +0000556 case ARM::tTBH_JT:
Tim Northovera603c402015-05-31 19:22:07 +0000557 case ARM::t2TBH_JT:
558 JTOpcode = ARM::JUMPTABLE_TBH;
559 break;
560 }
561
562 unsigned NumOps = MI->getDesc().getNumOperands();
563 MachineOperand JTOp =
564 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
565 unsigned JTI = JTOp.getIndex();
566 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
567 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
568 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
569 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
570 DebugLoc(), TII->get(JTOpcode))
571 .addImm(i++)
572 .addJumpTableIndex(JTI)
573 .addImm(Size);
574 CPEMIs.push_back(CPEMI);
575 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
576 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
577 if (!LastCorrectlyNumberedBB)
578 LastCorrectlyNumberedBB = &MBB;
579 }
580
581 // If we did anything then we need to renumber the subsequent blocks.
582 if (LastCorrectlyNumberedBB)
583 MF->RenumberBlocks(LastCorrectlyNumberedBB);
584}
585
Dale Johannesene18b13b2007-02-23 05:02:36 +0000586/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Cheng10043e22007-01-19 07:51:42 +0000587/// into the block immediately after it.
Tim Northoverab85dcc2014-11-13 17:58:51 +0000588bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +0000589 // Get the next machine basic block in the function.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000590 MachineFunction::iterator MBBI = MBB->getIterator();
Jim Grosbach84511e12010-06-02 21:53:11 +0000591 // Can't fall off end of function.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000592 if (std::next(MBBI) == MBB->getParent()->end())
Evan Cheng10043e22007-01-19 07:51:42 +0000593 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000594
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000595 MachineBasicBlock *NextBB = &*std::next(MBBI);
David Majnemer42531262016-08-12 03:55:06 +0000596 if (!MBB->isSuccessor(NextBB))
Tim Northoverab85dcc2014-11-13 17:58:51 +0000597 return false;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000598
Tim Northoverab85dcc2014-11-13 17:58:51 +0000599 // Try to analyze the end of the block. A potential fallthrough may already
600 // have an unconditional branch for whatever reason.
601 MachineBasicBlock *TBB, *FBB;
602 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000603 bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
Tim Northoverab85dcc2014-11-13 17:58:51 +0000604 return TooDifficult || FBB == nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000605}
606
Evan Cheng8b7700f2007-02-09 20:54:44 +0000607/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
608/// look up the corresponding CPEntry.
609ARMConstantIslands::CPEntry
610*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
611 const MachineInstr *CPEMI) {
612 std::vector<CPEntry> &CPEs = CPEntries[CPI];
613 // Number of entries per constpool index should be small, just do a
614 // linear search.
615 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
616 if (CPEs[i].CPEMI == CPEMI)
617 return &CPEs[i];
618 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000619 return nullptr;
Evan Cheng8b7700f2007-02-09 20:54:44 +0000620}
621
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000622/// getCPELogAlign - Returns the required alignment of the constant pool entry
Jakob Stoklund Olesen0863de42011-12-12 19:25:51 +0000623/// represented by CPEMI. Alignment is measured in log2(bytes) units.
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000624unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
Tim Northovera603c402015-05-31 19:22:07 +0000625 switch (CPEMI->getOpcode()) {
626 case ARM::CONSTPOOL_ENTRY:
627 break;
628 case ARM::JUMPTABLE_TBB:
James Molloy70a3d6d2016-11-01 13:37:41 +0000629 return isThumb1 ? 2 : 0;
Tim Northovera603c402015-05-31 19:22:07 +0000630 case ARM::JUMPTABLE_TBH:
James Molloy70a3d6d2016-11-01 13:37:41 +0000631 return isThumb1 ? 2 : 1;
Tim Northovera603c402015-05-31 19:22:07 +0000632 case ARM::JUMPTABLE_INSTS:
633 return 1;
634 case ARM::JUMPTABLE_ADDRS:
635 return 2;
636 default:
637 llvm_unreachable("unknown constpool entry kind");
638 }
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000639
Tim Northovera603c402015-05-31 19:22:07 +0000640 unsigned CPI = getCombinedIndex(CPEMI);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +0000641 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
642 unsigned Align = MCP->getConstants()[CPI].getAlignment();
643 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
644 return Log2_32(Align);
645}
646
Jim Grosbach190e7b62012-03-23 23:07:03 +0000647/// scanFunctionJumpTables - Do a scan of the function, building up
Jim Grosbach5d577142009-11-12 17:25:07 +0000648/// information about the sizes of each block and the locations of all
649/// the jump tables.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000650void ARMConstantIslands::scanFunctionJumpTables() {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000651 for (MachineBasicBlock &MBB : *MF) {
652 for (MachineInstr &I : MBB)
James Molloy70a3d6d2016-11-01 13:37:41 +0000653 if (I.isBranch() &&
654 (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000655 T2JumpTables.push_back(&I);
Jim Grosbach5d577142009-11-12 17:25:07 +0000656 }
657}
658
Jim Grosbach190e7b62012-03-23 23:07:03 +0000659/// initializeFunctionInfo - Do the initial scan of the function, building up
Evan Cheng10043e22007-01-19 07:51:42 +0000660/// information about the sizes of each block, the location of all the water,
661/// and finding all of the constant pool users.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000662void ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +0000663initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000664
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000665 BBInfo = computeAllBlockSizes(MF);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000666
667 // The known bits of the entry block offset are determined by the function
668 // alignment.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000669 BBInfo.front().KnownBits = MF->getAlignment();
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000670
671 // Compute block offsets and known bits.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000672 adjustBBOffsetsAfter(&MF->front());
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +0000673
Bill Wendling18581a42010-12-21 01:54:40 +0000674 // Now go back through the instructions and build up our data structures.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000675 for (MachineBasicBlock &MBB : *MF) {
Evan Cheng10043e22007-01-19 07:51:42 +0000676 // If this block doesn't fall through into the next MBB, then this is
677 // 'water' that a constant pool island could be placed.
678 if (!BBHasFallthrough(&MBB))
679 WaterList.push_back(&MBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000680
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000681 for (MachineInstr &I : MBB) {
682 if (I.isDebugValue())
Jim Grosbach97c8a6a2010-06-21 17:49:23 +0000683 continue;
Jakob Stoklund Olesen97c85712011-12-07 04:17:35 +0000684
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000685 unsigned Opc = I.getOpcode();
686 if (I.isBranch()) {
Evan Cheng22c7cf52007-01-25 03:12:46 +0000687 bool isCond = false;
688 unsigned Bits = 0;
689 unsigned Scale = 1;
690 int UOpc = Opc;
691 switch (Opc) {
Evan Chengc6d70ae2009-07-29 02:18:14 +0000692 default:
693 continue; // Ignore other JT branches
Evan Chengc6d70ae2009-07-29 02:18:14 +0000694 case ARM::t2BR_JT:
James Molloy70a3d6d2016-11-01 13:37:41 +0000695 case ARM::tBR_JTr:
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000696 T2JumpTables.push_back(&I);
Evan Chengc6d70ae2009-07-29 02:18:14 +0000697 continue; // Does not get an entry in ImmBranches
Evan Cheng22c7cf52007-01-25 03:12:46 +0000698 case ARM::Bcc:
699 isCond = true;
700 UOpc = ARM::B;
Justin Bognerb03fd122016-08-17 05:10:15 +0000701 LLVM_FALLTHROUGH;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000702 case ARM::B:
703 Bits = 24;
704 Scale = 4;
705 break;
706 case ARM::tBcc:
707 isCond = true;
708 UOpc = ARM::tB;
709 Bits = 8;
710 Scale = 2;
711 break;
712 case ARM::tB:
713 Bits = 11;
714 Scale = 2;
715 break;
David Goodwin27303cd2009-06-30 18:04:13 +0000716 case ARM::t2Bcc:
717 isCond = true;
718 UOpc = ARM::t2B;
719 Bits = 20;
720 Scale = 2;
721 break;
722 case ARM::t2B:
723 Bits = 24;
724 Scale = 2;
725 break;
Evan Cheng22c7cf52007-01-25 03:12:46 +0000726 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000727
728 // Record this immediate branch.
Evan Cheng36d559d2007-02-03 02:08:34 +0000729 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000730 ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
Evan Cheng22c7cf52007-01-25 03:12:46 +0000731 }
732
Evan Cheng7fa69642007-01-30 01:18:38 +0000733 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000734 PushPopMIs.push_back(&I);
Evan Cheng7fa69642007-01-30 01:18:38 +0000735
Tim Northovera603c402015-05-31 19:22:07 +0000736 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
737 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
738 Opc == ARM::JUMPTABLE_TBH)
Evan Chengd2919a12009-07-23 18:27:47 +0000739 continue;
740
Evan Cheng10043e22007-01-19 07:51:42 +0000741 // Scan the instructions for constant pool operands.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000742 for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
743 if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
Evan Cheng10043e22007-01-19 07:51:42 +0000744 // We found one. The addressing mode tells us the max displacement
745 // from the PC that this instruction permits.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000746
Evan Cheng10043e22007-01-19 07:51:42 +0000747 // Basic size info comes from the TSFlags field.
Evan Chengf9a4c692007-02-01 10:16:15 +0000748 unsigned Bits = 0;
749 unsigned Scale = 1;
Evan Cheng87aaa192009-07-21 23:56:01 +0000750 bool NegOk = false;
Evan Chengd2919a12009-07-23 18:27:47 +0000751 bool IsSoImm = false;
752
753 switch (Opc) {
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000754 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000755 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd2919a12009-07-23 18:27:47 +0000756
757 // Taking the address of a CP entry.
758 case ARM::LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000759 case ARM::LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000760 // This takes a SoImm, which is 8 bit immediate rotated. We'll
761 // pretend the maximum offset is 255 * 4. Since each instruction
Jim Grosbach36a5bf82009-11-19 18:23:19 +0000762 // 4 byte wide, this is always correct. We'll check for other
Evan Chengd2919a12009-07-23 18:27:47 +0000763 // displacements that fits in a SoImm as well.
Evan Chengf9a4c692007-02-01 10:16:15 +0000764 Bits = 8;
Evan Chengd2919a12009-07-23 18:27:47 +0000765 Scale = 4;
766 NegOk = true;
767 IsSoImm = true;
768 break;
Owen Anderson9a4d4282010-12-13 22:51:08 +0000769 case ARM::t2LEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000770 case ARM::t2LEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000771 Bits = 12;
Evan Cheng87aaa192009-07-21 23:56:01 +0000772 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000773 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000774 case ARM::tLEApcrel:
Tim Northovera603c402015-05-31 19:22:07 +0000775 case ARM::tLEApcrelJT:
Evan Chengd2919a12009-07-23 18:27:47 +0000776 Bits = 8;
777 Scale = 4;
778 break;
779
David Majnemer452f1f92013-06-04 17:46:15 +0000780 case ARM::LDRBi12:
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000781 case ARM::LDRi12:
Evan Chengd2919a12009-07-23 18:27:47 +0000782 case ARM::LDRcp:
Owen Anderson4ebf4712011-02-08 22:39:40 +0000783 case ARM::t2LDRpci:
James Molloy9abb2fa2016-09-26 07:26:24 +0000784 case ARM::t2LDRHpci:
Evan Chengfd522992007-02-01 20:44:52 +0000785 Bits = 12; // +-offset_12
Evan Cheng87aaa192009-07-21 23:56:01 +0000786 NegOk = true;
Evan Cheng10043e22007-01-19 07:51:42 +0000787 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000788
789 case ARM::tLDRpci:
Evan Chengf9a4c692007-02-01 10:16:15 +0000790 Bits = 8;
791 Scale = 4; // +(offset_8*4)
Evan Cheng1526ba52007-01-24 08:53:17 +0000792 break;
Evan Chengd2919a12009-07-23 18:27:47 +0000793
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000794 case ARM::VLDRD:
795 case ARM::VLDRS:
Evan Chengd2919a12009-07-23 18:27:47 +0000796 Bits = 8;
797 Scale = 4; // +-(offset_8*4)
798 NegOk = true;
Evan Chengb23b50d2009-06-29 07:51:04 +0000799 break;
James Molloy9abb2fa2016-09-26 07:26:24 +0000800
801 case ARM::tLDRHi:
802 Bits = 5;
803 Scale = 2; // +(offset_5*2)
804 break;
Evan Cheng10043e22007-01-19 07:51:42 +0000805 }
Evan Chengf9a4c692007-02-01 10:16:15 +0000806
Evan Cheng10043e22007-01-19 07:51:42 +0000807 // Remember that this is a user of a CP entry.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000808 unsigned CPI = I.getOperand(op).getIndex();
809 if (I.getOperand(op).isJTI()) {
Tim Northovera603c402015-05-31 19:22:07 +0000810 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
811 CPI = JumpTableEntryIndices[CPI];
812 }
813
Evan Cheng8b7700f2007-02-09 20:54:44 +0000814 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chenge41903b2009-08-14 18:31:44 +0000815 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000816 CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Cheng8b7700f2007-02-09 20:54:44 +0000817
818 // Increment corresponding CPEntry reference count.
819 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
820 assert(CPE && "Cannot find a corresponding CPEntry!");
821 CPE->RefCount++;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000822
Evan Cheng10043e22007-01-19 07:51:42 +0000823 // Instructions can only use one CP entry, don't bother scanning the
824 // rest of the operands.
825 break;
826 }
827 }
Evan Cheng10043e22007-01-19 07:51:42 +0000828 }
829}
830
Jim Grosbach190e7b62012-03-23 23:07:03 +0000831/// getOffsetOf - Return the current offset of the specified machine instruction
Evan Cheng10043e22007-01-19 07:51:42 +0000832/// from the start of the function. This offset changes as stuff is moved
833/// around inside the function.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000834unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
Evan Cheng10043e22007-01-19 07:51:42 +0000835 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000836
Evan Cheng10043e22007-01-19 07:51:42 +0000837 // The offset is composed of two things: the sum of the sizes of all MBB's
838 // before this instruction's block, and the offset from the start of the block
839 // it is in.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000840 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000841
842 // Sum instructions before MI in MBB.
Jim Grosbach44091c22012-01-31 20:56:55 +0000843 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
Evan Cheng10043e22007-01-19 07:51:42 +0000844 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000845 Offset += TII->getInstSizeInBytes(*I);
Evan Cheng10043e22007-01-19 07:51:42 +0000846 }
Jim Grosbach44091c22012-01-31 20:56:55 +0000847 return Offset;
Evan Cheng10043e22007-01-19 07:51:42 +0000848}
849
850/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
851/// ID.
852static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
853 const MachineBasicBlock *RHS) {
854 return LHS->getNumber() < RHS->getNumber();
855}
856
Jim Grosbach190e7b62012-03-23 23:07:03 +0000857/// updateForInsertedWaterBlock - When a block is newly inserted into the
Evan Cheng10043e22007-01-19 07:51:42 +0000858/// machine function, it upsets all of the block numbers. Renumber the blocks
859/// and update the arrays that parallel this numbering.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000860void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
Duncan Sands75b5d272011-02-15 09:23:02 +0000861 // Renumber the MBB's to keep them consecutive.
Evan Cheng10043e22007-01-19 07:51:42 +0000862 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000863
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000864 // Insert an entry into BBInfo to align it properly with the (newly
Evan Cheng10043e22007-01-19 07:51:42 +0000865 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000866 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000867
868 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Cheng10043e22007-01-19 07:51:42 +0000869 // available water after it.
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000870 water_iterator IP =
Evan Cheng10043e22007-01-19 07:51:42 +0000871 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
872 CompareMBBNumbers);
873 WaterList.insert(IP, NewBB);
874}
875
876
877/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilson2f9be502009-10-15 20:49:47 +0000878/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng345877e2007-01-31 02:22:22 +0000879/// account for this change and returns the newly created block.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000880MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
Evan Cheng10043e22007-01-19 07:51:42 +0000881 MachineBasicBlock *OrigBB = MI->getParent();
882
883 // Create a new MBB for the code after the OrigBB.
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000884 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000885 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +0000886 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000887 MF->insert(MBBI, NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000888
Evan Cheng10043e22007-01-19 07:51:42 +0000889 // Splice the instructions starting with MI over to NewBB.
890 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000891
Evan Cheng10043e22007-01-19 07:51:42 +0000892 // Add an unconditional branch from OrigBB to NewBB.
Evan Cheng7169bd82007-01-31 18:29:27 +0000893 // Note the new unconditional branch is not being recorded.
Dale Johannesen7647da62009-02-13 02:25:56 +0000894 // There doesn't seem to be meaningful DebugInfo available; this doesn't
895 // correspond to anything in the source.
Evan Cheng7c943432009-07-07 01:16:41 +0000896 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000897 if (!isThumb)
898 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
899 else
Diana Picusbd66b7d2017-01-20 08:15:24 +0000900 BuildMI(OrigBB, DebugLoc(), TII->get(Opc))
901 .addMBB(NewBB)
902 .add(predOps(ARMCC::AL));
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000903 ++NumSplit;
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000904
Evan Cheng10043e22007-01-19 07:51:42 +0000905 // Update the CFG. All succs of OrigBB are now succs of NewBB.
Jakob Stoklund Olesen26081572011-12-06 00:51:12 +0000906 NewBB->transferSuccessors(OrigBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000907
Evan Cheng10043e22007-01-19 07:51:42 +0000908 // OrigBB branches to NewBB.
909 OrigBB->addSuccessor(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000910
Evan Cheng10043e22007-01-19 07:51:42 +0000911 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000912 // This is almost the same as updateForInsertedWaterBlock, except that
Dale Johannesene18b13b2007-02-23 05:02:36 +0000913 // the Water goes after OrigBB, not NewBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +0000914 MF->RenumberBlocks(NewBB);
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000915
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000916 // Insert an entry into BBInfo to align it properly with the (newly
Dale Johannesene18b13b2007-02-23 05:02:36 +0000917 // renumbered) block numbers.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +0000918 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
Dale Johannesen01ee5752007-02-25 00:47:03 +0000919
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000920 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesene18b13b2007-02-23 05:02:36 +0000921 // available water after it (but not if it's already there, which happens
922 // when splitting before a conditional branch that is followed by an
923 // unconditional branch - in that case we want to insert NewBB).
Bob Wilsonc7a3cf42009-10-12 18:52:13 +0000924 water_iterator IP =
Dale Johannesene18b13b2007-02-23 05:02:36 +0000925 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
926 CompareMBBNumbers);
927 MachineBasicBlock* WaterBB = *IP;
928 if (WaterBB == OrigBB)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000929 WaterList.insert(std::next(IP), NewBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000930 else
931 WaterList.insert(IP, OrigBB);
Bob Wilson2f9be502009-10-15 20:49:47 +0000932 NewWaterList.insert(OrigBB);
Dale Johannesene18b13b2007-02-23 05:02:36 +0000933
Dale Johannesenc17dd572010-07-23 22:50:23 +0000934 // Figure out how large the OrigBB is. As the first half of the original
935 // block, it cannot contain a tablejump. The size includes
936 // the new jump we added. (It should be possible to do this without
937 // recounting everything, but it's very confusing, and this is rarely
938 // executed.)
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000939 computeBlockSize(MF, OrigBB, BBInfo[OrigBB->getNumber()]);
Dale Johannesen01ee5752007-02-25 00:47:03 +0000940
Dale Johannesenc17dd572010-07-23 22:50:23 +0000941 // Figure out how large the NewMBB is. As the second half of the original
942 // block, it may contain a tablejump.
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +0000943 computeBlockSize(MF, NewBB, BBInfo[NewBB->getNumber()]);
Dale Johannesenc17dd572010-07-23 22:50:23 +0000944
Dale Johannesen01ee5752007-02-25 00:47:03 +0000945 // All BBOffsets following these blocks must be modified.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000946 adjustBBOffsetsAfter(OrigBB);
Evan Cheng345877e2007-01-31 02:22:22 +0000947
948 return NewBB;
Evan Cheng10043e22007-01-19 07:51:42 +0000949}
950
Jim Grosbach190e7b62012-03-23 23:07:03 +0000951/// getUserOffset - Compute the offset of U.MI as seen by the hardware
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000952/// displacement computation. Update U.KnownAlignment to match its current
953/// basic block location.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000954unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
955 unsigned UserOffset = getOffsetOf(U.MI);
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000956 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
957 unsigned KnownBits = BBI.internalKnownBits();
958
959 // The value read from PC is offset from the actual instruction address.
960 UserOffset += (isThumb ? 4 : 8);
961
962 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
963 // Make sure U.getMaxDisp() returns a constrained range.
964 U.KnownAlignment = (KnownBits >= 2);
965
966 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
967 // purposes of the displacement computation; compensate for that here.
968 // For unknown alignments, getMaxDisp() constrains the range instead.
969 if (isThumb && U.KnownAlignment)
970 UserOffset &= ~3u;
971
972 return UserOffset;
973}
974
Jim Grosbach190e7b62012-03-23 23:07:03 +0000975/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson2f4e56f2009-05-12 17:09:30 +0000976/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen4a00cf32007-04-29 19:19:30 +0000977/// constant pool entry).
Jim Grosbach190e7b62012-03-23 23:07:03 +0000978/// UserOffset is computed by getUserOffset above to include PC adjustments. If
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +0000979/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
980/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
Jim Grosbach190e7b62012-03-23 23:07:03 +0000981bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
Evan Chengd2919a12009-07-23 18:27:47 +0000982 unsigned TrialOffset, unsigned MaxDisp,
983 bool NegativeOK, bool IsSoImm) {
Dale Johannesen01ee5752007-02-25 00:47:03 +0000984 if (UserOffset <= TrialOffset) {
985 // User before the Trial.
Evan Chengd2919a12009-07-23 18:27:47 +0000986 if (TrialOffset - UserOffset <= MaxDisp)
987 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000988 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000989 } else if (NegativeOK) {
Evan Chengd2919a12009-07-23 18:27:47 +0000990 if (UserOffset - TrialOffset <= MaxDisp)
991 return true;
Evan Chengc26c76e2009-07-24 19:31:03 +0000992 // FIXME: Make use full range of soimm values.
Dale Johannesen01ee5752007-02-25 00:47:03 +0000993 }
994 return false;
995}
996
Jim Grosbach190e7b62012-03-23 23:07:03 +0000997/// isWaterInRange - Returns true if a CPE placed after the specified
Dale Johannesene18b13b2007-02-23 05:02:36 +0000998/// Water (a basic block) will be in range for the specific MI.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +0000999///
1000/// Compute how much the function will grow by inserting a CPE after Water.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001001bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001002 MachineBasicBlock* Water, CPUser &U,
1003 unsigned &Growth) {
1004 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1005 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1006 unsigned NextBlockOffset, NextBlockAlignment;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001007 MachineFunction::const_iterator NextBlock = Water->getIterator();
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001008 if (++NextBlock == MF->end()) {
1009 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1010 NextBlockAlignment = 0;
1011 } else {
1012 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1013 NextBlockAlignment = NextBlock->getAlignment();
1014 }
1015 unsigned Size = U.CPEMI->getOperand(2).getImm();
1016 unsigned CPEEnd = CPEOffset + Size;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001017
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001018 // The CPE may be able to hide in the alignment padding before the next
1019 // block. It may also cause more padding to be required if it is more aligned
1020 // that the next block.
1021 if (CPEEnd > NextBlockOffset) {
1022 Growth = CPEEnd - NextBlockOffset;
1023 // Compute the padding that would go at the end of the CPE to align the next
1024 // block.
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001025 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001026
1027 // If the CPE is to be inserted before the instruction, that will raise
Jim Grosbach190e7b62012-03-23 23:07:03 +00001028 // the offset of the instruction. Also account for unknown alignment padding
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001029 // in blocks between CPE and the user.
1030 if (CPEOffset < UserOffset)
1031 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1032 } else
1033 // CPE fits in existing padding.
1034 Growth = 0;
Dale Johannesend13786d2007-04-02 20:31:06 +00001035
Jim Grosbach190e7b62012-03-23 23:07:03 +00001036 return isOffsetInRange(UserOffset, CPEOffset, U);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001037}
1038
Jim Grosbach190e7b62012-03-23 23:07:03 +00001039/// isCPEntryInRange - Returns true if the distance between specific MI and
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001040/// specific ConstPool entry instruction can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001041bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng87aaa192009-07-21 23:56:01 +00001042 MachineInstr *CPEMI, unsigned MaxDisp,
1043 bool NegOk, bool DoDump) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001044 unsigned CPEOffset = getOffsetOf(CPEMI);
Evan Cheng234e0312007-02-01 01:09:47 +00001045
Dale Johannesene18b13b2007-02-23 05:02:36 +00001046 if (DoDump) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001047 DEBUG({
1048 unsigned Block = MI->getParent()->getNumber();
1049 const BasicBlockInfo &BBI = BBInfo[Block];
1050 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1051 << " max delta=" << MaxDisp
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001052 << format(" insn address=%#x", UserOffset)
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001053 << " in BB#" << Block << ": "
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001054 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1055 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1056 int(CPEOffset-UserOffset));
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001057 });
Dale Johannesene18b13b2007-02-23 05:02:36 +00001058 }
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001059
Jim Grosbach190e7b62012-03-23 23:07:03 +00001060 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001061}
1062
Evan Chenge4510972009-01-28 00:53:34 +00001063#ifndef NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001064/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1065/// unconditionally branches to its only successor.
1066static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1067 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1068 return false;
1069
1070 MachineBasicBlock *Succ = *MBB->succ_begin();
1071 MachineBasicBlock *Pred = *MBB->pred_begin();
1072 MachineInstr *PredMI = &Pred->back();
David Goodwin27303cd2009-06-30 18:04:13 +00001073 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1074 || PredMI->getOpcode() == ARM::t2B)
Evan Cheng8b7700f2007-02-09 20:54:44 +00001075 return PredMI->getOperand(0).getMBB() == Succ;
1076 return false;
1077}
Evan Chenge4510972009-01-28 00:53:34 +00001078#endif // NDEBUG
Evan Cheng8b7700f2007-02-09 20:54:44 +00001079
Jim Grosbach190e7b62012-03-23 23:07:03 +00001080void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001081 unsigned BBNum = BB->getNumber();
1082 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001083 // Get the offset and known bits at the end of the layout predecessor.
Jakob Stoklund Olesen91a7bcb2011-12-12 19:25:54 +00001084 // Include the alignment of the current block.
1085 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1086 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1087 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001088
Jakob Stoklund Olesen69051112012-01-06 21:40:15 +00001089 // This is where block i begins. Stop if the offset is already correct,
1090 // and we have updated 2 blocks. This is the maximum number of blocks
1091 // changed before calling this function.
1092 if (i > BBNum + 2 &&
1093 BBInfo[i].Offset == Offset &&
1094 BBInfo[i].KnownBits == KnownBits)
1095 break;
1096
Jakob Stoklund Olesen2a823332011-12-08 00:55:02 +00001097 BBInfo[i].Offset = Offset;
1098 BBInfo[i].KnownBits = KnownBits;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001099 }
Dale Johannesen01ee5752007-02-25 00:47:03 +00001100}
1101
Jim Grosbach190e7b62012-03-23 23:07:03 +00001102/// decrementCPEReferenceCount - find the constant pool entry with index CPI
Dale Johannesene18b13b2007-02-23 05:02:36 +00001103/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001104/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesene18b13b2007-02-23 05:02:36 +00001105/// the entry, false if we didn't.
Evan Cheng10043e22007-01-19 07:51:42 +00001106
Jim Grosbach190e7b62012-03-23 23:07:03 +00001107bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1108 MachineInstr *CPEMI) {
Evan Cheng8b7700f2007-02-09 20:54:44 +00001109 // Find the old entry. Eliminate it if it is no longer used.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001110 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1111 assert(CPE && "Unexpected!");
1112 if (--CPE->RefCount == 0) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001113 removeDeadCPEMI(CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001114 CPE->CPEMI = nullptr;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001115 --NumCPEs;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001116 return true;
1117 }
1118 return false;
1119}
1120
Tim Northovera603c402015-05-31 19:22:07 +00001121unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1122 if (CPEMI->getOperand(1).isCPI())
1123 return CPEMI->getOperand(1).getIndex();
1124
1125 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1126}
1127
Dale Johannesene18b13b2007-02-23 05:02:36 +00001128/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1129/// if not, see if an in-range clone of the CPE is in range, and if so,
1130/// change the data structures so the user references the clone. Returns:
1131/// 0 = no existing entry found
1132/// 1 = entry found, and there were no code insertions or deletions
1133/// 2 = entry found, and there were code insertions or deletions
Jim Grosbach190e7b62012-03-23 23:07:03 +00001134int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001135{
1136 MachineInstr *UserMI = U.MI;
1137 MachineInstr *CPEMI = U.CPEMI;
1138
1139 // Check to see if the CPE is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001140 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1141 true)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001142 DEBUG(dbgs() << "In range\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001143 return 1;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001144 }
1145
Dale Johannesene18b13b2007-02-23 05:02:36 +00001146 // No. Look for previously created clones of the CPE that are in range.
Tim Northovera603c402015-05-31 19:22:07 +00001147 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001148 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1149 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1150 // We already tried this one
1151 if (CPEs[i].CPEMI == CPEMI)
1152 continue;
1153 // Removing CPEs can leave empty entries, skip
Craig Topper062a2ba2014-04-25 05:30:21 +00001154 if (CPEs[i].CPEMI == nullptr)
Dale Johannesene18b13b2007-02-23 05:02:36 +00001155 continue;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001156 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001157 U.NegOk)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001158 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
Chris Lattneraf29ea62009-08-23 06:49:22 +00001159 << CPEs[i].CPI << "\n");
Dale Johannesene18b13b2007-02-23 05:02:36 +00001160 // Point the CPUser node to the replacement
1161 U.CPEMI = CPEs[i].CPEMI;
1162 // Change the CPI in the instruction operand to refer to the clone.
1163 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001164 if (UserMI->getOperand(j).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001165 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001166 break;
1167 }
1168 // Adjust the refcount of the clone...
1169 CPEs[i].RefCount++;
1170 // ...and the original. If we didn't remove the old entry, none of the
1171 // addresses changed, so we don't need another pass.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001172 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
Dale Johannesene18b13b2007-02-23 05:02:36 +00001173 }
1174 }
1175 return 0;
1176}
1177
Dale Johannesen440995b2007-02-28 18:41:23 +00001178/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1179/// the specific unconditional branch instruction.
1180static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin27303cd2009-06-30 18:04:13 +00001181 switch (Opc) {
1182 case ARM::tB:
1183 return ((1<<10)-1)*2;
1184 case ARM::t2B:
1185 return ((1<<23)-1)*2;
1186 default:
1187 break;
1188 }
Jim Grosbachf24f9d92009-08-11 15:33:49 +00001189
David Goodwin27303cd2009-06-30 18:04:13 +00001190 return ((1<<23)-1)*4;
Dale Johannesen440995b2007-02-28 18:41:23 +00001191}
1192
Jim Grosbach190e7b62012-03-23 23:07:03 +00001193/// findAvailableWater - Look for an existing entry in the WaterList in which
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001194/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilson2f9be502009-10-15 20:49:47 +00001195/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001196/// is set to the WaterList entry. For Thumb, prefer water that will not
1197/// introduce padding to water that will. To ensure that this pass
1198/// terminates, the CPE location for a particular CPUser is only allowed to
1199/// move to a lower address, so search backward from the end of the list and
1200/// prefer the first water that is in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001201bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001202 water_iterator &WaterIter,
1203 bool CloserWater) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001204 if (WaterList.empty())
1205 return false;
1206
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001207 unsigned BestGrowth = ~0u;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001208 // The nearest water without splitting the UserBB is right after it.
1209 // If the distance is still large (we have a big BB), then we need to split it
1210 // if we don't converge after certain iterations. This helps the following
1211 // situation to converge:
1212 // BB0:
1213 // Big BB
1214 // BB1:
1215 // Constant Pool
1216 // When a CP access is out of range, BB0 may be used as water. However,
1217 // inserting islands between BB0 and BB1 makes other accesses out of range.
1218 MachineBasicBlock *UserBB = U.MI->getParent();
1219 unsigned MinNoSplitDisp =
1220 BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1221 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1222 return false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001223 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001224 --IP) {
Bob Wilson3a7326e2009-10-12 19:04:03 +00001225 MachineBasicBlock* WaterBB = *IP;
Bob Wilson2f9be502009-10-15 20:49:47 +00001226 // Check if water is in range and is either at a lower address than the
1227 // current "high water mark" or a new water block that was created since
1228 // the previous iteration by inserting an unconditional branch. In the
1229 // latter case, we want to allow resetting the high water mark back to
1230 // this new water since we haven't seen it before. Inserting branches
1231 // should be relatively uncommon and when it does happen, we want to be
1232 // sure to take advantage of it for all the CPEs near that block, so that
1233 // we don't insert more branches than necessary.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001234 // When CloserWater is true, we try to find the lowest address after (or
1235 // equal to) user MI's BB no matter of padding growth.
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001236 unsigned Growth;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001237 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
Bob Wilson2f9be502009-10-15 20:49:47 +00001238 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
Tim Northover631cc9c2014-11-13 17:58:53 +00001239 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1240 Growth < BestGrowth) {
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001241 // This is the least amount of required padding seen so far.
1242 BestGrowth = Growth;
1243 WaterIter = IP;
1244 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1245 << " Growth=" << Growth << '\n');
1246
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001247 if (CloserWater && WaterBB == U.MI->getParent())
1248 return true;
1249 // Keep looking unless it is perfect and we're not looking for the lowest
1250 // possible address.
1251 if (!CloserWater && BestGrowth == 0)
Bob Wilson3a7326e2009-10-12 19:04:03 +00001252 return true;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001253 }
Bob Wilson3a7326e2009-10-12 19:04:03 +00001254 if (IP == B)
1255 break;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001256 }
Jakob Stoklund Olesenbfa576f2011-12-13 00:44:30 +00001257 return BestGrowth != ~0u;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001258}
1259
Jim Grosbach190e7b62012-03-23 23:07:03 +00001260/// createNewWater - No existing WaterList entry will work for
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001261/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1262/// block is used if in range, and the conditional branch munged so control
1263/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson3250e772009-10-12 21:39:43 +00001264/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001265/// block following which the new island can be inserted (the WaterList
1266/// is not adjusted).
Jim Grosbach190e7b62012-03-23 23:07:03 +00001267void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
Bob Wilson3250e772009-10-12 21:39:43 +00001268 unsigned UserOffset,
1269 MachineBasicBlock *&NewMBB) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001270 CPUser &U = CPUsers[CPUserIndex];
1271 MachineInstr *UserMI = U.MI;
1272 MachineInstr *CPEMI = U.CPEMI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001273 unsigned CPELogAlign = getCPELogAlign(CPEMI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001274 MachineBasicBlock *UserMBB = UserMI->getParent();
Jakob Stoklund Olesen146ac7b2011-12-10 02:55:10 +00001275 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001276
Bob Wilsonb4f2a852009-10-15 05:10:36 +00001277 // If the block does not end in an unconditional branch already, and if the
1278 // end of the block is within range, make new water there. (The addition
1279 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001280 // Thumb2, 2 on Thumb1.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001281 if (BBHasFallthrough(UserMBB)) {
1282 // Size of branch to insert.
1283 unsigned Delta = isThumb1 ? 2 : 4;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001284 // Compute the offset where the CPE will begin.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001285 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001286
Jim Grosbach190e7b62012-03-23 23:07:03 +00001287 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001288 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1289 << format(", expected CPE offset %#x\n", CPEOffset));
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001290 NewMBB = &*++UserMBB->getIterator();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001291 // Add an unconditional branch from UserMBB to fallthrough block. Record
1292 // it for branch lengthening; this new branch will not get out of range,
1293 // but if the preceding conditional branch is out of range, the targets
1294 // will be exchanged, and the altered branch may be out of range, so the
1295 // machinery has to know about it.
1296 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1297 if (!isThumb)
1298 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1299 else
Diana Picusbd66b7d2017-01-20 08:15:24 +00001300 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
1301 .addMBB(NewMBB)
1302 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001303 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1304 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1305 MaxDisp, false, UncondBr));
Sjoerd Meijer5c0ef832016-07-22 08:39:12 +00001306 computeBlockSize(MF, UserMBB, BBInfo[UserMBB->getNumber()]);
Jim Grosbach190e7b62012-03-23 23:07:03 +00001307 adjustBBOffsetsAfter(UserMBB);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001308 return;
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001309 }
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001310 }
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001311
1312 // What a big block. Find a place within the block to split it. This is a
1313 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1314 // entries are 4 bytes: if instruction I references island CPE, and
1315 // instruction I+1 references CPE', it will not work well to put CPE as far
1316 // forward as possible, since then CPE' cannot immediately follow it (that
1317 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1318 // need to create a new island. So, we make a first guess, then walk through
1319 // the instructions between the one currently being looked at and the
1320 // possible insertion point, and make sure any other instructions that
1321 // reference CPEs will be able to use the same island area; if not, we back
1322 // up the insertion point.
1323
1324 // Try to split the block so it's fully aligned. Compute the latest split
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001325 // point where we can add a 4-byte branch instruction, and then align to
1326 // LogAlign which is the largest possible alignment in the function.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001327 unsigned LogAlign = MF->getAlignment();
1328 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1329 unsigned KnownBits = UserBBI.internalKnownBits();
1330 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001331 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001332 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1333 BaseInsertOffset));
1334
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001335 // The 4 in the following is for the unconditional branch we'll be inserting
1336 // (allows for long branch on Thumb1). Alignment of the island is handled
Jim Grosbach190e7b62012-03-23 23:07:03 +00001337 // inside isOffsetInRange.
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001338 BaseInsertOffset -= 4;
1339
1340 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1341 << " la=" << LogAlign
1342 << " kb=" << KnownBits
1343 << " up=" << UPad << '\n');
1344
1345 // This could point off the end of the block if we've already got constant
1346 // pool entries following this block; only the last one is in the water list.
1347 // Back past any possible branches (allow for a conditional and a maximally
1348 // long unconditional).
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001349 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
Akira Hatanaka0d0c7812014-10-17 01:31:47 +00001350 // Ensure BaseInsertOffset is larger than the offset of the instruction
1351 // following UserMI so that the loop which searches for the split point
1352 // iterates at least once.
1353 BaseInsertOffset =
1354 std::max(UserBBI.postOffset() - UPad - 8,
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001355 UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001356 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1357 }
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001358 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001359 CPEMI->getOperand(2).getImm();
1360 MachineBasicBlock::iterator MI = UserMI;
1361 ++MI;
1362 unsigned CPUIndex = CPUserIndex+1;
1363 unsigned NumCPUsers = CPUsers.size();
Craig Topper062a2ba2014-04-25 05:30:21 +00001364 MachineInstr *LastIT = nullptr;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001365 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001366 Offset < BaseInsertOffset;
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001367 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
Jakob Stoklund Olesenae7521d2012-04-28 06:21:38 +00001368 assert(MI != UserMBB->end() && "Fell off end of block");
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001369 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001370 CPUser &U = CPUsers[CPUIndex];
Jim Grosbach190e7b62012-03-23 23:07:03 +00001371 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001372 // Shift intertion point by one unit of alignment so it is within reach.
1373 BaseInsertOffset -= 1u << LogAlign;
1374 EndInsertOffset -= 1u << LogAlign;
1375 }
1376 // This is overly conservative, as we don't account for CPEMIs being
1377 // reused within the block, but it doesn't matter much. Also assume CPEs
1378 // are added in order with alignment padding. We may eventually be able
1379 // to pack the aligned CPEs better.
Jakob Stoklund Olesen5f0d1b42012-04-27 22:58:38 +00001380 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001381 CPUIndex++;
1382 }
1383
1384 // Remember the last IT instruction.
1385 if (MI->getOpcode() == ARM::t2IT)
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001386 LastIT = &*MI;
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001387 }
1388
1389 --MI;
1390
1391 // Avoid splitting an IT block.
1392 if (LastIT) {
1393 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001394 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
Jakob Stoklund Olesen9efd7eb2011-12-14 23:48:54 +00001395 if (CC != ARMCC::AL)
1396 MI = LastIT;
1397 }
Tim Northover631cc9c2014-11-13 17:58:53 +00001398
1399 // We really must not split an IT block.
1400 DEBUG(unsigned PredReg;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001401 assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
Tim Northover631cc9c2014-11-13 17:58:53 +00001402
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001403 NewMBB = splitBlockBeforeInstr(&*MI);
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001404}
1405
Jim Grosbach190e7b62012-03-23 23:07:03 +00001406/// handleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001407/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesene18b13b2007-02-23 05:02:36 +00001408/// place in-range. Return true if we changed any addresses (thus must run
1409/// another pass of branch lengthening), false otherwise.
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001410bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1411 bool CloserWater) {
Dale Johannesen440995b2007-02-28 18:41:23 +00001412 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesene18b13b2007-02-23 05:02:36 +00001413 MachineInstr *UserMI = U.MI;
1414 MachineInstr *CPEMI = U.CPEMI;
Tim Northovera603c402015-05-31 19:22:07 +00001415 unsigned CPI = getCombinedIndex(CPEMI);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001416 unsigned Size = CPEMI->getOperand(2).getImm();
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001417 // Compute this only once, it's expensive.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001418 unsigned UserOffset = getUserOffset(U);
Evan Chengd9990f02007-04-27 08:14:15 +00001419
Dale Johannesene18b13b2007-02-23 05:02:36 +00001420 // See if the current entry is within range, or there is a clone of it
1421 // in range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001422 int result = findInRangeCPEntry(U, UserOffset);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001423 if (result==1) return false;
1424 else if (result==2) return true;
1425
1426 // No existing clone of this CPE is within range.
1427 // We will be generating a new clone. Get a UID for it.
Evan Chengdfce83c2011-01-17 08:03:18 +00001428 unsigned ID = AFI->createPICLabelUId();
Dale Johannesene18b13b2007-02-23 05:02:36 +00001429
Bob Wilsoncc121aa2009-10-12 21:23:15 +00001430 // Look for water where we can place this CPE.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001431 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
Bob Wilson2f9be502009-10-15 20:49:47 +00001432 MachineBasicBlock *NewMBB;
1433 water_iterator IP;
Weiming Zhao5e0c3eb2016-02-23 18:39:19 +00001434 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001435 DEBUG(dbgs() << "Found water in range\n");
Bob Wilson2f9be502009-10-15 20:49:47 +00001436 MachineBasicBlock *WaterBB = *IP;
1437
1438 // If the original WaterList entry was "new water" on this iteration,
1439 // propagate that to the new island. This is just keeping NewWaterList
1440 // updated to match the WaterList, which will be updated below.
Benjamin Kramerf29db272012-08-22 15:37:57 +00001441 if (NewWaterList.erase(WaterBB))
Bob Wilson2f9be502009-10-15 20:49:47 +00001442 NewWaterList.insert(NewIsland);
Benjamin Kramerf29db272012-08-22 15:37:57 +00001443
Bob Wilson2f9be502009-10-15 20:49:47 +00001444 // The new CPE goes before the following block (NewMBB).
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001445 NewMBB = &*++WaterBB->getIterator();
Bob Wilson2f9be502009-10-15 20:49:47 +00001446 } else {
Dale Johannesene18b13b2007-02-23 05:02:36 +00001447 // No water found.
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001448 DEBUG(dbgs() << "No water found\n");
Jim Grosbach190e7b62012-03-23 23:07:03 +00001449 createNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001450
Jim Grosbach190e7b62012-03-23 23:07:03 +00001451 // splitBlockBeforeInstr adds to WaterList, which is important when it is
Bob Wilson2f9be502009-10-15 20:49:47 +00001452 // called while handling branches so that the water will be seen on the
1453 // next iteration for constant pools, but in this context, we don't want
1454 // it. Check for this so it will be removed from the WaterList.
1455 // Also remove any entry from NewWaterList.
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001456 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
David Majnemer0d955d02016-08-11 22:21:41 +00001457 IP = find(WaterList, WaterBB);
Bob Wilson2f9be502009-10-15 20:49:47 +00001458 if (IP != WaterList.end())
1459 NewWaterList.erase(WaterBB);
1460
1461 // We are adding new water. Update NewWaterList.
1462 NewWaterList.insert(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001463 }
1464
Bob Wilson2f9be502009-10-15 20:49:47 +00001465 // Remove the original WaterList entry; we want subsequent insertions in
1466 // this vicinity to go after the one we're about to insert. This
1467 // considerably reduces the number of times we have to move the same CPE
1468 // more than once and is also important to ensure the algorithm terminates.
1469 if (IP != WaterList.end())
1470 WaterList.erase(IP);
1471
Dale Johannesene18b13b2007-02-23 05:02:36 +00001472 // Okay, we know we can put an island before NewMBB now, do it!
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001473 MF->insert(NewMBB->getIterator(), NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001474
1475 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001476 updateForInsertedWaterBlock(NewIsland);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001477
Dale Johannesene18b13b2007-02-23 05:02:36 +00001478 // Now that we have an island to add the CPE to, clone the original CPE and
1479 // add it to the island.
Bob Wilson68ead6c2009-10-15 05:52:29 +00001480 U.HighWaterMark = NewIsland;
Tim Northovera603c402015-05-31 19:22:07 +00001481 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
Diana Picus116bbab2017-01-13 09:58:52 +00001482 .addImm(ID)
1483 .add(CPEMI->getOperand(1))
1484 .addImm(Size);
Dale Johannesene18b13b2007-02-23 05:02:36 +00001485 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001486 ++NumCPEs;
Evan Cheng8b7700f2007-02-09 20:54:44 +00001487
Tim Northovera603c402015-05-31 19:22:07 +00001488 // Decrement the old entry, and remove it if refcount becomes 0.
1489 decrementCPEReferenceCount(CPI, CPEMI);
1490
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001491 // Mark the basic block as aligned as required by the const-pool entry.
1492 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
Jakob Stoklund Olesen2e05db22011-12-06 01:43:02 +00001493
Evan Cheng10043e22007-01-19 07:51:42 +00001494 // Increase the size of the island block to account for the new entry.
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001495 BBInfo[NewIsland->getNumber()].Size += Size;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001496 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001497
Evan Cheng10043e22007-01-19 07:51:42 +00001498 // Finally, change the CPI in the instruction operand to be ID.
1499 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001500 if (UserMI->getOperand(i).isCPI()) {
Chris Lattnera5bb3702007-12-30 23:10:15 +00001501 UserMI->getOperand(i).setIndex(ID);
Evan Cheng10043e22007-01-19 07:51:42 +00001502 break;
1503 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001504
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001505 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
Jakob Stoklund Olesenb3734522011-12-10 02:55:06 +00001506 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001507
Evan Cheng10043e22007-01-19 07:51:42 +00001508 return true;
1509}
1510
Jim Grosbach190e7b62012-03-23 23:07:03 +00001511/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001512/// sizes and offsets of impacted basic blocks.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001513void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001514 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001515 unsigned Size = CPEMI->getOperand(2).getImm();
1516 CPEMI->eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001517 BBInfo[CPEBB->getNumber()].Size -= Size;
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001518 // All succeeding offsets have the current size value added in, fix this.
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001519 if (CPEBB->empty()) {
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001520 BBInfo[CPEBB->getNumber()].Size = 0;
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001521
Evan Chengab28b9a2013-02-21 18:37:54 +00001522 // This block no longer needs to be aligned.
Jakob Stoklund Olesen2fa74482011-12-06 21:55:35 +00001523 CPEBB->setAlignment(0);
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001524 } else
1525 // Entries are sorted by descending alignment, so realign from the front.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00001526 CPEBB->setAlignment(getCPELogAlign(&*CPEBB->begin()));
Jakob Stoklund Olesen17c27a82011-12-12 18:45:45 +00001527
Jim Grosbach190e7b62012-03-23 23:07:03 +00001528 adjustBBOffsetsAfter(CPEBB);
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001529 // An island has only one predecessor BB and one successor BB. Check if
1530 // this BB's predecessor jumps directly to this BB's successor. This
1531 // shouldn't happen currently.
1532 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1533 // FIXME: remove the empty blocks after all the work is done?
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001534}
1535
Jim Grosbach190e7b62012-03-23 23:07:03 +00001536/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001537/// are zero.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001538bool ARMConstantIslands::removeUnusedCPEntries() {
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001539 unsigned MadeChange = false;
1540 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1541 std::vector<CPEntry> &CPEs = CPEntries[i];
1542 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1543 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001544 removeDeadCPEMI(CPEs[j].CPEMI);
Craig Topper062a2ba2014-04-25 05:30:21 +00001545 CPEs[j].CPEMI = nullptr;
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001546 MadeChange = true;
1547 }
1548 }
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001549 }
Evan Cheng3c68d4e2007-04-03 23:39:48 +00001550 return MadeChange;
1551}
1552
Jim Grosbach190e7b62012-03-23 23:07:03 +00001553/// isBBInRange - Returns true if the distance between specific MI and
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001554/// specific BB can fit in MI's displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001555bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001556 unsigned MaxDisp) {
Dale Johannesen962fa8e2007-02-28 23:20:38 +00001557 unsigned PCAdj = isThumb ? 4 : 8;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001558 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001559 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001560
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001561 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
Chris Lattnera6f074f2009-08-23 03:41:05 +00001562 << " from BB#" << MI->getParent()->getNumber()
1563 << " max delta=" << MaxDisp
Jim Grosbach190e7b62012-03-23 23:07:03 +00001564 << " from " << getOffsetOf(MI) << " to " << DestOffset
Chris Lattnera6f074f2009-08-23 03:41:05 +00001565 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001566
Dale Johannesen4a00cf32007-04-29 19:19:30 +00001567 if (BrOffset <= DestOffset) {
1568 // Branch before the Dest.
1569 if (DestOffset-BrOffset <= MaxDisp)
1570 return true;
1571 } else {
1572 if (BrOffset-DestOffset <= MaxDisp)
1573 return true;
1574 }
1575 return false;
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001576}
1577
Jim Grosbach190e7b62012-03-23 23:07:03 +00001578/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
Evan Cheng7fa69642007-01-30 01:18:38 +00001579/// away to fit in its displacement field.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001580bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
Evan Cheng22c7cf52007-01-25 03:12:46 +00001581 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001582 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001583
Evan Cheng1f3fc4b2007-01-31 19:57:44 +00001584 // Check to see if the DestBB is already in-range.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001585 if (isBBInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001586 return false;
Evan Cheng22c7cf52007-01-25 03:12:46 +00001587
Evan Cheng7fa69642007-01-30 01:18:38 +00001588 if (!Br.isCond)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001589 return fixupUnconditionalBr(Br);
1590 return fixupConditionalBr(Br);
Evan Cheng7fa69642007-01-30 01:18:38 +00001591}
Evan Cheng22c7cf52007-01-25 03:12:46 +00001592
Jim Grosbach190e7b62012-03-23 23:07:03 +00001593/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
Dale Johannesene18b13b2007-02-23 05:02:36 +00001594/// too far away to fit in its displacement field. If the LR register has been
Evan Cheng7fa69642007-01-30 01:18:38 +00001595/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001596/// Otherwise, add an intermediate branch instruction to a branch.
Evan Cheng7fa69642007-01-30 01:18:38 +00001597bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001598ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001599 MachineInstr *MI = Br.MI;
1600 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng317bd7a2009-08-07 05:45:07 +00001601 if (!isThumb1)
Jim Grosbach190e7b62012-03-23 23:07:03 +00001602 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
Evan Cheng7fa69642007-01-30 01:18:38 +00001603
1604 // Use BL to implement far jump.
1605 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner59687512008-01-11 18:10:50 +00001606 MI->setDesc(TII->get(ARM::tBfar));
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001607 BBInfo[MBB->getNumber()].Size += 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001608 adjustBBOffsetsAfter(MBB);
Evan Cheng7fa69642007-01-30 01:18:38 +00001609 HasFarJump = true;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001610 ++NumUBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001611
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001612 DEBUG(dbgs() << " Changed B to long jump " << *MI);
Evan Cheng36d559d2007-02-03 02:08:34 +00001613
Evan Cheng7fa69642007-01-30 01:18:38 +00001614 return true;
1615}
1616
Jim Grosbach190e7b62012-03-23 23:07:03 +00001617/// fixupConditionalBr - Fix up a conditional branch whose destination is too
Evan Cheng7fa69642007-01-30 01:18:38 +00001618/// far away to fit in its displacement field. It is converted to an inverse
1619/// conditional branch + an unconditional branch to the destination.
1620bool
Jim Grosbach190e7b62012-03-23 23:07:03 +00001621ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
Evan Cheng7fa69642007-01-30 01:18:38 +00001622 MachineInstr *MI = Br.MI;
Chris Lattnera5bb3702007-12-30 23:10:15 +00001623 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Cheng7fa69642007-01-30 01:18:38 +00001624
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001625 // Add an unconditional branch to the destination and invert the branch
Evan Cheng7fa69642007-01-30 01:18:38 +00001626 // condition to jump over it:
Evan Cheng22c7cf52007-01-25 03:12:46 +00001627 // blt L1
1628 // =>
1629 // bge L2
1630 // b L1
1631 // L2:
Chris Lattner5c463782007-12-30 20:49:49 +00001632 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001633 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng94f04c62007-07-05 07:18:20 +00001634 unsigned CCReg = MI->getOperand(2).getReg();
Evan Cheng22c7cf52007-01-25 03:12:46 +00001635
1636 // If the branch is at the end of its MBB and that has a fall-through block,
1637 // direct the updated conditional branch to the fall-through block. Otherwise,
1638 // split the MBB before the next instruction.
1639 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng36d559d2007-02-03 02:08:34 +00001640 MachineInstr *BMI = &MBB->back();
1641 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001642
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001643 ++NumCBrFixed;
Evan Cheng36d559d2007-02-03 02:08:34 +00001644 if (BMI != MI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001645 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
Evan Cheng36d559d2007-02-03 02:08:34 +00001646 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001647 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001648 // condition and swap destinations:
1649 // beq L1
1650 // b L2
1651 // =>
1652 // bne L2
1653 // b L1
Chris Lattnera5bb3702007-12-30 23:10:15 +00001654 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001655 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001656 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
Chris Lattnera6f074f2009-08-23 03:41:05 +00001657 << *BMI);
Chris Lattnera5bb3702007-12-30 23:10:15 +00001658 BMI->getOperand(0).setMBB(DestBB);
1659 MI->getOperand(0).setMBB(NewDest);
Evan Cheng3c9dc6b2007-01-26 20:38:26 +00001660 MI->getOperand(1).setImm(CC);
1661 return true;
1662 }
1663 }
1664 }
1665
1666 if (NeedSplit) {
Jim Grosbach190e7b62012-03-23 23:07:03 +00001667 splitBlockBeforeInstr(MI);
Bob Wilsonce8cfb42009-05-12 17:35:29 +00001668 // No need for the branch to the next block. We're adding an unconditional
Evan Cheng1e270b62007-01-26 02:02:39 +00001669 // branch to the destination.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001670 int delta = TII->getInstSizeInBytes(MBB->back());
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001671 BBInfo[MBB->getNumber()].Size -= delta;
Evan Cheng1e270b62007-01-26 02:02:39 +00001672 MBB->back().eraseFromParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001673 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
Evan Cheng1e270b62007-01-26 02:02:39 +00001674 }
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001675 MachineBasicBlock *NextBB = &*++MBB->getIterator();
Bob Wilson2f4e56f2009-05-12 17:09:30 +00001676
Jakob Stoklund Olesen5f5fa122011-12-09 18:20:35 +00001677 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
Chris Lattneraf29ea62009-08-23 06:49:22 +00001678 << " also invert condition and change dest. to BB#"
1679 << NextBB->getNumber() << "\n");
Evan Cheng22c7cf52007-01-25 03:12:46 +00001680
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001681 // Insert a new conditional branch and a new unconditional branch.
Evan Cheng22c7cf52007-01-25 03:12:46 +00001682 // Also update the ImmBranch as well as adding a new entry for the new branch.
Chris Lattner6f306d72010-04-02 20:16:16 +00001683 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
Dale Johannesen7647da62009-02-13 02:25:56 +00001684 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001685 Br.MI = &MBB->back();
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001686 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Owen Anderson93cd3182011-09-09 23:05:14 +00001687 if (isThumb)
Diana Picusbd66b7d2017-01-20 08:15:24 +00001688 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))
1689 .addMBB(DestBB)
1690 .add(predOps(ARMCC::AL));
Owen Anderson93cd3182011-09-09 23:05:14 +00001691 else
1692 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001693 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
Evan Cheng7169bd82007-01-31 18:29:27 +00001694 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Cheng1d138982007-01-25 23:31:04 +00001695 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesenfdfb7572007-04-23 20:09:04 +00001696
1697 // Remove the old conditional branch. It may or may not still be in MBB.
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001698 BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001699 MI->eraseFromParent();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001700 adjustBBOffsetsAfter(MBB);
Evan Cheng22c7cf52007-01-25 03:12:46 +00001701 return true;
1702}
Evan Cheng7fa69642007-01-30 01:18:38 +00001703
Jim Grosbach190e7b62012-03-23 23:07:03 +00001704/// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Chengcc9ca352009-08-11 21:11:32 +00001705/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1706/// to do this if tBfar is not used.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001707bool ARMConstantIslands::undoLRSpillRestore() {
Evan Cheng7fa69642007-01-30 01:18:38 +00001708 bool MadeChange = false;
1709 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1710 MachineInstr *MI = PushPopMIs[i];
Bob Wilson947f04b2010-03-13 01:08:20 +00001711 // First two operands are predicates.
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001712 if (MI->getOpcode() == ARM::tPOP_RET &&
Bob Wilson947f04b2010-03-13 01:08:20 +00001713 MI->getOperand(2).getReg() == ARM::PC &&
1714 MI->getNumExplicitOperands() == 3) {
Jim Grosbach74719372011-07-08 21:50:04 +00001715 // Create the new insn and copy the predicate from the old.
1716 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
Diana Picus116bbab2017-01-13 09:58:52 +00001717 .add(MI->getOperand(0))
1718 .add(MI->getOperand(1));
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001719 MI->eraseFromParent();
1720 MadeChange = true;
Evan Cheng7fa69642007-01-30 01:18:38 +00001721 }
1722 }
1723 return MadeChange;
1724}
Evan Chengc6d70ae2009-07-29 02:18:14 +00001725
Jim Grosbach190e7b62012-03-23 23:07:03 +00001726bool ARMConstantIslands::optimizeThumb2Instructions() {
Evan Chengdb73d682009-08-14 00:32:16 +00001727 bool MadeChange = false;
1728
1729 // Shrink ADR and LDR from constantpool.
1730 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1731 CPUser &U = CPUsers[i];
1732 unsigned Opcode = U.MI->getOpcode();
1733 unsigned NewOpc = 0;
1734 unsigned Scale = 1;
1735 unsigned Bits = 0;
1736 switch (Opcode) {
1737 default: break;
Owen Anderson9a4d4282010-12-13 22:51:08 +00001738 case ARM::t2LEApcrel:
Evan Chengdb73d682009-08-14 00:32:16 +00001739 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1740 NewOpc = ARM::tLEApcrel;
1741 Bits = 8;
1742 Scale = 4;
1743 }
1744 break;
1745 case ARM::t2LDRpci:
1746 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1747 NewOpc = ARM::tLDRpci;
1748 Bits = 8;
1749 Scale = 4;
1750 }
1751 break;
1752 }
1753
1754 if (!NewOpc)
1755 continue;
1756
Jim Grosbach190e7b62012-03-23 23:07:03 +00001757 unsigned UserOffset = getUserOffset(U);
Evan Chengdb73d682009-08-14 00:32:16 +00001758 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
Jakob Stoklund Olesenf09a3162012-01-10 01:34:59 +00001759
1760 // Be conservative with inline asm.
1761 if (!U.KnownAlignment)
1762 MaxOffs -= 2;
1763
Evan Chengdb73d682009-08-14 00:32:16 +00001764 // FIXME: Check if offset is multiple of scale if scale is not 4.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001765 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001766 DEBUG(dbgs() << "Shrink: " << *U.MI);
Evan Chengdb73d682009-08-14 00:32:16 +00001767 U.MI->setDesc(TII->get(NewOpc));
1768 MachineBasicBlock *MBB = U.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001769 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001770 adjustBBOffsetsAfter(MBB);
Evan Chengdb73d682009-08-14 00:32:16 +00001771 ++NumT2CPShrunk;
1772 MadeChange = true;
1773 }
1774 }
1775
Evan Chengdb73d682009-08-14 00:32:16 +00001776 return MadeChange;
1777}
1778
Jim Grosbach190e7b62012-03-23 23:07:03 +00001779bool ARMConstantIslands::optimizeThumb2Branches() {
Evan Chenge41903b2009-08-14 18:31:44 +00001780 bool MadeChange = false;
1781
Peter Collingbourne167668f2015-04-23 20:31:35 +00001782 // The order in which branches appear in ImmBranches is approximately their
1783 // order within the function body. By visiting later branches first, we reduce
1784 // the distance between earlier forward branches and their targets, making it
1785 // more likely that the cbn?z optimization, which can only apply to forward
1786 // branches, will succeed.
1787 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1788 ImmBranch &Br = ImmBranches[i-1];
Evan Chenge41903b2009-08-14 18:31:44 +00001789 unsigned Opcode = Br.MI->getOpcode();
1790 unsigned NewOpc = 0;
1791 unsigned Scale = 1;
1792 unsigned Bits = 0;
1793 switch (Opcode) {
1794 default: break;
1795 case ARM::t2B:
1796 NewOpc = ARM::tB;
1797 Bits = 11;
1798 Scale = 2;
1799 break;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001800 case ARM::t2Bcc: {
Evan Chenge41903b2009-08-14 18:31:44 +00001801 NewOpc = ARM::tBcc;
1802 Bits = 8;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001803 Scale = 2;
Evan Chenge41903b2009-08-14 18:31:44 +00001804 break;
1805 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001806 }
1807 if (NewOpc) {
1808 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1809 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Jim Grosbach190e7b62012-03-23 23:07:03 +00001810 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001811 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001812 Br.MI->setDesc(TII->get(NewOpc));
1813 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001814 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001815 adjustBBOffsetsAfter(MBB);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001816 ++NumT2BrShrunk;
1817 MadeChange = true;
1818 }
1819 }
1820
1821 Opcode = Br.MI->getOpcode();
1822 if (Opcode != ARM::tBcc)
Evan Chenge41903b2009-08-14 18:31:44 +00001823 continue;
1824
Evan Cheng6bb95252012-01-14 01:53:46 +00001825 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1826 // so this transformation is not safe.
1827 if (!Br.MI->killsRegister(ARM::CPSR))
1828 continue;
1829
Evan Cheng6f29ad92009-10-31 23:46:45 +00001830 NewOpc = 0;
1831 unsigned PredReg = 0;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001832 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
Evan Cheng6f29ad92009-10-31 23:46:45 +00001833 if (Pred == ARMCC::EQ)
1834 NewOpc = ARM::tCBZ;
1835 else if (Pred == ARMCC::NE)
1836 NewOpc = ARM::tCBNZ;
1837 if (!NewOpc)
1838 continue;
Evan Chenge41903b2009-08-14 18:31:44 +00001839 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Cheng6f29ad92009-10-31 23:46:45 +00001840 // Check if the distance is within 126. Subtract starting offset by 2
1841 // because the cmp will be eliminated.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001842 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001843 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
Evan Cheng6f29ad92009-10-31 23:46:45 +00001844 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
Evan Cheng88530e62011-04-01 22:09:28 +00001845 MachineBasicBlock::iterator CmpMI = Br.MI;
1846 if (CmpMI != Br.MI->getParent()->begin()) {
1847 --CmpMI;
1848 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1849 unsigned Reg = CmpMI->getOperand(0).getReg();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001850 Pred = getInstrPredicate(*CmpMI, PredReg);
Evan Cheng88530e62011-04-01 22:09:28 +00001851 if (Pred == ARMCC::AL &&
1852 CmpMI->getOperand(1).getImm() == 0 &&
1853 isARMLowRegister(Reg)) {
1854 MachineBasicBlock *MBB = Br.MI->getParent();
Jakob Stoklund Olesen24bb3d52012-03-31 00:06:42 +00001855 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
Evan Cheng88530e62011-04-01 22:09:28 +00001856 MachineInstr *NewBR =
1857 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1858 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1859 CmpMI->eraseFromParent();
1860 Br.MI->eraseFromParent();
1861 Br.MI = NewBR;
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00001862 BBInfo[MBB->getNumber()].Size -= 2;
Jim Grosbach190e7b62012-03-23 23:07:03 +00001863 adjustBBOffsetsAfter(MBB);
Evan Cheng88530e62011-04-01 22:09:28 +00001864 ++NumCBZ;
1865 MadeChange = true;
1866 }
Evan Cheng6f29ad92009-10-31 23:46:45 +00001867 }
1868 }
Evan Chenge41903b2009-08-14 18:31:44 +00001869 }
1870 }
1871
1872 return MadeChange;
Evan Chengdb73d682009-08-14 00:32:16 +00001873}
1874
Tim Northovera603c402015-05-31 19:22:07 +00001875static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1876 unsigned BaseReg) {
1877 if (I.getOpcode() != ARM::t2ADDrs)
1878 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001879
Tim Northovera603c402015-05-31 19:22:07 +00001880 if (I.getOperand(0).getReg() != EntryReg)
1881 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001882
Tim Northovera603c402015-05-31 19:22:07 +00001883 if (I.getOperand(1).getReg() != BaseReg)
1884 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001885
Tim Northovera603c402015-05-31 19:22:07 +00001886 // FIXME: what about CC and IdxReg?
1887 return true;
1888}
Tim Northover688f7bb2015-05-13 20:28:32 +00001889
Tim Northovera603c402015-05-31 19:22:07 +00001890/// \brief While trying to form a TBB/TBH instruction, we may (if the table
1891/// doesn't immediately follow the BR_JT) need access to the start of the
1892/// jump-table. We know one instruction that produces such a register; this
1893/// function works out whether that definition can be preserved to the BR_JT,
1894/// possibly by removing an intervening addition (which is usually needed to
1895/// calculate the actual entry to jump to).
1896bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
1897 MachineInstr *LEAMI,
1898 unsigned &DeadSize,
1899 bool &CanDeleteLEA,
1900 bool &BaseRegKill) {
1901 if (JumpMI->getParent() != LEAMI->getParent())
1902 return false;
Tim Northover688f7bb2015-05-13 20:28:32 +00001903
Tim Northovera603c402015-05-31 19:22:07 +00001904 // Now we hope that we have at least these instructions in the basic block:
1905 // BaseReg = t2LEA ...
1906 // [...]
1907 // EntryReg = t2ADDrs BaseReg, ...
1908 // [...]
1909 // t2BR_JT EntryReg
1910 //
1911 // We have to be very conservative about what we recognise here though. The
1912 // main perturbing factors to watch out for are:
1913 // + Spills at any point in the chain: not direct problems but we would
1914 // expect a blocking Def of the spilled register so in practice what we
1915 // can do is limited.
1916 // + EntryReg == BaseReg: this is the one situation we should allow a Def
1917 // of BaseReg, but only if the t2ADDrs can be removed.
1918 // + Some instruction other than t2ADDrs computing the entry. Not seen in
1919 // the wild, but we should be careful.
1920 unsigned EntryReg = JumpMI->getOperand(0).getReg();
1921 unsigned BaseReg = LEAMI->getOperand(0).getReg();
1922
1923 CanDeleteLEA = true;
1924 BaseRegKill = false;
1925 MachineInstr *RemovableAdd = nullptr;
1926 MachineBasicBlock::iterator I(LEAMI);
1927 for (++I; &*I != JumpMI; ++I) {
1928 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
1929 RemovableAdd = &*I;
1930 break;
1931 }
1932
1933 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1934 const MachineOperand &MO = I->getOperand(K);
1935 if (!MO.isReg() || !MO.getReg())
1936 continue;
1937 if (MO.isDef() && MO.getReg() == BaseReg)
1938 return false;
1939 if (MO.isUse() && MO.getReg() == BaseReg) {
1940 BaseRegKill = BaseRegKill || MO.isKill();
1941 CanDeleteLEA = false;
1942 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001943 }
1944 }
1945
Tim Northovera603c402015-05-31 19:22:07 +00001946 if (!RemovableAdd)
1947 return true;
Tim Northover688f7bb2015-05-13 20:28:32 +00001948
Tim Northovera603c402015-05-31 19:22:07 +00001949 // Check the add really is removable, and that nothing else in the block
1950 // clobbers BaseReg.
1951 for (++I; &*I != JumpMI; ++I) {
1952 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1953 const MachineOperand &MO = I->getOperand(K);
1954 if (!MO.isReg() || !MO.getReg())
1955 continue;
1956 if (MO.isDef() && MO.getReg() == BaseReg)
1957 return false;
1958 if (MO.isUse() && MO.getReg() == EntryReg)
1959 RemovableAdd = nullptr;
1960 }
1961 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001962
Tim Northovera603c402015-05-31 19:22:07 +00001963 if (RemovableAdd) {
1964 RemovableAdd->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00001965 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00001966 } else if (BaseReg == EntryReg) {
1967 // The add wasn't removable, but clobbered the base for the TBB. So we can't
1968 // preserve it.
1969 return false;
1970 }
Tim Northover688f7bb2015-05-13 20:28:32 +00001971
Tim Northovera603c402015-05-31 19:22:07 +00001972 // We reached the end of the block without seeing another definition of
1973 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
1974 // used in the TBB/TBH if necessary.
1975 return true;
1976}
Tim Northover688f7bb2015-05-13 20:28:32 +00001977
Tim Northovera603c402015-05-31 19:22:07 +00001978/// \brief Returns whether CPEMI is the first instruction in the block
1979/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
1980/// we can switch the first register to PC and usually remove the address
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001981/// calculation that preceded it.
Tim Northovera603c402015-05-31 19:22:07 +00001982static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00001983 MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
Tim Northovera603c402015-05-31 19:22:07 +00001984 MachineFunction *MF = MBB->getParent();
1985 ++MBB;
1986
1987 return MBB != MF->end() && MBB->begin() != MBB->end() &&
1988 &*MBB->begin() == CPEMI;
Tim Northover688f7bb2015-05-13 20:28:32 +00001989}
1990
Jim Grosbach190e7b62012-03-23 23:07:03 +00001991/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
Evan Chengdb73d682009-08-14 00:32:16 +00001992/// jumptables when it's possible.
Jim Grosbach190e7b62012-03-23 23:07:03 +00001993bool ARMConstantIslands::optimizeThumb2JumpTables() {
Evan Chengc6d70ae2009-07-29 02:18:14 +00001994 bool MadeChange = false;
1995
1996 // FIXME: After the tables are shrunk, can we get rid some of the
1997 // constantpool tables?
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00001998 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00001999 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002000
Evan Chengc6d70ae2009-07-29 02:18:14 +00002001 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2002 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2003 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002004 const MCInstrDesc &MCID = MI->getDesc();
2005 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002006 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Evan Chengc6d70ae2009-07-29 02:18:14 +00002007 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2008 unsigned JTI = JTOP.getIndex();
2009 assert(JTI < JT.size());
2010
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002011 bool ByteOk = true;
2012 bool HalfWordOk = true;
Jim Grosbach190e7b62012-03-23 23:07:03 +00002013 unsigned JTOffset = getOffsetOf(MI) + 4;
Jim Grosbach5d577142009-11-12 17:25:07 +00002014 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002015 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2016 MachineBasicBlock *MBB = JTBBs[j];
Jakob Stoklund Olesene2b3ff22011-12-07 01:08:25 +00002017 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
Evan Chenge3493a92009-07-29 23:20:20 +00002018 // Negative offset is not ok. FIXME: We should change BB layout to make
2019 // sure all the branches are forward.
Evan Chengf6d0fa32009-07-31 18:28:05 +00002020 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002021 ByteOk = false;
Evan Chenge64f48b2009-08-01 06:13:52 +00002022 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Chenge64f48b2009-08-01 06:13:52 +00002023 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Chengc6d70ae2009-07-29 02:18:14 +00002024 HalfWordOk = false;
2025 if (!ByteOk && !HalfWordOk)
2026 break;
2027 }
2028
Tim Northovera603c402015-05-31 19:22:07 +00002029 if (!ByteOk && !HalfWordOk)
2030 continue;
Jim Grosbach40eda102010-07-07 22:51:22 +00002031
James Molloy70a3d6d2016-11-01 13:37:41 +00002032 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
Tim Northovera603c402015-05-31 19:22:07 +00002033 MachineBasicBlock *MBB = MI->getParent();
2034 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2035 continue;
Tim Northovera603c402015-05-31 19:22:07 +00002036
Tim Northovera603c402015-05-31 19:22:07 +00002037 unsigned DeadSize = 0;
2038 bool CanDeleteLEA = false;
2039 bool BaseRegKill = false;
James Molloy70a3d6d2016-11-01 13:37:41 +00002040
2041 unsigned IdxReg = ~0U;
2042 bool IdxRegKill = true;
2043 if (isThumb2) {
2044 IdxReg = MI->getOperand(1).getReg();
2045 IdxRegKill = MI->getOperand(1).isKill();
2046
2047 bool PreservedBaseReg =
Tim Northovera603c402015-05-31 19:22:07 +00002048 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
James Molloy70a3d6d2016-11-01 13:37:41 +00002049 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2050 continue;
2051 } else {
2052 // We're in thumb-1 mode, so we must have something like:
2053 // %idx = tLSLri %idx, 2
2054 // %base = tLEApcrelJT
2055 // %t = tLDRr %idx, %base
2056 unsigned BaseReg = User.MI->getOperand(0).getReg();
James Molloy2bae8642016-10-22 09:58:37 +00002057
James Molloy70a3d6d2016-11-01 13:37:41 +00002058 if (User.MI->getIterator() == User.MI->getParent()->begin())
2059 continue;
2060 MachineInstr *Shift = User.MI->getPrevNode();
2061 if (Shift->getOpcode() != ARM::tLSLri ||
2062 Shift->getOperand(3).getImm() != 2 ||
2063 !Shift->getOperand(2).isKill())
2064 continue;
2065 IdxReg = Shift->getOperand(2).getReg();
2066 unsigned ShiftedIdxReg = Shift->getOperand(0).getReg();
Tim Northovera603c402015-05-31 19:22:07 +00002067
James Molloy70a3d6d2016-11-01 13:37:41 +00002068 MachineInstr *Load = User.MI->getNextNode();
2069 if (Load->getOpcode() != ARM::tLDRr)
2070 continue;
2071 if (Load->getOperand(1).getReg() != ShiftedIdxReg ||
2072 Load->getOperand(2).getReg() != BaseReg ||
2073 !Load->getOperand(1).isKill())
2074 continue;
2075
2076 // If we're in PIC mode, there should be another ADD following.
2077 if (isPositionIndependentOrROPI) {
2078 MachineInstr *Add = Load->getNextNode();
2079 if (Add->getOpcode() != ARM::tADDrr ||
2080 Add->getOperand(2).getReg() != Load->getOperand(0).getReg() ||
2081 Add->getOperand(3).getReg() != BaseReg ||
2082 !Add->getOperand(2).isKill())
2083 continue;
2084 if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
2085 continue;
2086
2087 Add->eraseFromParent();
2088 DeadSize += 2;
2089 } else {
2090 if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
2091 continue;
2092 }
2093
2094
2095 // Now safe to delete the load and lsl. The LEA will be removed later.
2096 CanDeleteLEA = true;
2097 Shift->eraseFromParent();
2098 Load->eraseFromParent();
2099 DeadSize += 4;
2100 }
2101
Tim Northovera603c402015-05-31 19:22:07 +00002102 DEBUG(dbgs() << "Shrink JT: " << *MI);
2103 MachineInstr *CPEMI = User.CPEMI;
2104 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
James Molloy70a3d6d2016-11-01 13:37:41 +00002105 if (!isThumb2)
2106 Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
2107
Tim Northovera603c402015-05-31 19:22:07 +00002108 MachineBasicBlock::iterator MI_JT = MI;
2109 MachineInstr *NewJTMI =
Chad Rosier620fb222014-12-12 23:27:40 +00002110 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
Tim Northovera603c402015-05-31 19:22:07 +00002111 .addReg(User.MI->getOperand(0).getReg(),
2112 getKillRegState(BaseRegKill))
2113 .addReg(IdxReg, getKillRegState(IdxRegKill))
2114 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2115 .addImm(CPEMI->getOperand(0).getImm());
2116 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
Evan Chenge64f48b2009-08-01 06:13:52 +00002117
Tim Northovera603c402015-05-31 19:22:07 +00002118 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2119 CPEMI->setDesc(TII->get(JTOpc));
Evan Chenge64f48b2009-08-01 06:13:52 +00002120
Tim Northovera603c402015-05-31 19:22:07 +00002121 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2122 NewJTMI->getOperand(0).setReg(ARM::PC);
2123 NewJTMI->getOperand(0).setIsKill(false);
2124
2125 if (CanDeleteLEA) {
2126 User.MI->eraseFromParent();
James Molloy70a3d6d2016-11-01 13:37:41 +00002127 DeadSize += isThumb2 ? 4 : 2;
Tim Northovera603c402015-05-31 19:22:07 +00002128
2129 // The LEA was eliminated, the TBB instruction becomes the only new user
2130 // of the jump table.
2131 User.MI = NewJTMI;
2132 User.MaxDisp = 4;
2133 User.NegOk = false;
2134 User.IsSoImm = false;
2135 User.KnownAlignment = false;
2136 } else {
2137 // The LEA couldn't be eliminated, so we must add another CPUser to
2138 // record the TBB or TBH use.
2139 int CPEntryIdx = JumpTableEntryIndices[JTI];
2140 auto &CPEs = CPEntries[CPEntryIdx];
David Majnemer562e8292016-08-12 00:18:03 +00002141 auto Entry =
2142 find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
Tim Northovera603c402015-05-31 19:22:07 +00002143 ++Entry->RefCount;
2144 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2145 }
Evan Chengc6d70ae2009-07-29 02:18:14 +00002146 }
Tim Northovera603c402015-05-31 19:22:07 +00002147
Sjoerd Meijer89217f82016-07-28 16:32:22 +00002148 unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2149 unsigned OrigSize = TII->getInstSizeInBytes(*MI);
Tim Northovera603c402015-05-31 19:22:07 +00002150 MI->eraseFromParent();
2151
2152 int Delta = OrigSize - NewSize + DeadSize;
2153 BBInfo[MBB->getNumber()].Size -= Delta;
2154 adjustBBOffsetsAfter(MBB);
2155
2156 ++NumTBs;
2157 MadeChange = true;
Evan Chengc6d70ae2009-07-29 02:18:14 +00002158 }
2159
2160 return MadeChange;
2161}
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002162
Jim Grosbach190e7b62012-03-23 23:07:03 +00002163/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
Jim Grosbach87b0f0d2009-11-16 18:55:47 +00002164/// jump tables always branch forwards, since that's what tbb and tbh need.
Jim Grosbach190e7b62012-03-23 23:07:03 +00002165bool ARMConstantIslands::reorderThumb2JumpTables() {
Jim Grosbach5d577142009-11-12 17:25:07 +00002166 bool MadeChange = false;
2167
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002168 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +00002169 if (!MJTI) return false;
Jim Grosbache4ba2aa2010-07-07 21:06:51 +00002170
Jim Grosbach5d577142009-11-12 17:25:07 +00002171 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2172 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2173 MachineInstr *MI = T2JumpTables[i];
Evan Cheng6cc775f2011-06-28 19:10:37 +00002174 const MCInstrDesc &MCID = MI->getDesc();
2175 unsigned NumOps = MCID.getNumOperands();
Tim Northover4998a472015-05-13 20:28:38 +00002176 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
Jim Grosbach5d577142009-11-12 17:25:07 +00002177 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2178 unsigned JTI = JTOP.getIndex();
2179 assert(JTI < JT.size());
2180
2181 // We prefer if target blocks for the jump table come after the jump
2182 // instruction so we can use TB[BH]. Loop through the target blocks
2183 // and try to adjust them such that that's true.
Jim Grosbach9785e592009-11-16 18:58:52 +00002184 int JTNumber = MI->getParent()->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002185 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2186 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2187 MachineBasicBlock *MBB = JTBBs[j];
Jim Grosbach9785e592009-11-16 18:58:52 +00002188 int DTNumber = MBB->getNumber();
Jim Grosbach5d577142009-11-12 17:25:07 +00002189
Jim Grosbach9785e592009-11-16 18:58:52 +00002190 if (DTNumber < JTNumber) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002191 // The destination precedes the switch. Try to move the block forward
2192 // so we have a positive offset.
2193 MachineBasicBlock *NewBB =
Jim Grosbach190e7b62012-03-23 23:07:03 +00002194 adjustJTTargetBlockForward(MBB, MI->getParent());
Jim Grosbach5d577142009-11-12 17:25:07 +00002195 if (NewBB)
Jim Grosbach43d21082009-11-14 20:10:18 +00002196 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
Jim Grosbach5d577142009-11-12 17:25:07 +00002197 MadeChange = true;
2198 }
2199 }
2200 }
2201
2202 return MadeChange;
2203}
2204
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002205MachineBasicBlock *ARMConstantIslands::
Jim Grosbach190e7b62012-03-23 23:07:03 +00002206adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
Jim Grosbach73ef80f2010-07-07 22:53:35 +00002207 // If the destination block is terminated by an unconditional branch,
Jim Grosbach5d577142009-11-12 17:25:07 +00002208 // try to move it; otherwise, create a new block following the jump
Jim Grosbach9785e592009-11-16 18:58:52 +00002209 // table that branches back to the actual target. This is a very simple
2210 // heuristic. FIXME: We can definitely improve it.
Craig Topper062a2ba2014-04-25 05:30:21 +00002211 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002212 SmallVector<MachineOperand, 4> Cond;
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002213 SmallVector<MachineOperand, 4> CondPrior;
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002214 MachineFunction::iterator BBi = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002215 MachineFunction::iterator OldPrior = std::prev(BBi);
Jim Grosbach43d21082009-11-14 20:10:18 +00002216
Jim Grosbach47d5e332009-11-16 17:10:56 +00002217 // If the block terminator isn't analyzable, don't try to move the block
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002218 bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
Jim Grosbach47d5e332009-11-16 17:10:56 +00002219
Jim Grosbachaf1ad302009-11-17 01:21:04 +00002220 // If the block ends in an unconditional branch, move it. The prior block
2221 // has to have an analyzable terminator for us to move this one. Be paranoid
Jim Grosbach9785e592009-11-16 18:58:52 +00002222 // and make sure we're not trying to move the entry block of the function.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002223 if (!B && Cond.empty() && BB != &MF->front() &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002224 !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
Jim Grosbach5d577142009-11-12 17:25:07 +00002225 BB->moveAfter(JTBB);
2226 OldPrior->updateTerminator();
Jim Grosbach43d21082009-11-14 20:10:18 +00002227 BB->updateTerminator();
Jim Grosbach9785e592009-11-16 18:58:52 +00002228 // Update numbering to account for the block being moved.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002229 MF->RenumberBlocks();
Jim Grosbach5d577142009-11-12 17:25:07 +00002230 ++NumJTMoved;
Craig Topper062a2ba2014-04-25 05:30:21 +00002231 return nullptr;
Jim Grosbach5d577142009-11-12 17:25:07 +00002232 }
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002233
2234 // Create a new MBB for the code after the jump BB.
2235 MachineBasicBlock *NewBB =
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002236 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
Duncan P. N. Exon Smith9f9559e2015-10-19 23:25:57 +00002237 MachineFunction::iterator MBBI = ++JTBB->getIterator();
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002238 MF->insert(MBBI, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002239
2240 // Add an unconditional branch from NewBB to BB.
2241 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2242 // correspond directly to anything in the source.
James Molloy70a3d6d2016-11-01 13:37:41 +00002243 if (isThumb2)
2244 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
2245 .addMBB(BB)
Diana Picusbd66b7d2017-01-20 08:15:24 +00002246 .add(predOps(ARMCC::AL));
James Molloy70a3d6d2016-11-01 13:37:41 +00002247 else
2248 BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
2249 .addMBB(BB)
Diana Picusbd66b7d2017-01-20 08:15:24 +00002250 .add(predOps(ARMCC::AL));
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002251
Jim Grosbach43d21082009-11-14 20:10:18 +00002252 // Update internal data structures to account for the newly inserted MBB.
Jakob Stoklund Olesen2a759972011-12-12 18:16:53 +00002253 MF->RenumberBlocks(NewBB);
Jim Grosbach43d21082009-11-14 20:10:18 +00002254
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002255 // Update the CFG.
2256 NewBB->addSuccessor(BB);
Cong Houd97c1002015-12-01 05:29:22 +00002257 JTBB->replaceSuccessor(BB, NewBB);
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002258
Jim Grosbach5d577142009-11-12 17:25:07 +00002259 ++NumJTInserted;
Jim Grosbach8d92ec42009-11-11 02:47:19 +00002260 return NewBB;
2261}